From 1f66ca722e46dc68a9f3fed97710d80702306bd4 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 08:48:27 +0700 Subject: [PATCH 01/25] hmm? --- old-types.d.ts | 1996 ++++++++++++++++++++++++++++++++++++++++ src/Cloud.ts | 10 +- src/ParseObject.ts | 80 +- src/ParseQuery.ts | 25 +- src/ParseSchema.ts | 28 +- src/ParseUser.ts | 11 +- types/Cloud.d.ts | 8 +- types/ParseObject.d.ts | 40 +- types/ParseQuery.d.ts | 4 +- types/ParseSchema.d.ts | 4 +- types/ParseUser.d.ts | 6 +- types/index.d.ts | 132 ++- types/tests.ts | 151 ++- 13 files changed, 2413 insertions(+), 82 deletions(-) create mode 100644 old-types.d.ts diff --git a/old-types.d.ts b/old-types.d.ts new file mode 100644 index 000000000..df3c7045f --- /dev/null +++ b/old-types.d.ts @@ -0,0 +1,1996 @@ +/// +/// +/// + +import { EventEmitter } from "events"; + +declare enum ErrorCode { + /** Error code indicating some error other than those enumerated here */ + OTHER_CAUSE = -1, + /** Error code indicating that something has gone wrong with the server. */ + INTERNAL_SERVER_ERROR = 1, + /** Error code indicating the connection to the Parse servers failed. */ + CONNECTION_FAILED = 100, + /** Error code indicating the specified object doesn't exist. */ + OBJECT_NOT_FOUND = 101, + /** + * Error code indicating you tried to query with a datatype that doesn't + * support it, like exact matching an array or object. + */ + INVALID_QUERY = 102, + /* + * Error code indicating a missing or invalid classname. Classnames are + * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the + * only valid characters. + */ + INVALID_CLASS_NAME = 103, + /** Error code indicating an unspecified object id. */ + MISSING_OBJECT_ID = 104, + /** + * Error code indicating an invalid key name. Keys are case-sensitive. They + * must start with a letter, and a-zA-Z0-9_ are the only valid characters. + */ + INVALID_KEY_NAME = 105, + /** + * Error code indicating a malformed pointer. You should not see this unless + * you have been mucking about changing internal Parse code. + */ + INVALID_POINTER = 106, + /* + * Error code indicating that badly formed JSON was received upstream. This + * either indicates you have done something unusual with modifying how + * things encode to JSON, or the network is failing badly. + */ + INVALID_JSON = 107, + /** + * Error code indicating that the feature you tried to access is only + * available internally for testing purposes. + */ + COMMAND_UNAVAILABLE = 108, + /** You must call Parse.initialize before using the Parse library. */ + NOT_INITIALIZED = 109, + /** Error code indicating that a field was set to an inconsistent type. */ + INCORRECT_TYPE = 111, + /** + * Error code indicating an invalid channel name. A channel name is either + * an empty string (the broadcast channel) or contains only a-zA-Z0-9_ + * characters and starts with a letter. + */ + INVALID_CHANNEL_NAME = 112, + /** Error code indicating that push is misconfigured. */ + PUSH_MISCONFIGURED = 115, + /** Error code indicating that the object is too large. */ + OBJECT_TOO_LARGE = 116, + /** Error code indicating that the operation isn't allowed for clients. */ + OPERATION_FORBIDDEN = 119, + /** Error code indicating the result was not found in the cache. */ + CACHE_MISS = 120, + /** Error code indicating that an invalid key was used in a nested JSONObject. */ + INVALID_NESTED_KEY = 121, + /** + * Error code indicating that an invalid filename was used for ParseFile. + * A valid file name contains only a-zA-Z0-9_. characters and is between 1 + * and 128 characters. + */ + INVALID_FILE_NAME = 122, + /** Error code indicating an invalid ACL was provided. */ + INVALID_ACL = 123, + /** + * Error code indicating that the request timed out on the server. Typically + * this indicates that the request is too expensive to run. + */ + TIMEOUT = 124, + /** Error code indicating that the email address was invalid. */ + INVALID_EMAIL_ADDRESS = 125, + /** Error code indicating a missing content type. */ + MISSING_CONTENT_TYPE = 126, + /** Error code indicating a missing content length. */ + MISSING_CONTENT_LENGTH = 127, + /** Error code indicating an invalid content length. */ + INVALID_CONTENT_LENGTH = 128, + /** Error code indicating a file that was too large. */ + FILE_TOO_LARGE = 129, + /** Error code indicating an error saving a file. */ + FILE_SAVE_ERROR = 130, + /** + * Error code indicating that a unique field was given a value that is + * already taken. + */ + DUPLICATE_VALUE = 137, + /** Error code indicating that a role's name is invalid. */ + INVALID_ROLE_NAME = 139, + /** + * Error code indicating that an application quota was exceeded. + * Upgrade to resolve. + */ + EXCEEDED_QUOTA = 140, + /** Error code indicating that a Cloud Code script failed. */ + SCRIPT_FAILED = 141, + /** Error code indicating that a Cloud Code validation failed. */ + VALIDATION_ERROR = 142, + /** Error code indicating that invalid image data was provided. */ + INVALID_IMAGE_DATA = 150, + /** Error code indicating an unsaved file. */ + UNSAVED_FILE_ERROR = 151, + /** Error code indicating an invalid push time. */ + INVALID_PUSH_TIME_ERROR = 152, + /** Error code indicating an error deleting a file. */ + FILE_DELETE_ERROR = 153, + /** Error code indicating that the application has exceeded its request limit. */ + REQUEST_LIMIT_EXCEEDED = 155, + /** + * Error code indicating that the request was a duplicate and has been discarded due to + * idempotency rules. + */ + DUPLICATE_REQUEST = 159, + /** Error code indicating an invalid event name. */ + INVALID_EVENT_NAME = 160, + /** Error code indicating an error deleting an unnamed file. */ + FILE_DELETE_UNNAMED_ERROR = 161, + /** Error code indicating that the username is missing or empty. */ + USERNAME_MISSING = 200, + /** Error code indicating that the password is missing or empty. */ + PASSWORD_MISSING = 201, + /** Error code indicating that the username has already been taken. */ + USERNAME_TAKEN = 202, + /** Error code indicating that the email has already been taken. */ + EMAIL_TAKEN = 203, + /** Error code indicating that the email is missing, but must be specified. */ + EMAIL_MISSING = 204, + /** Error code indicating that a user with the specified email was not found. */ + EMAIL_NOT_FOUND = 205, + /** + * Error code indicating that a user object without a valid session could + * not be altered. + */ + SESSION_MISSING = 206, + /** Error code indicating that a user can only be created through signup. */ + MUST_CREATE_USER_THROUGH_SIGNUP = 207, + /** + * Error code indicating that an an account being linked is already linked + * to another user. + */ + ACCOUNT_ALREADY_LINKED = 208, + /** Error code indicating that the current session token is invalid. */ + INVALID_SESSION_TOKEN = 209, + /** Error code indicating an error enabling or verifying MFA */ + MFA_ERROR = 210, + /** Error code indicating that a valid MFA token must be provided */ + MFA_TOKEN_REQUIRED = 211, + /** + * Error code indicating that a user cannot be linked to an account because + * that account's id could not be found. + */ + LINKED_ID_MISSING = 250, + /** + * Error code indicating that a user with a linked (e.g. Facebook) account + * has an invalid session. + */ + INVALID_LINKED_SESSION = 251, + /** + * Error code indicating that a service being linked (e.g. Facebook or + * Twitter) is unsupported. + */ + UNSUPPORTED_SERVICE = 252, + /** Error code indicating an invalid operation occured on schema */ + INVALID_SCHEMA_OPERATION = 255, + /** + * Error code indicating that there were multiple errors. Aggregate errors + * have an "errors" property, which is an array of error objects with more + * detail about each error that occurred. + */ + AGGREGATE_ERROR = 600, + /** Error code indicating the client was unable to read an input file. */ + FILE_READ_ERROR = 601, + /* + * Error code indicating a real error code is unavailable because + * we had to use an XDomainRequest object to allow CORS requests in + * Internet Explorer, which strips the body from HTTP responses that have + * a non-2XX status code. + */ + X_DOMAIN_REQUEST = 602, +} + +declare global { + namespace Parse { + let applicationId: string; + let javaScriptKey: string | undefined; + let liveQueryServerURL: string; + let masterKey: string | undefined; + let serverAuthToken: string | undefined; + let serverAuthType: string | undefined; + let serverURL: string; + let secret: string; + let idempotency: boolean; + let encryptedUser: boolean; + + interface BatchSizeOption { + batchSize?: number | undefined; + } + + interface CascadeSaveOption { + /** If `false`, nested objects will not be saved (default is `true`). */ + cascadeSave?: boolean | undefined; + } + + interface SuccessOption { + success?: Function | undefined; + } + + interface ErrorOption { + error?: Function | undefined; + } + + interface ContextOption { + context?: { [key: string]: any }; + } + + interface FullOptions { + success?: Function | undefined; + error?: Function | undefined; + useMasterKey?: boolean | undefined; + sessionToken?: string | undefined; + installationId?: string | undefined; + progress?: Function | undefined; + /** + * logIn will default to POST instead of GET method since + * version 3.0.0 for security reasons. + * If you need to use GET set this to `false`. + */ + usePost?: boolean; + } + + interface RequestOptions { + useMasterKey?: boolean | undefined; + sessionToken?: string | undefined; + installationId?: string | undefined; + batchSize?: number | undefined; + include?: string | string[] | undefined; + progress?: Function | undefined; + } + + interface SuccessFailureOptions extends SuccessOption, ErrorOption {} + + interface SignUpOptions { + useMasterKey?: boolean | undefined; + installationId?: string | undefined; + } + + interface SessionTokenOption { + sessionToken?: string | undefined; + } + + interface WaitOption { + /** + * Set to true to wait for the server to confirm success + * before triggering an event. + */ + wait?: boolean | undefined; + } + + interface UseMasterKeyOption { + /** + * In Cloud Code and Node only, causes the Master Key to be used for this request. + */ + useMasterKey?: boolean | undefined; + } + + /** + * https://github.com/parse-community/Parse-SDK-JS/pull/1294/files + * feat: Add option to return raw json from queries + */ + interface RawJSONOptions { + /** (3.0.0+) json: Return raw json without converting to Parse.Object */ + json?: boolean; + } + interface ScopeOptions extends SessionTokenOption, UseMasterKeyOption {} + + interface SilentOption { + /** + * Set to true to avoid firing the event. + */ + silent?: boolean | undefined; + } + + interface Pointer { + __type: string; + className: string; + objectId: string; + } + + interface AuthData { + [key: string]: any; + } + + /** + * Interface declaration for Authentication Providers + * https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html + */ + interface AuthProvider { + /** + * Called when _linkWith isn't passed authData. Handle your own authentication here. + */ + authenticate: () => void; + /** + * (Optional) Called when service is unlinked. Handle any cleanup here. + */ + deauthenticate?: (() => void) | undefined; + /** + * Unique identifier for this Auth Provider. + */ + getAuthType: () => string; + /** + * Called when auth data is syncronized. Can be used to determine if authData is still valid + */ + restoreAuthentication: () => boolean; + } + + interface BaseAttributes { + createdAt: Date; + objectId: string; + updatedAt: Date; + } + + interface CommonAttributes { + ACL: ACL; + } + + interface JSONBaseAttributes { + createdAt: string; + objectId: string; + updatedAt: string; + } + + /** + * Creates a new ACL. + * If no argument is given, the ACL has no permissions for anyone. + * If the argument is a Parse.User, the ACL will have read and write + * permission for only that user. + * If the argument is any other JSON object, that object will be interpretted + * as a serialized ACL created with toJSON(). + * @see Parse.Object#setACL + * + *

An ACL, or Access Control List can be added to any + * Parse.Object to restrict access to only a subset of users + * of your application.

+ */ + class ACL { + permissionsById: any; + + constructor(arg1?: any); + + setPublicReadAccess(allowed: boolean): void; + getPublicReadAccess(): boolean; + + setPublicWriteAccess(allowed: boolean): void; + getPublicWriteAccess(): boolean; + + setReadAccess(userId: User | string, allowed: boolean): void; + getReadAccess(userId: User | string): boolean; + + setWriteAccess(userId: User | string, allowed: boolean): void; + getWriteAccess(userId: User | string): boolean; + + setRoleReadAccess(role: Role | string, allowed: boolean): void; + getRoleReadAccess(role: Role | string): boolean; + + setRoleWriteAccess(role: Role | string, allowed: boolean): void; + getRoleWriteAccess(role: Role | string): boolean; + + toJSON(): any; + } + + /** + * A Parse.File is a local representation of a file that is saved to the Parse + * cloud. + * @param name The file's name. This will be prefixed by a unique + * value once the file has finished saving. The file name must begin with + * an alphanumeric character, and consist of alphanumeric characters, + * periods, spaces, underscores, or dashes. + * @param data The data for the file, as either: + * 1. an Array of byte value Numbers, or + * 2. an Object like { base64: "..." } with a base64-encoded String. + * 3. a File object selected with a file upload control. (3) only works + * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+. + * For example:
+         * var fileUploadControl = $("#profilePhotoFileUpload")[0];
+         * if (fileUploadControl.files.length > 0) {
+         *   var file = fileUploadControl.files[0];
+         *   var name = "photo.jpg";
+         *   var parseFile = new Parse.File(name, file);
+         *   parseFile.save().then(function() {
+         *     // The file has been saved to Parse.
+         *   }, function(error) {
+         *     // The file either could not be read, or could not be saved to Parse.
+         *   });
+         * }
+ * @param type Optional Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + */ + class File { + constructor( + name: string, + data: number[] | { base64: string } | { size: number; type: string } | { uri: string }, + type?: string, + ); + /** + * Return the data for the file, downloading it if not already present. + * Data is present if initialized with Byte Array, Base64 or Saved with Uri. + * Data is cleared if saved with File object selected with a file upload control + * + * @returns Promise that is resolved with base64 data + */ + getData(): Promise; + url(options?: { forceSecure?: boolean | undefined }): string; + metadata(): Record; + tags(): Record; + name(): string; + save(options?: FullOptions): Promise; + cancel(): void; + destroy(options?: FullOptions): Promise; + toJSON(): { __type: string; name: string; url: string }; + equals(other: File): boolean; + setMetadata(metadata: Record): void; + addMetadata(key: string, value: any): void; + setTags(tags: Record): void; + addTag(key: string, value: any): void; + readonly _url: string; + } + + /** + * Creates a new GeoPoint with any of the following forms:
+ *
+         *   new GeoPoint(otherGeoPoint)
+         *   new GeoPoint(30, 30)
+         *   new GeoPoint([30, 30])
+         *   new GeoPoint({latitude: 30, longitude: 30})
+         *   new GeoPoint()  // defaults to (0, 0)
+         *   
+ * + *

Represents a latitude / longitude point that may be associated + * with a key in a ParseObject or used as a reference point for geo queries. + * This allows proximity-based queries on the key.

+ * + *

Only one key in a class may contain a GeoPoint.

+ * + *

Example:

+         *   var point = new Parse.GeoPoint(30.0, -20.0);
+         *   var object = new Parse.Object("PlaceObject");
+         *   object.set("location", point);
+         *   object.save();

+ */ + class GeoPoint { + latitude: number; + longitude: number; + + constructor(latitude: number, longitude: number); + constructor(coords?: { latitude: number; longitude: number } | [number, number]); + + current(options?: SuccessFailureOptions): GeoPoint; + radiansTo(point: GeoPoint): number; + kilometersTo(point: GeoPoint): number; + milesTo(point: GeoPoint): number; + toJSON(): any; + } + + /** + * A class that is used to access all of the children of a many-to-many relationship. + * Each instance of Parse.Relation is associated with a particular parent object and key. + */ + class Relation { + parent: S; + key: string; + targetClassName: string; + + constructor(parent?: S, key?: string); + + // Adds a Parse.Object or an array of Parse.Objects to the relation. + add(object: T | T[]): void; + + // Returns a Parse.Query that is limited to objects in this relation. + query(): Query; + + // Removes a Parse.Object or an array of Parse.Objects from this relation. + remove(object: T | T[]): void; + + toJSON(): any; + } + + interface Attributes { + [key: string]: any; + } + + /** + * Creates a new model with defined attributes. A client id (cid) is + * automatically generated and assigned for you. + * + *

You won't normally call this method directly. It is recommended that + * you use a subclass of Parse.Object instead, created by calling + * extend.

+ * + *

However, if you don't want to use a subclass, or aren't sure which + * subclass is appropriate, you can use this form:

+         *     var object = new Parse.Object("ClassName");
+         * 
+ * That is basically equivalent to:
+         *     var MyClass = Parse.Object.extend("ClassName");
+         *     var object = new MyClass();
+         * 

+ * + * @param attributes The initial set of data to store in the object. + * @param options The options for this object instance. + * @see Parse.Object.extend + * + * Creates a new model with defined attributes. + */ + interface Object { + id: string; + createdAt: Date; + updatedAt: Date; + attributes: T; + className: string; + + add extends any[] ? K : never }[keyof T]>( + attr: K, + item: NonNullable[number], + ): this | false; + addAll extends any[] ? K : never }[keyof T]>( + attr: K, + items: NonNullable, + ): this | false; + addAllUnique: this["addAll"]; + addUnique: this["add"]; + clear(options: any): any; + clone(): this; + destroy(options?: Object.DestroyOptions): Promise; + /** EventuallyQueue API; added in version 3.0.0 */ + destroyEventually(options?: Object.DestroyOptions): Promise; + dirty(attr?: Extract): boolean; + dirtyKeys(): string[]; + equals(other: T): boolean; + escape(attr: Extract): string; + existed(): boolean; + exists(options?: RequestOptions): Promise; + fetch(options?: Object.FetchOptions): Promise; + fetchFromLocalDatastore(): Promise; + fetchWithInclude>( + keys: K | Array, + options?: RequestOptions, + ): Promise; + get>(attr: K): T[K]; + getACL(): ACL | undefined; + has(attr: Extract): boolean; + increment(attr: Extract, amount?: number): this | false; + decrement(attr: Extract, amount?: number): this | false; + initialize(): void; + isDataAvailable(): boolean; + isNew(): boolean; + isPinned(): Promise; + isValid(): boolean; + newInstance(): this; + op(attr: Extract): any; + pin(): Promise; + pinWithName(name: string): Promise; + relation = Extract>( + attr: T[K] extends Relation ? K : never, + ): Relation; + remove: this["add"]; + removeAll: this["addAll"]; + revert(...keys: Array>): void; + // "Pick | T" is a trick to keep IntelliSense working, see: + // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/3bdadbf9583c2335197c7e999b9a30880e055f62/types/react/index.d.ts#L482 + save>( + attrs?: Pick | T | null, + options?: Object.SaveOptions, + ): Promise; + save>( + key: K, + value: T[K] extends undefined ? never : T[K], + options?: Object.SaveOptions, + ): Promise; + /** EventuallyQueue API; added in version 3.0.0 */ + saveEventually(options?: Object.SaveOptions): Promise; + set>(attrs: Pick | T, options?: Object.SetOptions): this | false; + set>( + key: K, + value: T[K] extends undefined ? never : T[K], + options?: Object.SetOptions, + ): this | false; + setACL(acl: ACL, options?: SuccessFailureOptions): this | false; + toJSON(): Object.ToJSON & JSONBaseAttributes; + toPointer(): Pointer; + unPin(): Promise; + unPinWithName(name: string): Promise; + unset(attr: Extract, options?: any): this | false; + validate(attrs: Attributes, options?: SuccessFailureOptions): Error | false; + } + interface ObjectStatic { + createWithoutData(id: string): T; + destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; + extend(className: string | { className: string }, protoProps?: any, classProps?: any): any; + fetchAll(list: T[], options: Object.FetchAllOptions): Promise; + fetchAllIfNeeded(list: T[], options?: Object.FetchAllOptions): Promise; + fetchAllIfNeededWithInclude( + list: T[], + keys: keyof T["attributes"] | Array, + options?: RequestOptions, + ): Promise; + fetchAllWithInclude( + list: T[], + keys: keyof T["attributes"] | Array, + options?: RequestOptions, + ): Promise; + fromJSON(json: any, override?: boolean): T; + pinAll(objects: Object[]): Promise; + pinAllWithName(name: string, objects: Object[]): Promise; + registerSubclass(className: string, clazz: new(options?: any) => T): void; + saveAll(list: T, options?: Object.SaveAllOptions): Promise; + unPinAll(objects: Object[]): Promise; + unPinAllObjects(): Promise; + unPinAllObjectsWithName(name: string): Promise; + unPinAllWithName(name: string, objects: Object[]): Promise; + } + interface ObjectConstructor extends ObjectStatic { + new(className: string, attributes: T, options?: any): Object; + new(className?: string, attributes?: Attributes, options?: any): Object; + } + const Object: ObjectConstructor; + + namespace Object { + interface DestroyOptions extends SuccessFailureOptions, WaitOption, ScopeOptions {} + + interface DestroyAllOptions extends BatchSizeOption, ScopeOptions {} + + interface FetchAllOptions extends SuccessFailureOptions, ScopeOptions {} + + interface FetchOptions extends SuccessFailureOptions, ScopeOptions {} + + interface SaveOptions + extends CascadeSaveOption, SuccessFailureOptions, SilentOption, ScopeOptions, ContextOption, WaitOption + {} + + interface SaveAllOptions extends BatchSizeOption, ScopeOptions {} + + interface SetOptions extends ErrorOption, SilentOption { + promise?: any; + } + + // From https://github.com/parse-community/Parse-SDK-JS/blob/master/src/encode.js + type Encode = T extends Object ? ReturnType | Pointer + : T extends ACL | GeoPoint | Polygon | Relation | File ? ReturnType + : T extends Date ? { __type: "Date"; iso: string } + : T extends RegExp ? string + : T extends Array + // This recursion is unsupported in <=3.6 + ? Array> + : T extends object ? ToJSON + : T; + + type ToJSON = { + [K in keyof T]: Encode; + }; + } + + class Polygon { + constructor(arg1: GeoPoint[] | number[][]); + containsPoint(point: GeoPoint): boolean; + equals(other: any): boolean; + toJSON(): any; + } + + /** + * Every Parse application installed on a device registered for + * push notifications has an associated Installation object. + */ + interface Installation extends Object { + badge: any; + channels: string[]; + timeZone: any; + deviceType: string; + pushType: string; + installationId: string; + deviceToken: string; + channelUris: string; + appName: string; + appVersion: string; + parseVersion: string; + appIdentifier: string; + } + interface InstallationConstructor extends ObjectStatic { + new(attributes: T): Installation; + new(): Installation; + } + const Installation: InstallationConstructor; + + /** + * Creates a new parse Parse.Query for the given Parse.Object subclass. + * @param objectClass - + * An instance of a subclass of Parse.Object, or a Parse className string. + * + *

Parse.Query defines a query that is used to fetch Parse.Objects. The + * most common use case is finding all objects that match a query through the + * find method. For example, this sample code fetches all objects + * of class MyClass. It calls a different function depending on + * whether the fetch succeeded or not. + * + *

+         * var query = new Parse.Query(MyClass);
+         * query.find({
+         *   success: function(results) {
+         *     // results is an array of Parse.Object.
+         *   },
+         *
+         *   error: function(error) {
+         *     // error is an instance of Parse.Error.
+         *   }
+         * });

+ * + *

A Parse.Query can also be used to retrieve a single object whose id is + * known, through the get method. For example, this sample code fetches an + * object of class MyClass and id myId. It calls a + * different function depending on whether the fetch succeeded or not. + * + *

+         * var query = new Parse.Query(MyClass);
+         * query.get(myId, {
+         *   success: function(object) {
+         *     // object is an instance of Parse.Object.
+         *   },
+         *
+         *   error: function(object, error) {
+         *     // error is an instance of Parse.Error.
+         *   }
+         * });

+ * + *

A Parse.Query can also be used to count the number of objects that match + * the query without retrieving all of those objects. For example, this + * sample code counts the number of objects of the class MyClass + *

+         * var query = new Parse.Query(MyClass);
+         * query.count({
+         *   success: function(number) {
+         *     // There are number instances of MyClass.
+         *   },
+         *
+         *   error: function(error) {
+         *     // error is an instance of Parse.Error.
+         *   }
+         * });

+ */ + class Query { + objectClass: any; + className: string; + + constructor(objectClass: string | (new(...args: any[]) => T | Object)); + + static and(...args: Array>): Query; + static fromJSON(className: string | (new() => U), json: any): Query; + static nor(...args: Array>): Query; + static or(...var_args: Array>): Query; + + addAscending(key: K | K[]): this; + addDescending(key: K | K[]): this; + ascending(key: K | K[]): this; + aggregate(pipeline: Query.AggregationOptions | Query.AggregationOptions[]): Promise; + containedBy( + key: K, + values: Array, + ): this; + containedIn( + key: K, + values: Array, + ): this; + contains(key: K, substring: string): this; + containsAll(key: K, values: any[]): this; + containsAllStartingWith( + key: K, + values: any[], + ): this; + count(options?: Query.CountOptions): Promise; + descending(key: K | K[]): this; + doesNotExist(key: K): this; + doesNotMatchKeyInQuery< + U extends Object, + K extends keyof T["attributes"] | keyof BaseAttributes, + X extends Extract, + >(key: K, queryKey: X, query: Query): this; + doesNotMatchQuery(key: K, query: Query): this; + distinct(key: K): Promise; + eachBatch(callback: (objs: T[]) => PromiseLike | void, options?: Query.BatchOptions): Promise; + each(callback: (obj: T) => PromiseLike | void, options?: Query.BatchOptions): Promise; + hint(value: string | object): this; + explain(explain: boolean): this; + map( + callback: (currentObject: T, index: number, query: Query) => PromiseLike | U, + options?: Query.BatchOptions, + ): Promise; + reduce( + callback: (accumulator: T, currentObject: T, index: number) => PromiseLike | T, + initialValue?: undefined, + options?: Query.BatchOptions, + ): Promise; + reduce( + callback: (accumulator: U, currentObject: T, index: number) => PromiseLike | U, + initialValue: U, + options?: Query.BatchOptions, + ): Promise; + filter( + callback: (currentObject: T, index: number, query: Query) => PromiseLike | boolean, + options?: Query.BatchOptions, + ): Promise; + endsWith(key: K, suffix: string): this; + equalTo( + key: K, + value: + | T["attributes"][K] + | (T["attributes"][K] extends Object ? Pointer + : T["attributes"][K] extends Array ? E + : never), + ): this; + exclude(...keys: K[]): this; + exists(key: K): this; + find(options?: Query.FindOptions): Promise; + findAll(options?: Query.BatchOptions): Promise; + first(options?: Query.FirstOptions): Promise; + fromNetwork(): this; + fromLocalDatastore(): this; + fromPin(): this; + fromPinWithName(name: string): this; + cancel(): this; + fullText( + key: K, + value: string, + options?: Query.FullTextOptions, + ): this; + get(objectId: string, options?: Query.GetOptions): Promise; + greaterThan( + key: K, + value: T["attributes"][K], + ): this; + greaterThanOrEqualTo( + key: K, + value: T["attributes"][K], + ): this; + include(...key: K[]): this; + include(key: K[]): this; + includeAll(): Query; + lessThan(key: K, value: T["attributes"][K]): this; + lessThanOrEqualTo( + key: K, + value: T["attributes"][K], + ): this; + limit(n: number): Query; + matches( + key: K, + regex: RegExp, + modifiers?: string, + ): this; + matchesKeyInQuery< + U extends Object, + K extends keyof T["attributes"], + X extends Extract, + >(key: K, queryKey: X, query: Query): this; + matchesQuery(key: K, query: Query): this; + near(key: K, point: GeoPoint): this; + notContainedIn( + key: K, + values: Array, + ): this; + notEqualTo( + key: K, + value: + | T["attributes"][K] + | (T["attributes"][K] extends Object ? Pointer + : T["attributes"][K] extends Array ? E + : never), + ): this; + polygonContains(key: K, point: GeoPoint): this; + select(...keys: K[]): this; + select(keys: K[]): this; + skip(n: number): Query; + sortByTextScore(): this; + startsWith(key: K, prefix: string): this; + subscribe(sessionToken?: string): Promise; + toJSON(): any; + withJSON(json: any): this; + withCount(includeCount?: boolean): this; + withinGeoBox( + key: K, + southwest: GeoPoint, + northeast: GeoPoint, + ): this; + withinKilometers( + key: K, + point: GeoPoint, + maxDistance: number, + sorted?: boolean, + ): this; + withinMiles( + key: K, + point: GeoPoint, + maxDistance: number, + sorted?: boolean, + ): this; + withinPolygon(key: K, points: number[][]): this; + withinRadians( + key: K, + point: GeoPoint, + maxDistance: number, + ): this; + } + + namespace Query { + interface EachOptions extends SuccessFailureOptions, ScopeOptions {} + interface CountOptions extends SuccessFailureOptions, ScopeOptions {} + interface FindOptions extends SuccessFailureOptions, ScopeOptions, RawJSONOptions {} + interface FirstOptions extends SuccessFailureOptions, ScopeOptions, RawJSONOptions {} + interface GetOptions extends SuccessFailureOptions, ScopeOptions, RawJSONOptions {} + + // According to http://docs.parseplatform.org/rest/guide/#aggregate-queries + interface AggregationOptions { + group?: (Record & { objectId?: string }) | undefined; + match?: Record | undefined; + project?: Record | undefined; + limit?: number | undefined; + skip?: number | undefined; + // Sort documentation https://docs.mongodb.com/v3.2/reference/operator/aggregation/sort/#pipe._S_sort + sort?: Record | undefined; + // Sample documentation: https://docs.mongodb.com/v3.2/reference/operator/aggregation/sample/ + sample?: { size: number } | undefined; + // Count documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/count/ + count?: string | undefined; + // Lookup documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ + lookup?: + | { + from: string; + localField: string; + foreignField: string; + as: string; + } + | { + from: string; + let?: Record; + pipeline: Record; + as: string; + } + | undefined; + // Graph Lookup documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/ + graphLookup?: + | { + from: string; + startWith?: string; + connectFromField: string; + connectToField: string; + as: string; + maxDepth?: number; + depthField?: string; + restrictSearchWithMatch?: Record; + } + | undefined; + // Facet documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/facet/ + facet?: Record>> | undefined; + // Unwind documentation: https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind/ + unwind?: + | { + path: string; + includeArrayIndex?: string; + preserveNullAndEmptyArrays?: boolean; + } + | string + | undefined; + } + + // According to https://parseplatform.org/Parse-SDK-JS/api/2.1.0/Parse.Query.html#fullText + interface FullTextOptions { + language?: string | undefined; + caseSensitive?: boolean | undefined; + diacriticSensitive?: boolean | undefined; + } + + interface BatchOptions extends FullOptions { + batchSize?: number | undefined; + } + } + + /** + * Represents a LiveQuery Subscription. + * + * @see https://docs.parseplatform.org/js/guide/#live-queries + * @see NodeJS.EventEmitter + * + * Events list + * --- + * `open` - when you call `query.subscribe()`, we send a subscribe request to + * the LiveQuery server, when we get the confirmation from the LiveQuery server, + * this event will be emitted. When the client loses WebSocket connection to the + * LiveQuery server, we will try to auto reconnect the LiveQuery server. If we + * reconnect the LiveQuery server and successfully resubscribe the ParseQuery, + * you'll also get this event. + * + * ``` + * subscription.on('open', () => {}); + * ``` + * --- + * `create` - when a new ParseObject is created and it fulfills the ParseQuery you subscribe, + * you'll get this event. The object is the ParseObject which is created. + * + * ``` + * subscription.on('create', (object: Parse.Object) => {}); + * ``` + * --- + * `update` event - when an existing ParseObject which fulfills the ParseQuery you subscribe + * is updated (The ParseObject fulfills the ParseQuery before and after changes), + * you'll get this event. The object is the ParseObject which is updated. + * Its content is the latest value of the ParseObject. + * + * ``` + * subscription.on('update', (object: Parse.Object) => {}); + * ``` + * --- + * `enter` event - when an existing ParseObject's old value doesn't fulfill the ParseQuery + * but its new value fulfills the ParseQuery, you'll get this event. The object is the + * ParseObject which enters the ParseQuery. Its content is the latest value of the ParseObject. + * + * ``` + * subscription.on('enter', (object: Parse.Object) => {}); + * ``` + * --- + * `update` event - when an existing ParseObject's old value fulfills the ParseQuery but its new value + * doesn't fulfill the ParseQuery, you'll get this event. The object is the ParseObject + * which leaves the ParseQuery. Its content is the latest value of the ParseObject. + * + * ``` + * subscription.on('leave', (object: Parse.Object) => {}); + * ``` + * --- + * `delete` event - when an existing ParseObject which fulfills the ParseQuery is deleted, you'll + * get this event. The object is the ParseObject which is deleted. + * + * ``` + * subscription.on('delete', (object: Parse.Object) => {}); + * ``` + * --- + * `close` event - when the client loses the WebSocket connection to the LiveQuery + * server and we stop receiving events, you'll get this event. + * + * ``` + * subscription.on('close', () => {}); + * ``` + */ + class LiveQuerySubscription extends EventEmitter { + /** + * Creates an instance of LiveQuerySubscription. + * + * @param id + * @param query + * @param [sessionToken] + */ + constructor(id: string, query: string, sessionToken?: string); + + on( + event: "open" | "create" | "update" | "enter" | "leave" | "delete" | "close", + listener: (object: Object) => void, + ): this; + + /** + * Closes the subscription. + */ + unsubscribe(): void; + } + + /** + * The LiveQuery namespace is basically an EventEmitter + * (source : https://github.com/parse-community/Parse-SDK-JS/blob/8115e959533d1676fe5e5551bc81888b21fc12ef/src/ParseLiveQuery.js) + * https://docs.parseplatform.org/js/guide/#websocket-status + */ + namespace LiveQuery { + function on( + event: "open" | "close", + /** When we establish ('open') or lose the WebSocket connection to the LiveQuery server, you’ll get this event */ + listener: () => void, + ): void; + function on( + event: "error", + /** When some network error or LiveQuery server error happens, you’ll get this event. */ + listener: (error: any) => void, + ): void; + } + + /** + * Represents a Role on the Parse server. Roles represent groupings of + * Users for the purposes of granting permissions (e.g. specifying an ACL + * for an Object). Roles are specified by their sets of child users and + * child roles, all of which are granted any permissions that the parent + * role has. + * + *

Roles must have a name (which cannot be changed after creation of the + * role), and must specify an ACL.

+ * A Parse.Role is a local representation of a role persisted to the Parse + * cloud. + */ + interface Role extends Object { + getRoles(): Relation; + getUsers(): Relation; + getName(): string; + setName(name: string, options?: SuccessFailureOptions): any; + } + interface RoleConstructor extends ObjectStatic { + new(name: string, acl: ACL): Role>; + new(name: string, acl: ACL): Role; + } + const Role: RoleConstructor; + + class Config { + static get(options?: UseMasterKeyOption): Promise; + static current(): Config; + static save(attr: any, options?: { [attr: string]: boolean }): Promise; + + get(attr: string): any; + escape(attr: string): any; + } + + interface Session extends Object { + getSessionToken(): string; + isCurrentSessionRevocable(): boolean; + } + interface SessionConstructor extends ObjectStatic { + new(attributes: T): Session; + new(): Session; + + current(): Promise; + } + const Session: SessionConstructor; + + /** + *

A Parse.User object is a local representation of a user persisted to the + * Parse cloud. This class is a subclass of a Parse.Object, and retains the + * same functionality of a Parse.Object, but also extends it with various + * user specific methods, like authentication, signing up, and validation of + * uniqueness.

+ */ + interface User extends Object { + signUp(attrs?: any, options?: SignUpOptions): Promise; + logIn(options?: FullOptions): Promise; + authenticated(): boolean; + isCurrent(): boolean; + /** Since version 3.0.0, Returns true if `current` would return this user */ + isCurrentAsync(): Promise; + + getEmail(): string | undefined; + setEmail(email: string, options?: SuccessFailureOptions): boolean; + + getUsername(): string | undefined; + setUsername(username: string, options?: SuccessFailureOptions): boolean; + + setPassword(password: string, options?: SuccessFailureOptions): boolean; + getSessionToken(): string; + + linkWith: ( + provider: string | AuthProvider, + options: { authData?: AuthData | undefined }, + saveOpts?: FullOptions, + ) => Promise; + _isLinked: (provider: string | AuthProvider) => boolean; + _unlinkFrom: (provider: string | AuthProvider, options?: FullOptions) => Promise; + } + interface UserConstructor extends ObjectStatic { + new(attributes: T): User; + new(attributes?: Attributes): User; + + allowCustomUserClass(isAllowed: boolean): void; + become(sessionToken: string, options?: UseMasterKeyOption): Promise; + current(): T | undefined; + currentAsync(): Promise; + signUp(username: string, password: string, attrs: any, options?: SignUpOptions): Promise; + logIn(username: string, password: string, options?: FullOptions): Promise; + logOut(): Promise; + requestPasswordReset(email: string, options?: SuccessFailureOptions): Promise; + requestEmailVerification(email: string, options?: UseMasterKeyOption): Promise; + extend(protoProps?: any, classProps?: any): any; + hydrate(userJSON: any): Promise; + enableUnsafeCurrentUser(): void; + disableUnsafeCurrentUser(): void; + logInWith( + provider: string | AuthProvider, + options: { authData?: AuthData | undefined }, + saveOpts?: FullOptions, + ): Promise; + _registerAuthenticationProvider: (provider: AuthProvider) => void; + } + const User: UserConstructor; + + /** + * The raw schema response returned from the `GET /parse/schemas` endpoint. + * This is defined here: https://docs.parseplatform.org/js/guide/#schema. + * Unfortunately, `Schema.all()` and `Schema.prototype.get()` return this rather + * than a `Schema`. It is also the only object which provides introspection on + * the schema - such as `className` and `fields`. + */ + interface RestSchema { + className: string; + fields: { + [key: string]: { + type: string; + targetClass?: string; + required?: boolean; + defaultValue?: string; + }; + }; + classLevelPermissions: Schema.CLP; + indexes?: { + [key: string]: { + [key: string]: any; + }; + }; + } + + /** + * A Parse.Schema object is for handling schema data from Parse. + * All the schemas methods require MasterKey. + * + * @param className Parse Class string + * + * https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html + * + * ``` + * const schema = new Parse.Schema('MyClass'); + * schema.addString('field'); + * schema.addIndex('index_name', { field: 1 }); + * schema.save(); + * ``` + */ + class Schema { + constructor(className: string); + + /** + * Static method to get all schemas + * + * @return A promise that is resolved with the result when + * the query completes. + */ + static all(): Promise; + + addArray(key: Schema.AttrType, options?: Schema.FieldOptions): this; + addBoolean(key: Schema.AttrType, options?: Schema.FieldOptions): this; + addDate(key: Schema.AttrType, options?: Schema.FieldOptions): this; + addField(name: string, type?: T, options?: Schema.FieldOptions): this; + addFile(key: Schema.AttrType, options?: Schema.FieldOptions): this; + addGeoPoint(key: Schema.AttrType, options?: Schema.FieldOptions): this; + + /** + * Adding an Index to Create / Update a Schema + * @param name Name of the field that will be created on Parse + * @param index `{ 'field': value }` where `field` should exist in the schema before using addIndex. + * @return Returns the schema, so you can chain this call. + * @example + * ``` + * schema.addIndex('index_name', {'field': 1}); + * ``` + */ + addIndex(name: string, index: Schema.Index): this; + + addNumber(key: Schema.AttrType, options?: Schema.FieldOptions): this; + + addObject(key: Schema.AttrType, options?: Schema.FieldOptions): this; + + /** + * Adding Pointer Field + * @param name Name of the field that will be created on Parse + * @param targetClass Name of the target Pointer Class + * @return Returns the schema, so you can chain this call. + */ + addPointer( + key: Schema.AttrType, + targetClass: string, + options?: Schema.FieldOptions, + ): this; + + addPolygon(key: Schema.AttrType, options?: Schema.FieldOptions): this; + + /** + * Adding Relation Field + * @param name Name of the field that will be created on Parse + * @param targetClass Name of the target Pointer Class + * @return Returns the schema, so you can chain this call. + */ + addRelation( + key: Schema.AttrType, + targetClass: string, + options?: Schema.FieldOptions, + ): this; + + addString(key: Schema.AttrType, options?: Schema.FieldOptions): this; + + /** + * Removing a Schema from Parse Can only be used on Schema without objects + * @returns A promise that is resolved with the result when the query completes. + */ + // @TODO Fix Promise + delete(): Promise; + + /** + * Deleting a Field to Update on a Schema + * @param name Name of the field + * @return Returns the schema, so you can chain this call. + */ + deleteField(name: string): this; + + /** + * Deleting a Index Field to Update on a Schema + * @param name Name of the index field + * @return Returns the schema, so you can chain this call. + */ + deleteIndex(name: string): this; + + /** + * Get the Schema from Parse + */ + get(): Promise; + + /** + * Removes all objects from a Schema (class) in EXERCISE CAUTION, running this will delete all objects for this schema and cannot be reversed + */ + // TODO Fix Promise + purge(): Promise; + + /** + * Create a new Schema on Parse + */ + save(): Promise; + + /** + * Sets Class Level Permissions when creating / updating a Schema. + * EXERCISE CAUTION, running this may override CLP for this schema and cannot be reversed + */ + setCLP(clp: Schema.CLP): this; + + /** + * Update a Schema on Parse + */ + update(): Promise; + } + + namespace Schema { + type TYPE = + | "String" + | "Number" + | "Boolean" + | "Date" + | "File" + | "GeoPoint" + | "Polygon" + | "Array" + | "Object" + | "Pointer" + | "Relation"; + type FieldType = + | string + | number + | boolean + | Date + | File + | GeoPoint + | Polygon + | any[] + | object + | Pointer + | Relation; + type AttrType = Extract< + { [K in keyof T["attributes"]]: T["attributes"][K] extends V ? K : never }[keyof T["attributes"]], + string + >; + + interface FieldOptions< + T extends + | string + | number + | boolean + | Date + | File + | GeoPoint + | Polygon + | any[] + | object + | Pointer + | Relation = any, + > { + required?: boolean | undefined; + defaultValue?: T | undefined; + } + + interface Index { + [fieldName: string]: number | string; + } + + /** + * The id of a `_User` object or a role name prefixed by `'role:'`. + * @example + * '*': false, // public + * requiresAuthentication: false, + * 'role:Admin': true, + * 'idOfASpecificUser': true + */ + interface CLPField { + "*"?: boolean | undefined; + requiresAuthentication?: boolean | undefined; + /** `role:Admin` */ + [userIdOrRoleName: string]: boolean | undefined; + } + + interface CLP { + find?: CLPField | undefined; + get?: CLPField | undefined; + count?: CLPField | undefined; + create?: CLPField | undefined; + update?: CLPField | undefined; + delete?: CLPField | undefined; + addField?: CLPField | undefined; + /** Array of fields that point to a `_User` object's ID or a `Role` object's name */ + readUserFields?: string[] | undefined; + /** Array of fields that point to a `_User` object's ID or a `Role` object's name */ + writeUserFields?: string[] | undefined; + protectedFields?: { + /** '*', user id, or role: followed by a list of fields. */ + [userIdOrRoleName: string]: string[]; + }; + } + } + + namespace Analytics { + function track(name: string, dimensions: any): Promise; + } + + /** + * Provides utility functions for working with Anonymously logged-in users. + */ + namespace AnonymousUtils { + function isLinked(user: User): boolean; + function link(user: User, options?: ScopeOptions): Promise; + function logIn(options?: ScopeOptions): Promise; + } + + /** + * Provides a set of utilities for using Parse with Facebook. + * Provides a set of utilities for using Parse with Facebook. + */ + namespace FacebookUtils { + function init(options?: any): void; + function isLinked(user: User): boolean; + function link(user: User, permissions: any, options?: SuccessFailureOptions): void; + function logIn(permissions: any, options?: FullOptions): void; + function unlink(user: User, options?: SuccessFailureOptions): void; + } + + /** + * Contains functions for calling and declaring + * cloud functions. + *

+ * Some functions are only available from Cloud Code. + *

+ */ + namespace Cloud { + interface CookieOptions { + domain?: string | undefined; + expires?: Date | undefined; + httpOnly?: boolean | undefined; + maxAge?: number | undefined; + path?: string | undefined; + secure?: boolean | undefined; + } + + interface HttpResponse { + buffer?: Buffer | undefined; + cookies?: any; + data?: any; + headers?: any; + status?: number | undefined; + text?: string | undefined; + } + + interface JobRequest { + params: T; + message: (response: any) => void; + } + + interface Params { + [key: string]: any; + } + + interface FunctionRequest { + installationId?: string | undefined; + master?: boolean | undefined; + params: T; + user?: User | undefined; + } + + interface ValidatorField { + type?: any; + constant?: boolean | undefined; + default?: any; + options?: any[] | Function | undefined; + error?: String | undefined; + required?: boolean; + } + interface ValidatorFields { + [field: string]: ValidatorField; + } + interface Validator { + requireUser?: boolean | undefined; + requireMaster?: boolean | undefined; + validateMasterKey?: boolean | undefined; + skipWithMasterKey?: boolean | undefined; + requireAnyUserRoles?: String[] | Function | undefined; + requireAllUserRoles?: String[] | Function | undefined; + fields?: ValidatorFields | String[] | undefined; + requireUserKeys?: ValidatorFields | String[] | undefined; + } + + interface Cookie { + name?: string | undefined; + options?: CookieOptions | undefined; + value?: string | undefined; + } + + interface TriggerRequest { + installationId?: string | undefined; + master?: boolean | undefined; + user?: User | undefined; + ip: string; + headers: any; + triggerName: string; + log: any; + object: T; + original?: T | undefined; + } + + interface AfterSaveRequest extends TriggerRequest { + context: Record; + } + interface AfterDeleteRequest extends TriggerRequest {} // eslint-disable-line @typescript-eslint/no-empty-interface + interface BeforeDeleteRequest extends TriggerRequest {} // eslint-disable-line @typescript-eslint/no-empty-interface + interface BeforeSaveRequest extends TriggerRequest { + context: Record; + } + + interface FileTriggerRequest extends TriggerRequest { + file: File; + fileSize: number; + contentLength: number; + } + + // Read preference describes how MongoDB driver route read operations to the members of a replica set. + enum ReadPreferenceOption { + Primary = "PRIMARY", + PrimaryPreferred = "PRIMARY_PREFERRED", + Secondary = "SECONDARY", + SecondaryPreferred = "SECONDARY_PREFERRED", + Nearest = "NEAREST", + } + + interface BeforeFindRequest extends TriggerRequest { + query: Query; + count: boolean; + isGet: boolean; + readPreference?: ReadPreferenceOption | undefined; + } + + interface AfterFindRequest extends TriggerRequest { + objects: T[]; + } + + function afterDelete( + arg1: { new(): T } | string, + func?: (request: AfterDeleteRequest) => Promise | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function afterSave( + arg1: { new(): T } | string, + func?: (request: AfterSaveRequest) => Promise | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function beforeDelete( + arg1: { new(): T } | string, + func?: (request: BeforeDeleteRequest) => Promise | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function beforeSave( + arg1: { new(): T } | string, + func?: (request: BeforeSaveRequest) => Promise | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function beforeFind( + arg1: { new(): T } | string, + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + func?: (request: BeforeFindRequest) => Promise> | Promise | Query | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function afterFind( + arg1: { new(): T } | string, + func?: (request: AfterFindRequest) => any, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + + function beforeLogin(func?: (request: TriggerRequest) => PromiseLike | void): void; + function afterLogin( + func?: (request: TriggerRequest) => PromiseLike | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function afterLogout( + func?: (request: TriggerRequest) => PromiseLike | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + + function beforeSaveFile( + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + func?: (request: FileTriggerRequest) => PromiseLike | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function afterSaveFile( + func?: (request: FileTriggerRequest) => PromiseLike | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function beforeDeleteFile( + func?: (request: FileTriggerRequest) => PromiseLike | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function afterDeleteFile( + func?: (request: FileTriggerRequest) => PromiseLike | void, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + + function define( + name: string, + func: (request: FunctionRequest) => any, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function define any>( + name: string, + func: (request: FunctionRequest<{}>) => Promise> | ReturnType, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + function define[0]]: Parameters[0][P] }) => any>( + name: string, + func: (request: FunctionRequest[0]>) => Promise> | ReturnType, + validator?: Validator | ((request: FunctionRequest) => any), + ): void; + /** + * Gets data for the current set of cloud jobs. + * @returns A promise that will be resolved with the result of the function. + */ + function getJobsData(): Promise; + /** + * Gets job status by Id + * @param jobStatusId The Id of Job Status. + * @returns Status of Job. + */ + function getJobStatus(jobStatusId: string): Promise; + function httpRequest(options: HTTPOptions): Promise; + function job(name: string, func?: (request: JobRequest) => Promise | void): HttpResponse; + function run(name: string, data?: Params, options?: RunOptions): Promise; + function run any>(name: string, data?: null, options?: RunOptions): Promise>; + function run[0]]: Parameters[0][P] }) => any>( + name: string, + data: Parameters[0], + options?: RunOptions, + ): Promise>; + /** + * Starts a given cloud job, which will process asynchronously. + * @param jobName The function name. + * @param data The parameters to send to the cloud function. + * @returns A promise that will be resolved with the jobStatusId of the job. + */ + function startJob(jobName: string, data: any): Promise; + function useMasterKey(): void; + + interface RunOptions extends SuccessFailureOptions, ScopeOptions {} + + /** + * To use this Cloud Module in Cloud Code, you must require 'buffer' in your JavaScript file. + * + * import Buffer = require("buffer").Buffer; + */ + let HTTPOptions: new() => HTTPOptions; + interface HTTPOptions { + /** + * The body of the request. + * If it is a JSON object, then the Content-Type set in the headers must be application/x-www-form-urlencoded or application/json. + * You can also set this to a Buffer object to send raw bytes. + * If you use a Buffer, you should also set the Content-Type header explicitly to describe what these bytes represent. + */ + body?: string | Buffer | object | undefined; + /** + * Defaults to 'false'. + */ + followRedirects?: boolean | undefined; + /** + * The headers for the request. + */ + headers?: + | { + [headerName: string]: string | number | boolean; + } + | undefined; + /** + * The method of the request (i.e GET, POST, etc). + */ + method?: string | undefined; + /** + * The query portion of the url. + */ + params?: any; + /** + * The url to send the request to. + */ + url: string; + + success?: ((response: any) => void) | undefined; + error?: ((response: any) => void) | undefined; + } + } + + namespace EventuallyQueue { + interface QueueObject { + queueId: string; + action: string; + object: Object; + serverOptions: Object.SaveOptions | RequestOptions; + id: string; + className: string; + hash: string; + createdAt: Date; + } + type Queue = QueueObject[]; + /** + * Add object to queue with save operation. + * + * @param object Parse.Object to be saved eventually + * @param serverOptions See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#save Parse.Object.save} options. + * @returns A promise that is fulfilled if object is added to queue. + * @see Parse.Object#saveEventually + */ + function save(object: Object, serverOptions?: Object.SaveOptions): Promise; + /** + * Add object to queue with save operation. + * + * @param object Parse.Object to be destroyed eventually + * @param serverOptions See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#destroy Parse.Object.destroy} options + * @returns A promise that is fulfilled if object is added to queue. + * @see Parse.Object#destroyEventually + */ + function destroy(object: Object, serverOptions?: RequestOptions): Promise; + // function store(data: any): Promise; + // function load(): Promise; + /** + * Sets the in-memory queue from local storage and returns. + */ + function getQueue(): Promise; + /** + * Removes all objects from queue. + * @returns A promise that is fulfilled when queue is cleared. + */ + function clear(): Promise; + /** + * Return the number of objects in the queue. + */ + function length(): Promise; + /** + * Sends the queue to the server. + * @returns Returns true if queue was sent successfully. + */ + function sendQueue(): Promise; + /** + * Start polling server for network connection. + * Will send queue if connection is established. + * + * @param [ms] Milliseconds to ping the server. Default 2000ms + */ + function poll(ms?: number): void; + /** + * Turns off polling. + */ + function stopPoll(): void; + /** + * Return true if pinging the server. + */ + function isPolling(): boolean; + } + + class Error { + static OTHER_CAUSE: ErrorCode.OTHER_CAUSE; + static INTERNAL_SERVER_ERROR: ErrorCode.INTERNAL_SERVER_ERROR; + static CONNECTION_FAILED: ErrorCode.CONNECTION_FAILED; + static OBJECT_NOT_FOUND: ErrorCode.OBJECT_NOT_FOUND; + static INVALID_QUERY: ErrorCode.INVALID_QUERY; + static INVALID_CLASS_NAME: ErrorCode.INVALID_CLASS_NAME; + static MISSING_OBJECT_ID: ErrorCode.MISSING_OBJECT_ID; + static INVALID_KEY_NAME: ErrorCode.INVALID_KEY_NAME; + static INVALID_POINTER: ErrorCode.INVALID_POINTER; + static INVALID_JSON: ErrorCode.INVALID_JSON; + static COMMAND_UNAVAILABLE: ErrorCode.COMMAND_UNAVAILABLE; + static NOT_INITIALIZED: ErrorCode.NOT_INITIALIZED; + static INCORRECT_TYPE: ErrorCode.INCORRECT_TYPE; + static INVALID_CHANNEL_NAME: ErrorCode.INVALID_CHANNEL_NAME; + static PUSH_MISCONFIGURED: ErrorCode.PUSH_MISCONFIGURED; + static OBJECT_TOO_LARGE: ErrorCode.OBJECT_TOO_LARGE; + static OPERATION_FORBIDDEN: ErrorCode.OPERATION_FORBIDDEN; + static CACHE_MISS: ErrorCode.CACHE_MISS; + static INVALID_NESTED_KEY: ErrorCode.INVALID_NESTED_KEY; + static INVALID_FILE_NAME: ErrorCode.INVALID_FILE_NAME; + static INVALID_ACL: ErrorCode.INVALID_ACL; + static TIMEOUT: ErrorCode.TIMEOUT; + static INVALID_EMAIL_ADDRESS: ErrorCode.INVALID_EMAIL_ADDRESS; + static MISSING_CONTENT_TYPE: ErrorCode.MISSING_CONTENT_TYPE; + static MISSING_CONTENT_LENGTH: ErrorCode.MISSING_CONTENT_LENGTH; + static INVALID_CONTENT_LENGTH: ErrorCode.INVALID_CONTENT_LENGTH; + static FILE_TOO_LARGE: ErrorCode.FILE_TOO_LARGE; + static FILE_SAVE_ERROR: ErrorCode.FILE_SAVE_ERROR; + static DUPLICATE_VALUE: ErrorCode.DUPLICATE_VALUE; + static INVALID_ROLE_NAME: ErrorCode.INVALID_ROLE_NAME; + static EXCEEDED_QUOTA: ErrorCode.EXCEEDED_QUOTA; + static SCRIPT_FAILED: ErrorCode.SCRIPT_FAILED; + static VALIDATION_ERROR: ErrorCode.VALIDATION_ERROR; + static INVALID_IMAGE_DATA: ErrorCode.INVALID_IMAGE_DATA; + static UNSAVED_FILE_ERROR: ErrorCode.UNSAVED_FILE_ERROR; + static INVALID_PUSH_TIME_ERROR: ErrorCode.INVALID_PUSH_TIME_ERROR; + static FILE_DELETE_ERROR: ErrorCode.FILE_DELETE_ERROR; + static REQUEST_LIMIT_EXCEEDED: ErrorCode.REQUEST_LIMIT_EXCEEDED; + static INVALID_EVENT_NAME: ErrorCode.INVALID_EVENT_NAME; + static USERNAME_MISSING: ErrorCode.USERNAME_MISSING; + static PASSWORD_MISSING: ErrorCode.PASSWORD_MISSING; + static USERNAME_TAKEN: ErrorCode.USERNAME_TAKEN; + static EMAIL_TAKEN: ErrorCode.EMAIL_TAKEN; + static EMAIL_MISSING: ErrorCode.EMAIL_MISSING; + static EMAIL_NOT_FOUND: ErrorCode.EMAIL_NOT_FOUND; + static SESSION_MISSING: ErrorCode.SESSION_MISSING; + static MUST_CREATE_USER_THROUGH_SIGNUP: ErrorCode.MUST_CREATE_USER_THROUGH_SIGNUP; + static ACCOUNT_ALREADY_LINKED: ErrorCode.ACCOUNT_ALREADY_LINKED; + static INVALID_SESSION_TOKEN: ErrorCode.INVALID_SESSION_TOKEN; + static LINKED_ID_MISSING: ErrorCode.LINKED_ID_MISSING; + static INVALID_LINKED_SESSION: ErrorCode.INVALID_LINKED_SESSION; + static UNSUPPORTED_SERVICE: ErrorCode.UNSUPPORTED_SERVICE; + static AGGREGATE_ERROR: ErrorCode.AGGREGATE_ERROR; + static FILE_READ_ERROR: ErrorCode.FILE_READ_ERROR; + static X_DOMAIN_REQUEST: ErrorCode.X_DOMAIN_REQUEST; + + code: ErrorCode; + message: string; + + constructor(code: ErrorCode, message: string); + } + + /** + * A Parse.Op is an atomic operation that can be applied to a field in a + * Parse.Object. For example, calling object.set("foo", "bar") + * is an example of a Parse.Op.Set. Calling object.unset("foo") + * is a Parse.Op.Unset. These operations are stored in a Parse.Object and + * sent to the server as part of object.save() operations. + * Instances of Parse.Op should be immutable. + * + * You should not create subclasses of Parse.Op or instantiate Parse.Op + * directly. + */ + namespace Op { + interface BaseOperation { + objects(): any[]; + } + + interface Add extends BaseOperation { + toJSON(): any; + } + + interface AddUnique extends BaseOperation { + toJSON(): any; + } + + interface Increment { + amount: number; + toJSON(): any; + } + + interface Relation { + added(): Object[]; + removed: Object[]; + toJSON(): any; + } + + interface Set { + value(): any; + toJSON(): any; + } + + interface Unset { + toJSON(): any; + } + } + + /** + * Contains functions to deal with Push in Parse + */ + namespace Push { + function send(data: PushData, options?: SendOptions): Promise; + + interface PushData { + channels?: string[] | undefined; + push_time?: Date | undefined; + expiration_time?: Date | undefined; + expiration_interval?: number | undefined; + where?: Query | undefined; + data?: any; + alert?: string | undefined; + badge?: string | undefined; + sound?: string | undefined; + title?: string | undefined; + notification?: any; + content_available?: any; + } + + interface SendOptions extends UseMasterKeyOption { + success?: (() => void) | undefined; + error?: ((error: Error) => void) | undefined; + } + } + + /** + * Call this method first to set up your authentication tokens for Parse. + * You can get your keys from the Data Browser on parse.com. + * @param applicationId Your Parse Application ID. + * @param javaScriptKey (optional) Your Parse JavaScript Key (Not needed for parse-server) + * @param masterKey (optional) Your Parse Master Key. (Node.js only!) + */ + function initialize(applicationId: string, javaScriptKey?: string, masterKey?: string): void; + + /** + * Use this to set custom headers + * The headers will be sent with every parse request + */ + namespace CoreManager { + function set(key: string, value: any): void; + function get(key: string): void; + } + + /** + * Additionally on React-Native / Expo environments, add AsyncStorage from 'react-native' package + * @param AsyncStorage AsyncStorage from 'react-native' package + */ + function setAsyncStorage(AsyncStorage: any): void; + + /** + * Gets all contents from Local Datastore. + */ + function dumpLocalDatastore(): Promise<{ [key: string]: any }>; + + /** + * Enable pinning in your application. + * This must be called before your application can use pinning. + */ + function enableLocalDatastore(): void; + + /** + * Flag that indicates whether Local Datastore is enabled. + */ + function isLocalDatastoreEnabled(): boolean; + + function setLocalDatastoreController(controller: any): void; + + /** + * Call this method to set your LocalDatastoreStorage engine + * If using React-Native use {@link Parse.setAsyncStorage Parse.setAsyncStorage()} + * @param controller a data storage. + */ + function setLocalDatastoreController(controller: any): void; + + /** + * Enable the current user encryption. + * This must be called before login any user. + */ + function enableEncryptedUser(): void; + + /** + * Flag that indicates whether Encrypted User is enabled. + */ + function isEncryptedUserEnabled(): boolean; + } +} + +export = Parse; diff --git a/src/Cloud.ts b/src/Cloud.ts index c8fd781ad..d86fa57f7 100644 --- a/src/Cloud.ts +++ b/src/Cloud.ts @@ -4,7 +4,9 @@ import encode from './encode'; import ParseError from './ParseError'; import ParseQuery from './ParseQuery'; import ParseObject from './ParseObject'; -import type { RequestOptions } from './RESTController'; +import type { RequestOptions, FullOptions } from './RESTController'; + +export interface RunOptions extends RequestOptions, FullOptions { } /** * Contains functions for calling and declaring @@ -40,12 +42,12 @@ import type { RequestOptions } from './RESTController'; export function run any>( name: string, data?: null, - options?: RequestOptions + options?: RunOptions ): Promise>; export function run< T extends (param: { [P in keyof Parameters[0]]: Parameters[0][P] }) => any, ->(name: string, data: Parameters[0], options?: RequestOptions): Promise>; -export function run(name: string, data?: any, options?: RequestOptions): Promise { +>(name: string, data: Parameters[0], options?: RunOptions): Promise>; +export function run(name: string, data?: any, options?: RunOptions): Promise { if (typeof name !== 'string' || name.length === 0) { throw new TypeError('Cloud function name must be a string.'); } diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 8564aa6e0..bd247533d 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -52,7 +52,7 @@ export type SaveOptions = FullOptions & { transaction?: boolean; }; -interface FetchOptions { +export interface FetchOptions { useMasterKey?: boolean; sessionToken?: string; include?: string | string[]; @@ -64,16 +64,28 @@ export interface SetOptions { unset?: boolean; } +export interface DestroyOptions { + useMasterKey?: boolean; + sessionToken?: string; + context?: AttributeMap; +} + export type AttributeKey = Extract; export type Attributes = Record; -interface JSONBaseAttributes { +export interface JSONBaseAttributes { objectId: string; createdAt: string; updatedAt: string; } +export interface BaseAttributes { + objectId: string; + createdAt: Date; + updatedAt: Date; +} + interface CommonAttributes { ACL: ParseACL; } @@ -85,16 +97,16 @@ type AtomicKey = { type Encode = T extends ParseObject ? ReturnType | Pointer : T extends ParseACL | ParseGeoPoint | ParsePolygon | ParseRelation | ParseFile - ? ReturnType - : T extends Date - ? { __type: 'Date'; iso: string } - : T extends RegExp - ? string - : T extends (infer R)[] - ? Encode[] - : T extends object - ? ToJSON - : T; + ? ReturnType + : T extends Date + ? { __type: 'Date'; iso: string } + : T extends RegExp + ? string + : T extends (infer R)[] + ? Encode[] + : T extends object + ? ToJSON + : T; type ToJSON = { [K in keyof T]: Encode; @@ -151,7 +163,7 @@ class ParseObject { * @param {boolean} [options.ignoreValidation] Set to `true` ignore any attribute validation errors. */ constructor( - className?: string | { className: string; [attr: string]: any }, + className?: string | { className: string;[attr: string]: any }, attributes?: T, options?: SetOptions ) { @@ -188,9 +200,8 @@ class ParseObject { } if (CoreManager.get('NODE_LOGGING')) { this[Symbol.for('nodejs.util.inspect.custom')] = function () { - return `ParseObject: className: ${this.className}, id: ${ - this.id - }\nAttributes: ${JSON.stringify(this.attributes, null, 2)}`; + return `ParseObject: className: ${this.className}, id: ${this.id + }\nAttributes: ${JSON.stringify(this.attributes, null, 2)}`; }; } } @@ -1481,7 +1492,7 @@ class ParseObject { * @returns {Promise} A promise that is fulfilled when the destroy * completes. */ - destroy(options?: RequestOptions): Promise { + destroy(options?: DestroyOptions): Promise { if (!this.id) { return Promise.resolve(undefined); } @@ -1948,7 +1959,7 @@ class ParseObject { if (typeof constructor !== 'function') { throw new TypeError( 'You must register the subclass constructor. ' + - 'Did you attempt to register an instance of the subclass?' + 'Did you attempt to register an instance of the subclass?' ); } classMap[className] = constructor; @@ -2657,4 +2668,37 @@ const DefaultController = { CoreManager.setParseObject(ParseObject); CoreManager.setObjectController(DefaultController); +export interface ObjectStatic { + new(className: string, attributes?: Attributes, options?: any): T; + new(attributes?: Attributes, options?: any): T; + extend(className: string, protoProps?: any, classProps?: any): any; + enableSingleInstance(): void; + disableSingleInstance(): void; + enableLocaldatastore(): void; + isLocalDatastoreEnabled(): boolean; + disableLocaldatastore(): void; + unpinAllObjects(): Promise; + unpinAllObjectsWithName(name: string): Promise; + fetchAll(list: T[], options?: RequestOptions): Promise; + fetchAllWithInclude( + list: T[], + include: string | string[], + options?: RequestOptions + ): Promise; + fetchAllIfNeeded(list: T[], options?: RequestOptions): Promise; + destroyAll(list: T[], options?: RequestOptions): Promise; + saveAll(list: T[], options?: SaveOptions): Promise; + fetchAllFromLocalDatastore(list: T[], options?: RequestOptions): Promise; + unpinAll(list: T[], options?: RequestOptions): Promise; + pinAll(list: T[], options?: RequestOptions): Promise; + pinAllWithName( + name: string, + list: T[], + options?: RequestOptions + ): Promise; + fromJSON(json: any, override?: boolean): T; + registerSubclass(className: string, constructor: any): void; + createWithoutData(className: string, id: string): T; +} + export default ParseObject; diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index 91ece7e39..f1bf80f2e 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -22,13 +22,16 @@ type BatchOptions = FullOptions & { export type WhereClause = Record; -interface QueryOptions { +export interface QueryOptions { useMasterKey?: boolean; sessionToken?: string; context?: Record; json?: boolean; } +/** Alias for QueryOptions, used for find operations */ +export type FindOptions = QueryOptions; + interface FullTextQueryOptions { language?: string; caseSensitive?: boolean; @@ -305,7 +308,7 @@ class ParseQuery { this._extraOptions = {}; this._xhrRequest = { task: null, - onchange: () => {}, + onchange: () => { }, }; this._comment = null; } @@ -1153,10 +1156,10 @@ class ParseQuery { value: | T['attributes'][K] | (T['attributes'][K] extends ParseObject - ? Pointer - : T['attributes'][K] extends (infer E)[] - ? E - : never) + ? Pointer + : T['attributes'][K] extends (infer E)[] + ? E + : never) ): this { if (key && typeof key === 'object') { Object.entries(key).forEach(([k, val]) => this.equalTo(k, val as any)); @@ -1182,10 +1185,10 @@ class ParseQuery { value: | T['attributes'][K] | (T['attributes'][K] extends ParseObject - ? Pointer - : T['attributes'][K] extends (infer E)[] - ? E - : never) + ? Pointer + : T['attributes'][K] extends (infer E)[] + ? E + : never) ): this { if (key && typeof key === 'object') { Object.entries(key).forEach(([k, val]) => this.notEqualTo(k, val as any)); @@ -2133,7 +2136,7 @@ class ParseQuery { this._xhrRequest.task._aborted = true; this._xhrRequest.task.abort(); this._xhrRequest.task = null; - this._xhrRequest.onchange = () => {}; + this._xhrRequest.onchange = () => { }; return this; } this._xhrRequest.onchange = () => this.cancel(); diff --git a/src/ParseSchema.ts b/src/ParseSchema.ts index d6884c8c2..eaf0aa511 100644 --- a/src/ParseSchema.ts +++ b/src/ParseSchema.ts @@ -10,7 +10,7 @@ import type { Pointer } from './ParseObject'; type Bytes = string; -type TYPE = +export type TYPE = | 'String' | 'Number' | 'Bytes' @@ -33,18 +33,18 @@ type AttrType = Extract< interface FieldOptions< T extends - | string - | number - | boolean - | Bytes - | Date - | ParseFile - | ParseGeoPoint - | ParsePolygon - | any[] - | object - | Pointer - | ParseRelation = any, + | string + | number + | boolean + | Bytes + | Date + | ParseFile + | ParseGeoPoint + | ParsePolygon + | any[] + | object + | Pointer + | ParseRelation = any, > { required?: boolean | undefined; defaultValue?: T | undefined; @@ -72,7 +72,7 @@ interface CLP { protectedFields?: Record; } -interface RestSchema { +export interface RestSchema { className: string; fields: Record< string, diff --git a/src/ParseUser.ts b/src/ParseUser.ts index 5f3b39b76..f6ca0ad95 100644 --- a/src/ParseUser.ts +++ b/src/ParseUser.ts @@ -17,6 +17,11 @@ export interface AuthProvider { getAuthType(): string; deauthenticate?(): void; } + +export interface SignUpOptions { + useMasterKey?: boolean; + installationId?: string; +} const CURRENT_USER_KEY = 'currentUser'; let canUseCurrentUser = !CoreManager.get('IS_NODE'); let currentUserCacheMatchesDisk = false; @@ -437,7 +442,7 @@ class ParseUser extends ParseObject { */ signUp( attrs?: Attributes | null, - options?: FullOptions & { context?: Attributes } + options?: SignUpOptions & { context?: Attributes } ): Promise { const signupOptions = ParseObject._getRequestOptions(options); const controller = CoreManager.getUserController(); @@ -1039,7 +1044,7 @@ const DefaultController = { if (Storage.async()) { throw new Error( 'Cannot call currentUser() when using a platform with an async ' + - 'storage system. Call currentUserAsync() instead.' + 'storage system. Call currentUserAsync() instead.' ); } const path = Storage.generatePath(CURRENT_USER_KEY); @@ -1112,7 +1117,7 @@ const DefaultController = { }); }, - signUp(user: ParseUser, attrs: Attributes, options?: RequestOptions): Promise { + signUp(user: ParseUser, attrs: Attributes, options?: SignUpOptions): Promise { const username = (attrs && attrs.username) || user.get('username'); const password = (attrs && attrs.password) || user.get('password'); diff --git a/types/Cloud.d.ts b/types/Cloud.d.ts index 7a288f908..eb7346c57 100644 --- a/types/Cloud.d.ts +++ b/types/Cloud.d.ts @@ -1,5 +1,7 @@ import ParseObject from './ParseObject'; -import type { RequestOptions } from './RESTController'; +import type { RequestOptions, FullOptions } from './RESTController'; +export interface RunOptions extends RequestOptions, FullOptions { +} /** * Contains functions for calling and declaring * cloud functions. @@ -30,10 +32,10 @@ import type { RequestOptions } from './RESTController'; * @returns {Promise} A promise that will be resolved with the result * of the function. */ -export declare function run any>(name: string, data?: null, options?: RequestOptions): Promise>; +export declare function run any>(name: string, data?: null, options?: RunOptions): Promise>; export declare function run[0]]: Parameters[0][P]; -}) => any>(name: string, data: Parameters[0], options?: RequestOptions): Promise>; +}) => any>(name: string, data: Parameters[0], options?: RunOptions): Promise>; /** * Gets data for the current set of cloud jobs. * diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 4a653ece8..f04257260 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -24,7 +24,7 @@ export type SaveOptions = FullOptions & { batchSize?: number; transaction?: boolean; }; -interface FetchOptions { +export interface FetchOptions { useMasterKey?: boolean; sessionToken?: string; include?: string | string[]; @@ -34,13 +34,23 @@ export interface SetOptions { ignoreValidation?: boolean; unset?: boolean; } +export interface DestroyOptions { + useMasterKey?: boolean; + sessionToken?: string; + context?: AttributeMap; +} export type AttributeKey = Extract; export type Attributes = Record; -interface JSONBaseAttributes { +export interface JSONBaseAttributes { objectId: string; createdAt: string; updatedAt: string; } +export interface BaseAttributes { + objectId: string; + createdAt: Date; + updatedAt: Date; +} interface CommonAttributes { ACL: ParseACL; } @@ -594,7 +604,7 @@ declare class ParseObject { * @returns {Promise} A promise that is fulfilled when the destroy * completes. */ - destroy(options?: RequestOptions): Promise; + destroy(options?: DestroyOptions): Promise; /** * Asynchronously stores the object and every object it points to in the local datastore, * recursively, using a default pin name: _default. @@ -1067,4 +1077,28 @@ declare class ParseObject { */ static unPinAllObjectsWithName(name: string): Promise; } +export interface ObjectStatic { + new (className: string, attributes?: Attributes, options?: any): T; + new (attributes?: Attributes, options?: any): T; + extend(className: string, protoProps?: any, classProps?: any): any; + enableSingleInstance(): void; + disableSingleInstance(): void; + enableLocaldatastore(): void; + isLocalDatastoreEnabled(): boolean; + disableLocaldatastore(): void; + unpinAllObjects(): Promise; + unpinAllObjectsWithName(name: string): Promise; + fetchAll(list: T[], options?: RequestOptions): Promise; + fetchAllWithInclude(list: T[], include: string | string[], options?: RequestOptions): Promise; + fetchAllIfNeeded(list: T[], options?: RequestOptions): Promise; + destroyAll(list: T[], options?: RequestOptions): Promise; + saveAll(list: T[], options?: SaveOptions): Promise; + fetchAllFromLocalDatastore(list: T[], options?: RequestOptions): Promise; + unpinAll(list: T[], options?: RequestOptions): Promise; + pinAll(list: T[], options?: RequestOptions): Promise; + pinAllWithName(name: string, list: T[], options?: RequestOptions): Promise; + fromJSON(json: any, override?: boolean): T; + registerSubclass(className: string, constructor: any): void; + createWithoutData(className: string, id: string): T; +} export default ParseObject; diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index fa8e558e8..c05b0cabc 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -12,12 +12,14 @@ type BatchOptions = FullOptions & { json?: boolean; }; export type WhereClause = Record; -interface QueryOptions { +export interface QueryOptions { useMasterKey?: boolean; sessionToken?: string; context?: Record; json?: boolean; } +/** Alias for QueryOptions, used for find operations */ +export type FindOptions = QueryOptions; interface FullTextQueryOptions { language?: string; caseSensitive?: boolean; diff --git a/types/ParseSchema.d.ts b/types/ParseSchema.d.ts index 043d3d901..3d3ccb7fa 100644 --- a/types/ParseSchema.d.ts +++ b/types/ParseSchema.d.ts @@ -7,7 +7,7 @@ import type ParseRelation from './ParseRelation'; import type { PermissionsMap } from './ParseCLP'; import type { Pointer } from './ParseObject'; type Bytes = string; -type TYPE = 'String' | 'Number' | 'Bytes' | 'Boolean' | 'Date' | 'File' | 'GeoPoint' | 'Polygon' | 'Array' | 'Object' | 'Pointer' | 'Relation'; +export type TYPE = 'String' | 'Number' | 'Bytes' | 'Boolean' | 'Date' | 'File' | 'GeoPoint' | 'Polygon' | 'Array' | 'Object' | 'Pointer' | 'Relation'; type AttrType = Extract<{ [K in keyof T['attributes']]: T['attributes'][K] extends V ? K : never; }[keyof T['attributes']], string>; @@ -34,7 +34,7 @@ interface CLP { writeUserFields?: string[] | undefined; protectedFields?: Record; } -interface RestSchema { +export interface RestSchema { className: string; fields: RecordA Parse.User object is a local representation of a user persisted to the * Parse cloud. This class is a subclass of a Parse.Object, and retains the @@ -194,7 +198,7 @@ declare class ParseUser extends ParseObject; /** diff --git a/types/index.d.ts b/types/index.d.ts index 651f033f3..b18c73fc0 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -32,9 +32,14 @@ import Schema from './ParseSchema'; import Session from './ParseSession'; import Storage from './Storage'; import User from './ParseUser'; +import LiveQuerySubscription from './LiveQuerySubscription'; -export type { AuthProvider, AuthData } from './ParseUser'; -export type { Pointer } from './ParseObject'; +export type { AuthProvider, AuthData, SignUpOptions } from './ParseUser'; +export type { Pointer, Attributes, BaseAttributes, JSONBaseAttributes, ObjectStatic, FetchOptions as ObjectFetchOptions, SaveOptions as ObjectSaveOptions, SetOptions as ObjectSetOptions, DestroyOptions as ObjectDestroyOptions } from './ParseObject'; +export type { FullOptions, RequestOptions } from './RESTController'; +export type { RestSchema, TYPE } from './ParseSchema'; +export type { FindOptions, QueryOptions, QueryJSON, WhereClause } from './ParseQuery'; +export { LiveQuerySubscription }; export { ACL, Analytics, @@ -64,3 +69,126 @@ export { IndexedDB, Hooks, }; + +// Namespace-scoped option types for backwards compatibility +// These augment the class namespaces with additional types +export namespace Object { + /** Options for destroying objects */ + export interface DestroyOptions { + useMasterKey?: boolean; + sessionToken?: string; + context?: Record; + } + /** Options for fetching objects */ + export interface FetchOptions { + useMasterKey?: boolean; + sessionToken?: string; + include?: string | string[]; + context?: Record; + } + /** Options for saving objects */ + export interface SaveOptions { + useMasterKey?: boolean; + sessionToken?: string; + cascadeSave?: boolean; + context?: Record; + } + /** Options for setting attributes */ + export interface SetOptions { + ignoreValidation?: boolean; + unset?: boolean; + } +} + +export namespace Query { + /** Options for find operations */ + export interface FindOptions { + useMasterKey?: boolean; + sessionToken?: string; + context?: Record; + json?: boolean; + } + /** Options for first operations */ + export interface FirstOptions { + useMasterKey?: boolean; + sessionToken?: string; + context?: Record; + json?: boolean; + } + /** Options for get operations */ + export interface GetOptions { + useMasterKey?: boolean; + sessionToken?: string; + context?: Record; + json?: boolean; + } + /** Options for count operations */ + export interface CountOptions { + useMasterKey?: boolean; + sessionToken?: string; + } + /** Options for each operations */ + export interface EachOptions { + useMasterKey?: boolean; + sessionToken?: string; + } + /** Options for batch operations */ + export interface BatchOptions { + useMasterKey?: boolean; + useMaintenanceKey?: boolean; + sessionToken?: string; + batchSize?: number; + context?: Record; + json?: boolean; + } + /** Options for full text search */ + export interface FullTextOptions { + language?: string; + caseSensitive?: boolean; + diacriticSensitive?: boolean; + } + /** Options for aggregation queries */ + export interface AggregationOptions { + group?: (Record & { objectId?: string }); + match?: Record; + project?: Record; + limit?: number; + skip?: number; + sort?: Record; + sample?: { size: number }; + count?: string; + lookup?: { + from: string; + localField: string; + foreignField: string; + as: string; + } | { + from: string; + let?: Record; + pipeline: Record; + as: string; + }; + graphLookup?: { + from: string; + startWith?: string; + connectFromField: string; + connectToField: string; + as: string; + maxDepth?: number; + depthField?: string; + restrictSearchWithMatch?: Record; + }; + facet?: Record>>; + unwind?: { + path: string; + includeArrayIndex?: string; + preserveNullAndEmptyArrays?: boolean; + } | string; + } +} + +export namespace Schema { + /** Field type for Parse Schema */ + export type TYPE = 'String' | 'Number' | 'Bytes' | 'Boolean' | 'Date' | 'File' | 'GeoPoint' | 'Polygon' | 'Array' | 'Object' | 'Pointer' | 'Relation'; +} + diff --git a/types/tests.ts b/types/tests.ts index 7a97b9f67..2a30047e2 100644 --- a/types/tests.ts +++ b/types/tests.ts @@ -90,8 +90,8 @@ async function test_query() { diacriticSensitive: true, }); query.greaterThan('playerAge', 18); - await query.eachBatch(objs => {}, { batchSize: 10 }); - await query.each(score => {}); + await query.eachBatch(objs => { }, { batchSize: 10 }); + await query.each(score => { }); query.hint('_id_'); query.explain(true); query.limit(10); @@ -366,7 +366,7 @@ function test_relation() { .relation('games') .query() .find() - .then((g: Game[]) => {}) + .then((g: Game[]) => { }) .catch(error => error); new Parse.User().relation('games').add(game1); new Parse.User().relation('games').add([game1, game2]); @@ -438,7 +438,7 @@ async function test_user_acl_roles() { game.setACL(new Parse.ACL(Parse.User.current())); game .save() - .then((game: Game) => {}) + .then((game: Game) => { }) .catch(error => error); await game.save(null, { useMasterKey: true }); game @@ -782,26 +782,26 @@ async function test_cloud_functions() { void Parse.Cloud.getJobsData().then(v => v); // @ts-expect-error - define should not exist on browser Parse.Cloud - Parse.Cloud.define('test', () => {}); + Parse.Cloud.define('test', () => { }); // @ts-expect-error - beforeSave should not exist on browser Parse.Cloud - Parse.Cloud.beforeSave('Test', () => {}); + Parse.Cloud.beforeSave('Test', () => { }); // @ts-expect-error - job should not exist on browser Parse.Cloud - Parse.Cloud.job('test', () => {}); + Parse.Cloud.job('test', () => { }); // @ts-expect-error - httpRequest should not exist on browser Parse.Cloud void Parse.Cloud.httpRequest({ url: '' }); // @ts-expect-error - beforeConnect should not exist on browser Parse.Cloud - Parse.Cloud.beforeConnect(() => {}); + Parse.Cloud.beforeConnect(() => { }); // @ts-expect-error - beforeSubscribe should not exist on browser Parse.Cloud - Parse.Cloud.beforeSubscribe('Test', () => {}); + Parse.Cloud.beforeSubscribe('Test', () => { }); // @ts-expect-error - afterLiveQueryEvent should not exist on browser Parse.Cloud - Parse.Cloud.afterLiveQueryEvent('Test', () => {}); + Parse.Cloud.afterLiveQueryEvent('Test', () => { }); // @ts-expect-error - beforePasswordResetRequest should not exist on browser Parse.Cloud - Parse.Cloud.beforePasswordResetRequest(() => {}); + Parse.Cloud.beforePasswordResetRequest(() => { }); // @ts-expect-error - sendEmail should not exist on browser Parse.Cloud void Parse.Cloud.sendEmail({ to: '' }); } -class PlaceObject extends Parse.Object {} +class PlaceObject extends Parse.Object { } function test_geo_points() { let point = new Parse.GeoPoint(); @@ -835,7 +835,7 @@ function test_geo_points() { const query3 = new Parse.Query('PlaceObject') .find() - .then((o: Parse.Object[]) => {}) + .then((o: Parse.Object[]) => { }) .catch(error => error); } @@ -1126,7 +1126,7 @@ async function test_schema( relationField: Parse.Relation; pointerField: Parse.Pointer | Parse.Object; } - class TestObject extends Parse.Object {} + class TestObject extends Parse.Object { } const schema = new Parse.Schema('TestObject'); schema.addArray('arrField'); @@ -1853,7 +1853,7 @@ function testQuery() { attribute2: number; attribute3: AnotherSubClass; attribute4: string[]; - }> {} + }> { } const query = new Parse.Query(MySubClass); // $ExpectType ParseQuery @@ -2262,10 +2262,10 @@ function testUser() { async function testAuthenticationProvider() { const authProvider: Parse.AuthProvider = { - authenticate: () => {}, + authenticate: () => { }, getAuthType: () => 'customAuthorizationProvider', restoreAuthentication: () => false, - deauthenticate: () => {}, + deauthenticate: () => { }, }; const authData: Parse.AuthData = { id: 'some-user-authentication-id', @@ -2337,9 +2337,9 @@ function testEventuallyQueue() { function LiveQueryEvents() { function testLiveQueryEvents() { - Parse.LiveQuery.on('open', () => {}); - Parse.LiveQuery.on('close', () => {}); - Parse.LiveQuery.on('error', (error: any) => {}); + Parse.LiveQuery.on('open', () => { }); + Parse.LiveQuery.on('close', () => { }); + Parse.LiveQuery.on('error', (error: any) => { }); } } @@ -2363,4 +2363,115 @@ function testInitialize() { // Node - 1 param (should also work since javaScriptKey is optional in node) ParseNode.initialize('appId'); } +async function test_type_regressions() { + // Base type exports + const attributes: Parse.Attributes = { foo: 'bar' }; + const baseAttributes: Parse.BaseAttributes = { + objectId: '123', + createdAt: new Date(), + updatedAt: new Date(), + }; + const jsonBaseAttributes: Parse.JSONBaseAttributes = { + objectId: '123', + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }; + + const subscription: Parse.LiveQuerySubscription = await new Parse.Query('Test').subscribe(); + + const fullOptions: Parse.FullOptions = { + useMasterKey: true, + sessionToken: 'token', + }; + + const signUpOptions: Parse.SignUpOptions = { + useMasterKey: true, + installationId: 'install-123', + }; + + const objectStatic: Parse.ObjectStatic = Parse.Object; + + const restSchema: Parse.RestSchema = { + className: 'Test', + fields: {}, + classLevelPermissions: {}, + }; + + const cloudRunOptions: Parse.Cloud.RunOptions = { + useMasterKey: true, + context: { foo: 'bar' }, + }; + + // Namespace-scoped option types + // Parse.Object options + const destroyOptions: Parse.Object.DestroyOptions = { + useMasterKey: true, + sessionToken: 'token', + }; + + const objectFetchOptions: Parse.Object.FetchOptions = { + useMasterKey: true, + sessionToken: 'token', + include: ['relation1', 'relation2'], + }; + + const saveOptions: Parse.Object.SaveOptions = { + useMasterKey: true, + cascadeSave: false, + context: { key: 'value' }, + }; + + const setOptions: Parse.Object.SetOptions = { + ignoreValidation: true, + unset: false, + }; + + // Parse.Query options + const findOptions: Parse.Query.FindOptions = { + useMasterKey: true, + sessionToken: 'token', + json: true, + }; + + const firstOptions: Parse.Query.FirstOptions = { + useMasterKey: true, + json: false, + }; + + const getOptions: Parse.Query.GetOptions = { + sessionToken: 'token', + }; + + const countOptions: Parse.Query.CountOptions = { + useMasterKey: true, + }; + + const eachOptions: Parse.Query.EachOptions = { + sessionToken: 'token', + }; + + const batchOptions: Parse.Query.BatchOptions = { + batchSize: 100, + useMasterKey: true, + }; + + const fullTextOptions: Parse.Query.FullTextOptions = { + language: 'en', + caseSensitive: false, + diacriticSensitive: true, + }; + + const aggregationOptions: Parse.Query.AggregationOptions = { + group: { objectId: '$category' }, + match: { status: 'active' }, + limit: 100, + sort: { createdAt: -1 }, + }; + + // Parse.Schema.TYPE + const schemaType: Parse.Schema.TYPE = 'String'; + const schemaTypeNumber: Parse.Schema.TYPE = 'Number'; + const schemaTypePointer: Parse.Schema.TYPE = 'Pointer'; + const schemaTypeRelation: Parse.Schema.TYPE = 'Relation'; +} From 3f4d965764232b50409ce84709bb669b12f47c94 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 11:15:03 +0700 Subject: [PATCH 02/25] exported types --- src/ParseObject.ts | 34 +++- src/ParseQuery.ts | 6 +- src/Push.ts | 3 + types/ParseObject.d.ts | 31 ++- types/ParseQuery.d.ts | 6 +- types/Push.d.ts | 2 + types/index.d.ts | 138 +++----------- types/tests.ts | 423 ++++++++++++++++++++++++++++++++++++++--- 8 files changed, 487 insertions(+), 156 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index bd247533d..b8697db54 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -68,6 +68,28 @@ export interface DestroyOptions { useMasterKey?: boolean; sessionToken?: string; context?: AttributeMap; + /** Wait for the server to confirm before resolving */ + wait?: boolean; +} + +/** Options for destroyAll batch operation - matches old namespace Object.DestroyAllOptions */ +export interface DestroyAllOptions { + batchSize?: number; + useMasterKey?: boolean; + sessionToken?: string; +} + +/** Options for saveAll batch operation - matches old namespace Object.SaveAllOptions */ +export interface SaveAllOptions { + batchSize?: number; + useMasterKey?: boolean; + sessionToken?: string; +} + +/** Options for fetchAll batch operation - matches old namespace Object.FetchAllOptions */ +export interface FetchAllOptions { + useMasterKey?: boolean; + sessionToken?: string; } export type AttributeKey = Extract; @@ -94,7 +116,7 @@ type AtomicKey = { [K in keyof T]: NonNullable extends any[] ? K : never; }; -type Encode = T extends ParseObject +export type Encode = T extends ParseObject ? ReturnType | Pointer : T extends ParseACL | ParseGeoPoint | ParsePolygon | ParseRelation | ParseFile ? ReturnType @@ -108,7 +130,7 @@ type Encode = T extends ParseObject ? ToJSON : T; -type ToJSON = { +export type ToJSON = { [K in keyof T]: Encode; }; @@ -1648,7 +1670,7 @@ class ParseObject { * @static * @returns {Parse.Object[]} */ - static fetchAll(list: T[], options?: RequestOptions): Promise { + static fetchAll(list: T[], options?: FetchAllOptions): Promise { const fetchOptions = ParseObject._getRequestOptions(options); return CoreManager.getObjectController().fetch(list, true, fetchOptions) as Promise; } @@ -1759,7 +1781,7 @@ class ParseObject { * @static * @returns {Parse.Object[]} */ - static fetchAllIfNeeded(list: T[], options?: FetchOptions): Promise { + static fetchAllIfNeeded(list: T[], options?: FetchAllOptions): Promise { const fetchOptions = ParseObject._getRequestOptions(options); return CoreManager.getObjectController().fetch(list, false, fetchOptions) as Promise; } @@ -1835,7 +1857,7 @@ class ParseObject { * @returns {Promise} A promise that is fulfilled when the destroyAll * completes. */ - static destroyAll(list: ParseObject[], options?: SaveOptions) { + static destroyAll(list: ParseObject[], options?: DestroyAllOptions) { const destroyOptions = ParseObject._getRequestOptions(options); return CoreManager.getObjectController().destroy(list, destroyOptions); } @@ -1869,7 +1891,7 @@ class ParseObject { * @static * @returns {Parse.Object[]} */ - static saveAll(list: T, options?: SaveOptions): Promise { + static saveAll(list: T, options?: SaveAllOptions): Promise { const saveOptions = ParseObject._getRequestOptions(options); return CoreManager.getObjectController().save(list, saveOptions) as any; } diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index f1bf80f2e..8a5fbe541 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -11,7 +11,7 @@ import type LiveQuerySubscription from './LiveQuerySubscription'; import type { RequestOptions, FullOptions } from './RESTController'; import type { Pointer } from './ParseObject'; -type BatchOptions = FullOptions & { +export type BatchOptions = FullOptions & { batchSize?: number; useMasterKey?: boolean; useMaintenanceKey?: boolean; @@ -32,7 +32,7 @@ export interface QueryOptions { /** Alias for QueryOptions, used for find operations */ export type FindOptions = QueryOptions; -interface FullTextQueryOptions { +export interface FullTextOptions { language?: string; caseSensitive?: boolean; diacriticSensitive?: boolean; @@ -1524,7 +1524,7 @@ class ParseQuery { fullText( key: K, value: string, - options?: FullTextQueryOptions + options?: FullTextOptions ): this { options = options || {}; diff --git a/src/Push.ts b/src/Push.ts index 366628e68..fd6c94682 100644 --- a/src/Push.ts +++ b/src/Push.ts @@ -14,6 +14,9 @@ export interface PushData { channels?: string[]; } +/** Options for Push.send operation */ +export type SendOptions = FullOptions; + /** * Contains functions to deal with Push in Parse. * diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index f04257260..af55a2526 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -38,6 +38,25 @@ export interface DestroyOptions { useMasterKey?: boolean; sessionToken?: string; context?: AttributeMap; + /** Wait for the server to confirm before resolving */ + wait?: boolean; +} +/** Options for destroyAll batch operation - matches old namespace Object.DestroyAllOptions */ +export interface DestroyAllOptions { + batchSize?: number; + useMasterKey?: boolean; + sessionToken?: string; +} +/** Options for saveAll batch operation - matches old namespace Object.SaveAllOptions */ +export interface SaveAllOptions { + batchSize?: number; + useMasterKey?: boolean; + sessionToken?: string; +} +/** Options for fetchAll batch operation - matches old namespace Object.FetchAllOptions */ +export interface FetchAllOptions { + useMasterKey?: boolean; + sessionToken?: string; } export type AttributeKey = Extract; export type Attributes = Record; @@ -57,11 +76,11 @@ interface CommonAttributes { type AtomicKey = { [K in keyof T]: NonNullable extends any[] ? K : never; }; -type Encode = T extends ParseObject ? ReturnType | Pointer : T extends ParseACL | ParseGeoPoint | ParsePolygon | ParseRelation | ParseFile ? ReturnType : T extends Date ? { +export type Encode = T extends ParseObject ? ReturnType | Pointer : T extends ParseACL | ParseGeoPoint | ParsePolygon | ParseRelation | ParseFile ? ReturnType : T extends Date ? { __type: 'Date'; iso: string; } : T extends RegExp ? string : T extends (infer R)[] ? Encode[] : T extends object ? ToJSON : T; -type ToJSON = { +export type ToJSON = { [K in keyof T]: Encode; }; /** @@ -711,7 +730,7 @@ declare class ParseObject { * @static * @returns {Parse.Object[]} */ - static fetchAll(list: T[], options?: RequestOptions): Promise; + static fetchAll(list: T[], options?: FetchAllOptions): Promise; /** * Fetches the given list of Parse.Object. * @@ -800,7 +819,7 @@ declare class ParseObject { * @static * @returns {Parse.Object[]} */ - static fetchAllIfNeeded(list: T[], options?: FetchOptions): Promise; + static fetchAllIfNeeded(list: T[], options?: FetchAllOptions): Promise; static handleIncludeOptions(options: { include?: string | string[]; }): any[]; @@ -859,7 +878,7 @@ declare class ParseObject { * @returns {Promise} A promise that is fulfilled when the destroyAll * completes. */ - static destroyAll(list: ParseObject[], options?: SaveOptions): Promise | ParseObject[]>; + static destroyAll(list: ParseObject[], options?: DestroyAllOptions): Promise | ParseObject[]>; /** * Saves the given list of Parse.Object. * If any error is encountered, stops and calls the error handler. @@ -889,7 +908,7 @@ declare class ParseObject { * @static * @returns {Parse.Object[]} */ - static saveAll(list: T, options?: SaveOptions): Promise; + static saveAll(list: T, options?: SaveAllOptions): Promise; /** * Creates a reference to a subclass of Parse.Object with the given id. This * does not exist on Parse.Object, only on subclasses. diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index c05b0cabc..af10b8a02 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -3,7 +3,7 @@ import ParseObject from './ParseObject'; import type LiveQuerySubscription from './LiveQuerySubscription'; import type { FullOptions } from './RESTController'; import type { Pointer } from './ParseObject'; -type BatchOptions = FullOptions & { +export type BatchOptions = FullOptions & { batchSize?: number; useMasterKey?: boolean; useMaintenanceKey?: boolean; @@ -20,7 +20,7 @@ export interface QueryOptions { } /** Alias for QueryOptions, used for find operations */ export type FindOptions = QueryOptions; -interface FullTextQueryOptions { +export interface FullTextOptions { language?: string; caseSensitive?: boolean; diacriticSensitive?: boolean; @@ -627,7 +627,7 @@ declare class ParseQuery { * @param {boolean} options.diacriticSensitive A boolean flag to enable or disable diacritic sensitive search. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - fullText(key: K, value: string, options?: FullTextQueryOptions): this; + fullText(key: K, value: string, options?: FullTextOptions): this; /** * Method to sort the full text search by text score * diff --git a/types/Push.d.ts b/types/Push.d.ts index db926e9dc..191659526 100644 --- a/types/Push.d.ts +++ b/types/Push.d.ts @@ -10,6 +10,8 @@ export interface PushData { data?: any; channels?: string[]; } +/** Options for Push.send operation */ +export type SendOptions = FullOptions; /** * Contains functions to deal with Push in Parse. * diff --git a/types/index.d.ts b/types/index.d.ts index b18c73fc0..de88ced2d 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -35,10 +35,11 @@ import User from './ParseUser'; import LiveQuerySubscription from './LiveQuerySubscription'; export type { AuthProvider, AuthData, SignUpOptions } from './ParseUser'; -export type { Pointer, Attributes, BaseAttributes, JSONBaseAttributes, ObjectStatic, FetchOptions as ObjectFetchOptions, SaveOptions as ObjectSaveOptions, SetOptions as ObjectSetOptions, DestroyOptions as ObjectDestroyOptions } from './ParseObject'; +export type { Pointer, Attributes, BaseAttributes, JSONBaseAttributes, ObjectStatic, FetchOptions, SaveOptions, SetOptions, DestroyOptions, DestroyAllOptions, SaveAllOptions, FetchAllOptions, Encode, ToJSON } from './ParseObject'; +export type { PushData, SendOptions } from './Push'; export type { FullOptions, RequestOptions } from './RESTController'; export type { RestSchema, TYPE } from './ParseSchema'; -export type { FindOptions, QueryOptions, QueryJSON, WhereClause } from './ParseQuery'; +export type { FindOptions, QueryOptions, QueryJSON, WhereClause, BatchOptions, FullTextOptions } from './ParseQuery'; export { LiveQuerySubscription }; export { ACL, @@ -70,125 +71,30 @@ export { Hooks, }; -// Namespace-scoped option types for backwards compatibility -// These augment the class namespaces with additional types +// ============================================================================ +// Namespace re-exports for backward compatibility +// These enable Parse.Object.FetchOptions, Parse.Query.FindOptions etc. +// ============================================================================ + export namespace Object { - /** Options for destroying objects */ - export interface DestroyOptions { - useMasterKey?: boolean; - sessionToken?: string; - context?: Record; - } - /** Options for fetching objects */ - export interface FetchOptions { - useMasterKey?: boolean; - sessionToken?: string; - include?: string | string[]; - context?: Record; - } - /** Options for saving objects */ - export interface SaveOptions { - useMasterKey?: boolean; - sessionToken?: string; - cascadeSave?: boolean; - context?: Record; - } - /** Options for setting attributes */ - export interface SetOptions { - ignoreValidation?: boolean; - unset?: boolean; - } + export type DestroyOptions = import('./ParseObject').DestroyOptions; + export type DestroyAllOptions = import('./ParseObject').DestroyAllOptions; + export type FetchOptions = import('./ParseObject').FetchOptions; + export type FetchAllOptions = import('./ParseObject').FetchAllOptions; + export type SaveOptions = import('./ParseObject').SaveOptions; + export type SaveAllOptions = import('./ParseObject').SaveAllOptions; + export type SetOptions = import('./ParseObject').SetOptions; + export type Encode = import('./ParseObject').Encode; + export type ToJSON = import('./ParseObject').ToJSON; } export namespace Query { - /** Options for find operations */ - export interface FindOptions { - useMasterKey?: boolean; - sessionToken?: string; - context?: Record; - json?: boolean; - } - /** Options for first operations */ - export interface FirstOptions { - useMasterKey?: boolean; - sessionToken?: string; - context?: Record; - json?: boolean; - } - /** Options for get operations */ - export interface GetOptions { - useMasterKey?: boolean; - sessionToken?: string; - context?: Record; - json?: boolean; - } - /** Options for count operations */ - export interface CountOptions { - useMasterKey?: boolean; - sessionToken?: string; - } - /** Options for each operations */ - export interface EachOptions { - useMasterKey?: boolean; - sessionToken?: string; - } - /** Options for batch operations */ - export interface BatchOptions { - useMasterKey?: boolean; - useMaintenanceKey?: boolean; - sessionToken?: string; - batchSize?: number; - context?: Record; - json?: boolean; - } - /** Options for full text search */ - export interface FullTextOptions { - language?: string; - caseSensitive?: boolean; - diacriticSensitive?: boolean; - } - /** Options for aggregation queries */ - export interface AggregationOptions { - group?: (Record & { objectId?: string }); - match?: Record; - project?: Record; - limit?: number; - skip?: number; - sort?: Record; - sample?: { size: number }; - count?: string; - lookup?: { - from: string; - localField: string; - foreignField: string; - as: string; - } | { - from: string; - let?: Record; - pipeline: Record; - as: string; - }; - graphLookup?: { - from: string; - startWith?: string; - connectFromField: string; - connectToField: string; - as: string; - maxDepth?: number; - depthField?: string; - restrictSearchWithMatch?: Record; - }; - facet?: Record>>; - unwind?: { - path: string; - includeArrayIndex?: string; - preserveNullAndEmptyArrays?: boolean; - } | string; - } + export type FindOptions = import('./ParseQuery').FindOptions; + export type QueryOptions = import('./ParseQuery').QueryOptions; + export type BatchOptions = import('./ParseQuery').BatchOptions; + export type FullTextOptions = import('./ParseQuery').FullTextOptions; } export namespace Schema { - /** Field type for Parse Schema */ - export type TYPE = 'String' | 'Number' | 'Bytes' | 'Boolean' | 'Date' | 'File' | 'GeoPoint' | 'Polygon' | 'Array' | 'Object' | 'Pointer' | 'Relation'; + export type TYPE = import('./ParseSchema').TYPE; } - diff --git a/types/tests.ts b/types/tests.ts index 2a30047e2..c089fb69a 100644 --- a/types/tests.ts +++ b/types/tests.ts @@ -2402,8 +2402,11 @@ async function test_type_regressions() { context: { foo: 'bar' }, }; - // Namespace-scoped option types - // Parse.Object options + // ============================================= + // Namespace-scoped option types (Parse.Object.*, Parse.Query.*, Parse.Schema.*) + // ============================================= + + // Parse.Object namespace const destroyOptions: Parse.Object.DestroyOptions = { useMasterKey: true, sessionToken: 'token', @@ -2411,67 +2414,443 @@ async function test_type_regressions() { const objectFetchOptions: Parse.Object.FetchOptions = { useMasterKey: true, - sessionToken: 'token', include: ['relation1', 'relation2'], }; const saveOptions: Parse.Object.SaveOptions = { useMasterKey: true, cascadeSave: false, - context: { key: 'value' }, }; const setOptions: Parse.Object.SetOptions = { ignoreValidation: true, - unset: false, }; - // Parse.Query options + const destroyAllOptions: Parse.Object.DestroyAllOptions = { + batchSize: 100, + useMasterKey: true, + }; + + const saveAllOptions: Parse.Object.SaveAllOptions = { + batchSize: 50, + useMasterKey: true, + }; + + const fetchAllOptions: Parse.Object.FetchAllOptions = { + useMasterKey: true, + sessionToken: 'token', + }; + + // Parse.Query namespace const findOptions: Parse.Query.FindOptions = { useMasterKey: true, sessionToken: 'token', + }; + + // Parse.Schema namespace + const schemaType: Parse.Schema.TYPE = 'String'; + const schemaTypeNumber: Parse.Schema.TYPE = 'Number'; + const schemaTypePointer: Parse.Schema.TYPE = 'Pointer'; + const schemaTypeRelation: Parse.Schema.TYPE = 'Relation'; + + // Push types + const pushData: Parse.PushData = { + channels: ['news'], + data: { alert: 'Hello' }, + }; + + const sendOptions: Parse.SendOptions = { + useMasterKey: true, + }; +} + +// ============================================= +// COMPREHENSIVE TYPE EXPORT TESTS +// Tests for all types restored from old-types.d.ts +// ============================================= + +function test_restored_types_parseobject_namespace() { + // ============================================= + // Parse.Object.* namespace types + // ============================================= + + // Parse.Object.DestroyOptions + const destroyOpts1: Parse.Object.DestroyOptions = {}; + const destroyOpts2: Parse.Object.DestroyOptions = { + useMasterKey: true, + sessionToken: 'session-token', + }; + + // Parse.Object.DestroyAllOptions + const destroyAllOpts1: Parse.Object.DestroyAllOptions = {}; + const destroyAllOpts2: Parse.Object.DestroyAllOptions = { + batchSize: 100, + useMasterKey: true, + sessionToken: 'session-token', + }; + + // Parse.Object.FetchOptions + const fetchOpts1: Parse.Object.FetchOptions = {}; + const fetchOpts2: Parse.Object.FetchOptions = { + useMasterKey: true, + sessionToken: 'session-token', + include: ['pointer1', 'pointer2'], + }; + + // Parse.Object.FetchAllOptions + const fetchAllOpts1: Parse.Object.FetchAllOptions = {}; + const fetchAllOpts2: Parse.Object.FetchAllOptions = { + useMasterKey: true, + sessionToken: 'session-token', + }; + + // Parse.Object.SaveOptions + const saveOpts1: Parse.Object.SaveOptions = {}; + const saveOpts2: Parse.Object.SaveOptions = { + useMasterKey: true, + sessionToken: 'session-token', + cascadeSave: false, + context: { key: 'value' }, + }; + + // Parse.Object.SaveAllOptions + const saveAllOpts1: Parse.Object.SaveAllOptions = {}; + const saveAllOpts2: Parse.Object.SaveAllOptions = { + batchSize: 50, + useMasterKey: true, + sessionToken: 'session-token', + }; + + // Parse.Object.SetOptions + const setOpts1: Parse.Object.SetOptions = {}; + const setOpts2: Parse.Object.SetOptions = { + ignoreValidation: true, + }; + + // Parse.Object.Encode - utility type for encoding ParseObject to JSON + type TestEncodeString = Parse.Object.Encode; // string + type TestEncodeNumber = Parse.Object.Encode; // number + type TestEncodeDate = Parse.Object.Encode; // { __type: 'Date'; iso: string } + type TestEncodeObject = Parse.Object.Encode; // ReturnType | Pointer + + // Parse.Object.ToJSON - utility type for converting object properties + type TestToJSON = Parse.Object.ToJSON<{ name: string; count: number }>; +} + +function test_restored_types_parsequery_namespace() { + // ============================================= + // Parse.Query.* namespace types + // ============================================= + + // Parse.Query.QueryOptions - base query options + const queryOpts1: Parse.Query.QueryOptions = {}; + const queryOpts2: Parse.Query.QueryOptions = { + useMasterKey: true, + sessionToken: 'session-token', + context: { key: 'value' }, json: true, }; - const firstOptions: Parse.Query.FirstOptions = { + // Parse.Query.FindOptions - alias for QueryOptions + const findOpts1: Parse.Query.FindOptions = {}; + const findOpts2: Parse.Query.FindOptions = { useMasterKey: true, + sessionToken: 'session-token', + context: { key: 'value' }, json: false, }; - const getOptions: Parse.Query.GetOptions = { + // Parse.Query.BatchOptions - for batch operations like each(), eachBatch() + const batchOpts1: Parse.Query.BatchOptions = {}; + const batchOpts2: Parse.Query.BatchOptions = { + batchSize: 100, + useMasterKey: true, + sessionToken: 'session-token', + context: { key: 'value' }, + json: true, + }; + + // Parse.Query.FullTextOptions - for fullText() query method + const fullTextOpts1: Parse.Query.FullTextOptions = {}; + const fullTextOpts2: Parse.Query.FullTextOptions = { + language: 'en', + caseSensitive: true, + diacriticSensitive: false, + }; +} + +function test_restored_types_parseschema_namespace() { + // ============================================= + // Parse.Schema.* namespace types + // ============================================= + + // Parse.Schema.TYPE - all valid schema field types + const typeString: Parse.Schema.TYPE = 'String'; + const typeNumber: Parse.Schema.TYPE = 'Number'; + const typeBytes: Parse.Schema.TYPE = 'Bytes'; + const typeBoolean: Parse.Schema.TYPE = 'Boolean'; + const typeDate: Parse.Schema.TYPE = 'Date'; + const typeFile: Parse.Schema.TYPE = 'File'; + const typeGeoPoint: Parse.Schema.TYPE = 'GeoPoint'; + const typePolygon: Parse.Schema.TYPE = 'Polygon'; + const typeArray: Parse.Schema.TYPE = 'Array'; + const typeObject: Parse.Schema.TYPE = 'Object'; + const typePointer: Parse.Schema.TYPE = 'Pointer'; + const typeRelation: Parse.Schema.TYPE = 'Relation'; +} + +function test_restored_types_direct_exports() { + // ============================================= + // Direct Parse.* exports (top-level) + // These should be accessible directly from Parse namespace + // ============================================= + + // Parse.DestroyOptions (same as Parse.Object.DestroyOptions) + const directDestroyOpts: Parse.DestroyOptions = { + useMasterKey: true, sessionToken: 'token', }; - const countOptions: Parse.Query.CountOptions = { + // Parse.FetchOptions (same as Parse.Object.FetchOptions) + const directFetchOpts: Parse.FetchOptions = { useMasterKey: true, + include: ['relation'], }; - const eachOptions: Parse.Query.EachOptions = { + // Parse.SaveOptions (same as Parse.Object.SaveOptions) + const directSaveOpts: Parse.SaveOptions = { + useMasterKey: true, + cascadeSave: true, + context: { key: 'value' }, + }; + + // Parse.SetOptions (same as Parse.Object.SetOptions) + const directSetOpts: Parse.SetOptions = { + ignoreValidation: false, + }; + + // Parse.DestroyAllOptions + const directDestroyAllOpts: Parse.DestroyAllOptions = { + batchSize: 100, + useMasterKey: true, + }; + + // Parse.SaveAllOptions + const directSaveAllOpts: Parse.SaveAllOptions = { + batchSize: 50, + sessionToken: 'token', + }; + + // Parse.FetchAllOptions + const directFetchAllOpts: Parse.FetchAllOptions = { + useMasterKey: true, + }; + + // Parse.QueryOptions (same as Parse.Query.QueryOptions) + const directQueryOpts: Parse.QueryOptions = { + useMasterKey: true, sessionToken: 'token', + json: true, + }; + + // Parse.FindOptions (same as Parse.Query.FindOptions) + const directFindOpts: Parse.FindOptions = { + useMasterKey: true, + context: { key: 'value' }, }; - const batchOptions: Parse.Query.BatchOptions = { + // Parse.BatchOptions (same as Parse.Query.BatchOptions) + const directBatchOpts: Parse.BatchOptions = { batchSize: 100, useMasterKey: true, + json: false, }; - const fullTextOptions: Parse.Query.FullTextOptions = { + // Parse.FullTextOptions (same as Parse.Query.FullTextOptions) + const directFullTextOpts: Parse.FullTextOptions = { language: 'en', caseSensitive: false, diacriticSensitive: true, }; - const aggregationOptions: Parse.Query.AggregationOptions = { - group: { objectId: '$category' }, - match: { status: 'active' }, - limit: 100, - sort: { createdAt: -1 }, + // Parse.TYPE (same as Parse.Schema.TYPE) + const directType: Parse.TYPE = 'String'; + + // Parse.Pointer - object pointer type + const pointer: Parse.Pointer = { + __type: 'Pointer', + className: 'GameScore', + objectId: 'abc123', }; - // Parse.Schema.TYPE - const schemaType: Parse.Schema.TYPE = 'String'; - const schemaTypeNumber: Parse.Schema.TYPE = 'Number'; - const schemaTypePointer: Parse.Schema.TYPE = 'Pointer'; - const schemaTypeRelation: Parse.Schema.TYPE = 'Relation'; + // Parse.Attributes - base attributes type + const attrs: Parse.Attributes = { + score: 100, + playerName: 'John', + }; + + // Parse.BaseAttributes - standard object attributes + const baseAttrs: Parse.BaseAttributes = { + createdAt: new Date(), + updatedAt: new Date(), + objectId: 'abc123', + }; + + // Parse.JSONBaseAttributes - JSON representation of base attributes + const jsonBaseAttrs: Parse.JSONBaseAttributes = { + createdAt: '2023-01-01T00:00:00.000Z', + updatedAt: '2023-01-01T00:00:00.000Z', + objectId: 'abc123', + }; + + // Parse.Encode - utility type + type DirectEncode = Parse.Encode; + + // Parse.ToJSON - utility type + type DirectToJSON = Parse.ToJSON<{ name: string }>; + + // Parse.WhereClause - query where clause type + const whereClause: Parse.WhereClause = { + score: { $gt: 100 }, + playerName: 'John', + }; + + // Parse.QueryJSON - serialized query representation + const queryJson: Parse.QueryJSON = { + where: { score: { $gt: 100 } }, + limit: 10, + skip: 0, + order: 'score', + include: 'player', + keys: 'score,playerName', + }; + + // Parse.RestSchema - schema REST representation + const restSchema: Parse.RestSchema = { + className: 'GameScore', + fields: { + objectId: { type: 'String' }, + createdAt: { type: 'Date' }, + updatedAt: { type: 'Date' }, + ACL: { type: 'ACL' }, + score: { type: 'Number' }, + }, + classLevelPermissions: { + find: { '*': true }, + get: { '*': true }, + create: { '*': true }, + update: { '*': true }, + delete: { '*': true }, + }, + }; + + // Parse.FullOptions - full request options + const fullOpts: Parse.FullOptions = { + useMasterKey: true, + sessionToken: 'token', + installationId: 'install-id', + }; + + // Parse.RequestOptions - request options + const requestOpts: Parse.RequestOptions = { + useMasterKey: true, + sessionToken: 'token', + installationId: 'install-id', + batchSize: 50, + include: ['relation'], + }; + + // Parse.AuthProvider - authentication provider interface + const authProvider: Parse.AuthProvider = { + authenticate: () => { }, + getAuthType: () => 'custom', + restoreAuthentication: () => true, + deauthenticate: () => { }, + }; + + // Parse.AuthData - authentication data + const authData: Parse.AuthData = { + id: 'user-id', + access_token: 'token', + }; + + // Parse.SignUpOptions - user signup options + const signUpOpts: Parse.SignUpOptions = { + useMasterKey: true, + installationId: 'install-id', + }; + + // Parse.PushData - push notification data + const pushData: Parse.PushData = { + channels: ['news', 'updates'], + data: { alert: 'Hello World!' }, + }; + + // Parse.SendOptions - push send options + const sendOpts: Parse.SendOptions = { + useMasterKey: true, + }; +} + +async function test_restored_types_usage_in_methods() { + // ============================================= + // Verify types work correctly with actual Parse methods + // ============================================= + + const obj = new Parse.Object('TestClass'); + const query = new Parse.Query('TestClass'); + + // save() accepts SaveOptions + const saveOpts: Parse.SaveOptions = { useMasterKey: true, cascadeSave: false }; + await obj.save(null, saveOpts); + + // fetch() accepts FetchOptions + const fetchOpts: Parse.FetchOptions = { useMasterKey: true, include: ['relation'] }; + await obj.fetch(fetchOpts); + + // destroy() accepts DestroyOptions + const destroyOpts: Parse.DestroyOptions = { useMasterKey: true }; + await obj.destroy(destroyOpts); + + // set() accepts SetOptions + const setOpts: Parse.SetOptions = { ignoreValidation: true }; + obj.set('key', 'value', setOpts); + + // Parse.Object.saveAll accepts SaveAllOptions + const saveAllOpts: Parse.SaveAllOptions = { batchSize: 50, useMasterKey: true }; + await Parse.Object.saveAll([obj], saveAllOpts); + + // Parse.Object.destroyAll accepts DestroyAllOptions + const destroyAllOpts: Parse.DestroyAllOptions = { batchSize: 100, useMasterKey: true }; + await Parse.Object.destroyAll([obj], destroyAllOpts); + + // Parse.Object.fetchAll accepts FetchAllOptions + const fetchAllOpts: Parse.FetchAllOptions = { useMasterKey: true }; + await Parse.Object.fetchAll([obj], fetchAllOpts); + + // query.find() accepts FindOptions/QueryOptions + const findOpts: Parse.FindOptions = { useMasterKey: true, json: true }; + await query.find(findOpts); + + // query.first() accepts QueryOptions + const queryOpts: Parse.QueryOptions = { useMasterKey: true }; + await query.first(queryOpts); + + // query.get() accepts QueryOptions + await query.get('objectId', queryOpts); + + // query.count() accepts QueryOptions + await query.count(queryOpts); + + // query.each() accepts BatchOptions + const batchOpts: Parse.BatchOptions = { batchSize: 100, useMasterKey: true }; + await query.each(() => { }, batchOpts); + + // query.eachBatch() accepts BatchOptions + await query.eachBatch(() => { }, batchOpts); + + // query.fullText() accepts FullTextOptions + const fullTextOpts: Parse.FullTextOptions = { language: 'en', caseSensitive: false }; + query.fullText('field', 'search term', fullTextOpts); } From 9eede2cada4f5e89c50ea1e9daf677a501bdaccd Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 11:23:51 +0700 Subject: [PATCH 03/25] removed legacy types file --- old-types.d.ts | 1996 ------------------------------------------------ 1 file changed, 1996 deletions(-) delete mode 100644 old-types.d.ts diff --git a/old-types.d.ts b/old-types.d.ts deleted file mode 100644 index df3c7045f..000000000 --- a/old-types.d.ts +++ /dev/null @@ -1,1996 +0,0 @@ -/// -/// -/// - -import { EventEmitter } from "events"; - -declare enum ErrorCode { - /** Error code indicating some error other than those enumerated here */ - OTHER_CAUSE = -1, - /** Error code indicating that something has gone wrong with the server. */ - INTERNAL_SERVER_ERROR = 1, - /** Error code indicating the connection to the Parse servers failed. */ - CONNECTION_FAILED = 100, - /** Error code indicating the specified object doesn't exist. */ - OBJECT_NOT_FOUND = 101, - /** - * Error code indicating you tried to query with a datatype that doesn't - * support it, like exact matching an array or object. - */ - INVALID_QUERY = 102, - /* - * Error code indicating a missing or invalid classname. Classnames are - * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the - * only valid characters. - */ - INVALID_CLASS_NAME = 103, - /** Error code indicating an unspecified object id. */ - MISSING_OBJECT_ID = 104, - /** - * Error code indicating an invalid key name. Keys are case-sensitive. They - * must start with a letter, and a-zA-Z0-9_ are the only valid characters. - */ - INVALID_KEY_NAME = 105, - /** - * Error code indicating a malformed pointer. You should not see this unless - * you have been mucking about changing internal Parse code. - */ - INVALID_POINTER = 106, - /* - * Error code indicating that badly formed JSON was received upstream. This - * either indicates you have done something unusual with modifying how - * things encode to JSON, or the network is failing badly. - */ - INVALID_JSON = 107, - /** - * Error code indicating that the feature you tried to access is only - * available internally for testing purposes. - */ - COMMAND_UNAVAILABLE = 108, - /** You must call Parse.initialize before using the Parse library. */ - NOT_INITIALIZED = 109, - /** Error code indicating that a field was set to an inconsistent type. */ - INCORRECT_TYPE = 111, - /** - * Error code indicating an invalid channel name. A channel name is either - * an empty string (the broadcast channel) or contains only a-zA-Z0-9_ - * characters and starts with a letter. - */ - INVALID_CHANNEL_NAME = 112, - /** Error code indicating that push is misconfigured. */ - PUSH_MISCONFIGURED = 115, - /** Error code indicating that the object is too large. */ - OBJECT_TOO_LARGE = 116, - /** Error code indicating that the operation isn't allowed for clients. */ - OPERATION_FORBIDDEN = 119, - /** Error code indicating the result was not found in the cache. */ - CACHE_MISS = 120, - /** Error code indicating that an invalid key was used in a nested JSONObject. */ - INVALID_NESTED_KEY = 121, - /** - * Error code indicating that an invalid filename was used for ParseFile. - * A valid file name contains only a-zA-Z0-9_. characters and is between 1 - * and 128 characters. - */ - INVALID_FILE_NAME = 122, - /** Error code indicating an invalid ACL was provided. */ - INVALID_ACL = 123, - /** - * Error code indicating that the request timed out on the server. Typically - * this indicates that the request is too expensive to run. - */ - TIMEOUT = 124, - /** Error code indicating that the email address was invalid. */ - INVALID_EMAIL_ADDRESS = 125, - /** Error code indicating a missing content type. */ - MISSING_CONTENT_TYPE = 126, - /** Error code indicating a missing content length. */ - MISSING_CONTENT_LENGTH = 127, - /** Error code indicating an invalid content length. */ - INVALID_CONTENT_LENGTH = 128, - /** Error code indicating a file that was too large. */ - FILE_TOO_LARGE = 129, - /** Error code indicating an error saving a file. */ - FILE_SAVE_ERROR = 130, - /** - * Error code indicating that a unique field was given a value that is - * already taken. - */ - DUPLICATE_VALUE = 137, - /** Error code indicating that a role's name is invalid. */ - INVALID_ROLE_NAME = 139, - /** - * Error code indicating that an application quota was exceeded. - * Upgrade to resolve. - */ - EXCEEDED_QUOTA = 140, - /** Error code indicating that a Cloud Code script failed. */ - SCRIPT_FAILED = 141, - /** Error code indicating that a Cloud Code validation failed. */ - VALIDATION_ERROR = 142, - /** Error code indicating that invalid image data was provided. */ - INVALID_IMAGE_DATA = 150, - /** Error code indicating an unsaved file. */ - UNSAVED_FILE_ERROR = 151, - /** Error code indicating an invalid push time. */ - INVALID_PUSH_TIME_ERROR = 152, - /** Error code indicating an error deleting a file. */ - FILE_DELETE_ERROR = 153, - /** Error code indicating that the application has exceeded its request limit. */ - REQUEST_LIMIT_EXCEEDED = 155, - /** - * Error code indicating that the request was a duplicate and has been discarded due to - * idempotency rules. - */ - DUPLICATE_REQUEST = 159, - /** Error code indicating an invalid event name. */ - INVALID_EVENT_NAME = 160, - /** Error code indicating an error deleting an unnamed file. */ - FILE_DELETE_UNNAMED_ERROR = 161, - /** Error code indicating that the username is missing or empty. */ - USERNAME_MISSING = 200, - /** Error code indicating that the password is missing or empty. */ - PASSWORD_MISSING = 201, - /** Error code indicating that the username has already been taken. */ - USERNAME_TAKEN = 202, - /** Error code indicating that the email has already been taken. */ - EMAIL_TAKEN = 203, - /** Error code indicating that the email is missing, but must be specified. */ - EMAIL_MISSING = 204, - /** Error code indicating that a user with the specified email was not found. */ - EMAIL_NOT_FOUND = 205, - /** - * Error code indicating that a user object without a valid session could - * not be altered. - */ - SESSION_MISSING = 206, - /** Error code indicating that a user can only be created through signup. */ - MUST_CREATE_USER_THROUGH_SIGNUP = 207, - /** - * Error code indicating that an an account being linked is already linked - * to another user. - */ - ACCOUNT_ALREADY_LINKED = 208, - /** Error code indicating that the current session token is invalid. */ - INVALID_SESSION_TOKEN = 209, - /** Error code indicating an error enabling or verifying MFA */ - MFA_ERROR = 210, - /** Error code indicating that a valid MFA token must be provided */ - MFA_TOKEN_REQUIRED = 211, - /** - * Error code indicating that a user cannot be linked to an account because - * that account's id could not be found. - */ - LINKED_ID_MISSING = 250, - /** - * Error code indicating that a user with a linked (e.g. Facebook) account - * has an invalid session. - */ - INVALID_LINKED_SESSION = 251, - /** - * Error code indicating that a service being linked (e.g. Facebook or - * Twitter) is unsupported. - */ - UNSUPPORTED_SERVICE = 252, - /** Error code indicating an invalid operation occured on schema */ - INVALID_SCHEMA_OPERATION = 255, - /** - * Error code indicating that there were multiple errors. Aggregate errors - * have an "errors" property, which is an array of error objects with more - * detail about each error that occurred. - */ - AGGREGATE_ERROR = 600, - /** Error code indicating the client was unable to read an input file. */ - FILE_READ_ERROR = 601, - /* - * Error code indicating a real error code is unavailable because - * we had to use an XDomainRequest object to allow CORS requests in - * Internet Explorer, which strips the body from HTTP responses that have - * a non-2XX status code. - */ - X_DOMAIN_REQUEST = 602, -} - -declare global { - namespace Parse { - let applicationId: string; - let javaScriptKey: string | undefined; - let liveQueryServerURL: string; - let masterKey: string | undefined; - let serverAuthToken: string | undefined; - let serverAuthType: string | undefined; - let serverURL: string; - let secret: string; - let idempotency: boolean; - let encryptedUser: boolean; - - interface BatchSizeOption { - batchSize?: number | undefined; - } - - interface CascadeSaveOption { - /** If `false`, nested objects will not be saved (default is `true`). */ - cascadeSave?: boolean | undefined; - } - - interface SuccessOption { - success?: Function | undefined; - } - - interface ErrorOption { - error?: Function | undefined; - } - - interface ContextOption { - context?: { [key: string]: any }; - } - - interface FullOptions { - success?: Function | undefined; - error?: Function | undefined; - useMasterKey?: boolean | undefined; - sessionToken?: string | undefined; - installationId?: string | undefined; - progress?: Function | undefined; - /** - * logIn will default to POST instead of GET method since - * version 3.0.0 for security reasons. - * If you need to use GET set this to `false`. - */ - usePost?: boolean; - } - - interface RequestOptions { - useMasterKey?: boolean | undefined; - sessionToken?: string | undefined; - installationId?: string | undefined; - batchSize?: number | undefined; - include?: string | string[] | undefined; - progress?: Function | undefined; - } - - interface SuccessFailureOptions extends SuccessOption, ErrorOption {} - - interface SignUpOptions { - useMasterKey?: boolean | undefined; - installationId?: string | undefined; - } - - interface SessionTokenOption { - sessionToken?: string | undefined; - } - - interface WaitOption { - /** - * Set to true to wait for the server to confirm success - * before triggering an event. - */ - wait?: boolean | undefined; - } - - interface UseMasterKeyOption { - /** - * In Cloud Code and Node only, causes the Master Key to be used for this request. - */ - useMasterKey?: boolean | undefined; - } - - /** - * https://github.com/parse-community/Parse-SDK-JS/pull/1294/files - * feat: Add option to return raw json from queries - */ - interface RawJSONOptions { - /** (3.0.0+) json: Return raw json without converting to Parse.Object */ - json?: boolean; - } - interface ScopeOptions extends SessionTokenOption, UseMasterKeyOption {} - - interface SilentOption { - /** - * Set to true to avoid firing the event. - */ - silent?: boolean | undefined; - } - - interface Pointer { - __type: string; - className: string; - objectId: string; - } - - interface AuthData { - [key: string]: any; - } - - /** - * Interface declaration for Authentication Providers - * https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html - */ - interface AuthProvider { - /** - * Called when _linkWith isn't passed authData. Handle your own authentication here. - */ - authenticate: () => void; - /** - * (Optional) Called when service is unlinked. Handle any cleanup here. - */ - deauthenticate?: (() => void) | undefined; - /** - * Unique identifier for this Auth Provider. - */ - getAuthType: () => string; - /** - * Called when auth data is syncronized. Can be used to determine if authData is still valid - */ - restoreAuthentication: () => boolean; - } - - interface BaseAttributes { - createdAt: Date; - objectId: string; - updatedAt: Date; - } - - interface CommonAttributes { - ACL: ACL; - } - - interface JSONBaseAttributes { - createdAt: string; - objectId: string; - updatedAt: string; - } - - /** - * Creates a new ACL. - * If no argument is given, the ACL has no permissions for anyone. - * If the argument is a Parse.User, the ACL will have read and write - * permission for only that user. - * If the argument is any other JSON object, that object will be interpretted - * as a serialized ACL created with toJSON(). - * @see Parse.Object#setACL - * - *

An ACL, or Access Control List can be added to any - * Parse.Object to restrict access to only a subset of users - * of your application.

- */ - class ACL { - permissionsById: any; - - constructor(arg1?: any); - - setPublicReadAccess(allowed: boolean): void; - getPublicReadAccess(): boolean; - - setPublicWriteAccess(allowed: boolean): void; - getPublicWriteAccess(): boolean; - - setReadAccess(userId: User | string, allowed: boolean): void; - getReadAccess(userId: User | string): boolean; - - setWriteAccess(userId: User | string, allowed: boolean): void; - getWriteAccess(userId: User | string): boolean; - - setRoleReadAccess(role: Role | string, allowed: boolean): void; - getRoleReadAccess(role: Role | string): boolean; - - setRoleWriteAccess(role: Role | string, allowed: boolean): void; - getRoleWriteAccess(role: Role | string): boolean; - - toJSON(): any; - } - - /** - * A Parse.File is a local representation of a file that is saved to the Parse - * cloud. - * @param name The file's name. This will be prefixed by a unique - * value once the file has finished saving. The file name must begin with - * an alphanumeric character, and consist of alphanumeric characters, - * periods, spaces, underscores, or dashes. - * @param data The data for the file, as either: - * 1. an Array of byte value Numbers, or - * 2. an Object like { base64: "..." } with a base64-encoded String. - * 3. a File object selected with a file upload control. (3) only works - * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+. - * For example:
-         * var fileUploadControl = $("#profilePhotoFileUpload")[0];
-         * if (fileUploadControl.files.length > 0) {
-         *   var file = fileUploadControl.files[0];
-         *   var name = "photo.jpg";
-         *   var parseFile = new Parse.File(name, file);
-         *   parseFile.save().then(function() {
-         *     // The file has been saved to Parse.
-         *   }, function(error) {
-         *     // The file either could not be read, or could not be saved to Parse.
-         *   });
-         * }
- * @param type Optional Content-Type header to use for the file. If - * this is omitted, the content type will be inferred from the name's - * extension. - */ - class File { - constructor( - name: string, - data: number[] | { base64: string } | { size: number; type: string } | { uri: string }, - type?: string, - ); - /** - * Return the data for the file, downloading it if not already present. - * Data is present if initialized with Byte Array, Base64 or Saved with Uri. - * Data is cleared if saved with File object selected with a file upload control - * - * @returns Promise that is resolved with base64 data - */ - getData(): Promise; - url(options?: { forceSecure?: boolean | undefined }): string; - metadata(): Record; - tags(): Record; - name(): string; - save(options?: FullOptions): Promise; - cancel(): void; - destroy(options?: FullOptions): Promise; - toJSON(): { __type: string; name: string; url: string }; - equals(other: File): boolean; - setMetadata(metadata: Record): void; - addMetadata(key: string, value: any): void; - setTags(tags: Record): void; - addTag(key: string, value: any): void; - readonly _url: string; - } - - /** - * Creates a new GeoPoint with any of the following forms:
- *
-         *   new GeoPoint(otherGeoPoint)
-         *   new GeoPoint(30, 30)
-         *   new GeoPoint([30, 30])
-         *   new GeoPoint({latitude: 30, longitude: 30})
-         *   new GeoPoint()  // defaults to (0, 0)
-         *   
- * - *

Represents a latitude / longitude point that may be associated - * with a key in a ParseObject or used as a reference point for geo queries. - * This allows proximity-based queries on the key.

- * - *

Only one key in a class may contain a GeoPoint.

- * - *

Example:

-         *   var point = new Parse.GeoPoint(30.0, -20.0);
-         *   var object = new Parse.Object("PlaceObject");
-         *   object.set("location", point);
-         *   object.save();

- */ - class GeoPoint { - latitude: number; - longitude: number; - - constructor(latitude: number, longitude: number); - constructor(coords?: { latitude: number; longitude: number } | [number, number]); - - current(options?: SuccessFailureOptions): GeoPoint; - radiansTo(point: GeoPoint): number; - kilometersTo(point: GeoPoint): number; - milesTo(point: GeoPoint): number; - toJSON(): any; - } - - /** - * A class that is used to access all of the children of a many-to-many relationship. - * Each instance of Parse.Relation is associated with a particular parent object and key. - */ - class Relation { - parent: S; - key: string; - targetClassName: string; - - constructor(parent?: S, key?: string); - - // Adds a Parse.Object or an array of Parse.Objects to the relation. - add(object: T | T[]): void; - - // Returns a Parse.Query that is limited to objects in this relation. - query(): Query; - - // Removes a Parse.Object or an array of Parse.Objects from this relation. - remove(object: T | T[]): void; - - toJSON(): any; - } - - interface Attributes { - [key: string]: any; - } - - /** - * Creates a new model with defined attributes. A client id (cid) is - * automatically generated and assigned for you. - * - *

You won't normally call this method directly. It is recommended that - * you use a subclass of Parse.Object instead, created by calling - * extend.

- * - *

However, if you don't want to use a subclass, or aren't sure which - * subclass is appropriate, you can use this form:

-         *     var object = new Parse.Object("ClassName");
-         * 
- * That is basically equivalent to:
-         *     var MyClass = Parse.Object.extend("ClassName");
-         *     var object = new MyClass();
-         * 

- * - * @param attributes The initial set of data to store in the object. - * @param options The options for this object instance. - * @see Parse.Object.extend - * - * Creates a new model with defined attributes. - */ - interface Object { - id: string; - createdAt: Date; - updatedAt: Date; - attributes: T; - className: string; - - add extends any[] ? K : never }[keyof T]>( - attr: K, - item: NonNullable[number], - ): this | false; - addAll extends any[] ? K : never }[keyof T]>( - attr: K, - items: NonNullable, - ): this | false; - addAllUnique: this["addAll"]; - addUnique: this["add"]; - clear(options: any): any; - clone(): this; - destroy(options?: Object.DestroyOptions): Promise; - /** EventuallyQueue API; added in version 3.0.0 */ - destroyEventually(options?: Object.DestroyOptions): Promise; - dirty(attr?: Extract): boolean; - dirtyKeys(): string[]; - equals(other: T): boolean; - escape(attr: Extract): string; - existed(): boolean; - exists(options?: RequestOptions): Promise; - fetch(options?: Object.FetchOptions): Promise; - fetchFromLocalDatastore(): Promise; - fetchWithInclude>( - keys: K | Array, - options?: RequestOptions, - ): Promise; - get>(attr: K): T[K]; - getACL(): ACL | undefined; - has(attr: Extract): boolean; - increment(attr: Extract, amount?: number): this | false; - decrement(attr: Extract, amount?: number): this | false; - initialize(): void; - isDataAvailable(): boolean; - isNew(): boolean; - isPinned(): Promise; - isValid(): boolean; - newInstance(): this; - op(attr: Extract): any; - pin(): Promise; - pinWithName(name: string): Promise; - relation = Extract>( - attr: T[K] extends Relation ? K : never, - ): Relation; - remove: this["add"]; - removeAll: this["addAll"]; - revert(...keys: Array>): void; - // "Pick | T" is a trick to keep IntelliSense working, see: - // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/3bdadbf9583c2335197c7e999b9a30880e055f62/types/react/index.d.ts#L482 - save>( - attrs?: Pick | T | null, - options?: Object.SaveOptions, - ): Promise; - save>( - key: K, - value: T[K] extends undefined ? never : T[K], - options?: Object.SaveOptions, - ): Promise; - /** EventuallyQueue API; added in version 3.0.0 */ - saveEventually(options?: Object.SaveOptions): Promise; - set>(attrs: Pick | T, options?: Object.SetOptions): this | false; - set>( - key: K, - value: T[K] extends undefined ? never : T[K], - options?: Object.SetOptions, - ): this | false; - setACL(acl: ACL, options?: SuccessFailureOptions): this | false; - toJSON(): Object.ToJSON & JSONBaseAttributes; - toPointer(): Pointer; - unPin(): Promise; - unPinWithName(name: string): Promise; - unset(attr: Extract, options?: any): this | false; - validate(attrs: Attributes, options?: SuccessFailureOptions): Error | false; - } - interface ObjectStatic { - createWithoutData(id: string): T; - destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; - extend(className: string | { className: string }, protoProps?: any, classProps?: any): any; - fetchAll(list: T[], options: Object.FetchAllOptions): Promise; - fetchAllIfNeeded(list: T[], options?: Object.FetchAllOptions): Promise; - fetchAllIfNeededWithInclude( - list: T[], - keys: keyof T["attributes"] | Array, - options?: RequestOptions, - ): Promise; - fetchAllWithInclude( - list: T[], - keys: keyof T["attributes"] | Array, - options?: RequestOptions, - ): Promise; - fromJSON(json: any, override?: boolean): T; - pinAll(objects: Object[]): Promise; - pinAllWithName(name: string, objects: Object[]): Promise; - registerSubclass(className: string, clazz: new(options?: any) => T): void; - saveAll(list: T, options?: Object.SaveAllOptions): Promise; - unPinAll(objects: Object[]): Promise; - unPinAllObjects(): Promise; - unPinAllObjectsWithName(name: string): Promise; - unPinAllWithName(name: string, objects: Object[]): Promise; - } - interface ObjectConstructor extends ObjectStatic { - new(className: string, attributes: T, options?: any): Object; - new(className?: string, attributes?: Attributes, options?: any): Object; - } - const Object: ObjectConstructor; - - namespace Object { - interface DestroyOptions extends SuccessFailureOptions, WaitOption, ScopeOptions {} - - interface DestroyAllOptions extends BatchSizeOption, ScopeOptions {} - - interface FetchAllOptions extends SuccessFailureOptions, ScopeOptions {} - - interface FetchOptions extends SuccessFailureOptions, ScopeOptions {} - - interface SaveOptions - extends CascadeSaveOption, SuccessFailureOptions, SilentOption, ScopeOptions, ContextOption, WaitOption - {} - - interface SaveAllOptions extends BatchSizeOption, ScopeOptions {} - - interface SetOptions extends ErrorOption, SilentOption { - promise?: any; - } - - // From https://github.com/parse-community/Parse-SDK-JS/blob/master/src/encode.js - type Encode = T extends Object ? ReturnType | Pointer - : T extends ACL | GeoPoint | Polygon | Relation | File ? ReturnType - : T extends Date ? { __type: "Date"; iso: string } - : T extends RegExp ? string - : T extends Array - // This recursion is unsupported in <=3.6 - ? Array> - : T extends object ? ToJSON - : T; - - type ToJSON = { - [K in keyof T]: Encode; - }; - } - - class Polygon { - constructor(arg1: GeoPoint[] | number[][]); - containsPoint(point: GeoPoint): boolean; - equals(other: any): boolean; - toJSON(): any; - } - - /** - * Every Parse application installed on a device registered for - * push notifications has an associated Installation object. - */ - interface Installation extends Object { - badge: any; - channels: string[]; - timeZone: any; - deviceType: string; - pushType: string; - installationId: string; - deviceToken: string; - channelUris: string; - appName: string; - appVersion: string; - parseVersion: string; - appIdentifier: string; - } - interface InstallationConstructor extends ObjectStatic { - new(attributes: T): Installation; - new(): Installation; - } - const Installation: InstallationConstructor; - - /** - * Creates a new parse Parse.Query for the given Parse.Object subclass. - * @param objectClass - - * An instance of a subclass of Parse.Object, or a Parse className string. - * - *

Parse.Query defines a query that is used to fetch Parse.Objects. The - * most common use case is finding all objects that match a query through the - * find method. For example, this sample code fetches all objects - * of class MyClass. It calls a different function depending on - * whether the fetch succeeded or not. - * - *

-         * var query = new Parse.Query(MyClass);
-         * query.find({
-         *   success: function(results) {
-         *     // results is an array of Parse.Object.
-         *   },
-         *
-         *   error: function(error) {
-         *     // error is an instance of Parse.Error.
-         *   }
-         * });

- * - *

A Parse.Query can also be used to retrieve a single object whose id is - * known, through the get method. For example, this sample code fetches an - * object of class MyClass and id myId. It calls a - * different function depending on whether the fetch succeeded or not. - * - *

-         * var query = new Parse.Query(MyClass);
-         * query.get(myId, {
-         *   success: function(object) {
-         *     // object is an instance of Parse.Object.
-         *   },
-         *
-         *   error: function(object, error) {
-         *     // error is an instance of Parse.Error.
-         *   }
-         * });

- * - *

A Parse.Query can also be used to count the number of objects that match - * the query without retrieving all of those objects. For example, this - * sample code counts the number of objects of the class MyClass - *

-         * var query = new Parse.Query(MyClass);
-         * query.count({
-         *   success: function(number) {
-         *     // There are number instances of MyClass.
-         *   },
-         *
-         *   error: function(error) {
-         *     // error is an instance of Parse.Error.
-         *   }
-         * });

- */ - class Query { - objectClass: any; - className: string; - - constructor(objectClass: string | (new(...args: any[]) => T | Object)); - - static and(...args: Array>): Query; - static fromJSON(className: string | (new() => U), json: any): Query; - static nor(...args: Array>): Query; - static or(...var_args: Array>): Query; - - addAscending(key: K | K[]): this; - addDescending(key: K | K[]): this; - ascending(key: K | K[]): this; - aggregate(pipeline: Query.AggregationOptions | Query.AggregationOptions[]): Promise; - containedBy( - key: K, - values: Array, - ): this; - containedIn( - key: K, - values: Array, - ): this; - contains(key: K, substring: string): this; - containsAll(key: K, values: any[]): this; - containsAllStartingWith( - key: K, - values: any[], - ): this; - count(options?: Query.CountOptions): Promise; - descending(key: K | K[]): this; - doesNotExist(key: K): this; - doesNotMatchKeyInQuery< - U extends Object, - K extends keyof T["attributes"] | keyof BaseAttributes, - X extends Extract, - >(key: K, queryKey: X, query: Query): this; - doesNotMatchQuery(key: K, query: Query): this; - distinct(key: K): Promise; - eachBatch(callback: (objs: T[]) => PromiseLike | void, options?: Query.BatchOptions): Promise; - each(callback: (obj: T) => PromiseLike | void, options?: Query.BatchOptions): Promise; - hint(value: string | object): this; - explain(explain: boolean): this; - map( - callback: (currentObject: T, index: number, query: Query) => PromiseLike | U, - options?: Query.BatchOptions, - ): Promise; - reduce( - callback: (accumulator: T, currentObject: T, index: number) => PromiseLike | T, - initialValue?: undefined, - options?: Query.BatchOptions, - ): Promise; - reduce( - callback: (accumulator: U, currentObject: T, index: number) => PromiseLike | U, - initialValue: U, - options?: Query.BatchOptions, - ): Promise; - filter( - callback: (currentObject: T, index: number, query: Query) => PromiseLike | boolean, - options?: Query.BatchOptions, - ): Promise; - endsWith(key: K, suffix: string): this; - equalTo( - key: K, - value: - | T["attributes"][K] - | (T["attributes"][K] extends Object ? Pointer - : T["attributes"][K] extends Array ? E - : never), - ): this; - exclude(...keys: K[]): this; - exists(key: K): this; - find(options?: Query.FindOptions): Promise; - findAll(options?: Query.BatchOptions): Promise; - first(options?: Query.FirstOptions): Promise; - fromNetwork(): this; - fromLocalDatastore(): this; - fromPin(): this; - fromPinWithName(name: string): this; - cancel(): this; - fullText( - key: K, - value: string, - options?: Query.FullTextOptions, - ): this; - get(objectId: string, options?: Query.GetOptions): Promise; - greaterThan( - key: K, - value: T["attributes"][K], - ): this; - greaterThanOrEqualTo( - key: K, - value: T["attributes"][K], - ): this; - include(...key: K[]): this; - include(key: K[]): this; - includeAll(): Query; - lessThan(key: K, value: T["attributes"][K]): this; - lessThanOrEqualTo( - key: K, - value: T["attributes"][K], - ): this; - limit(n: number): Query; - matches( - key: K, - regex: RegExp, - modifiers?: string, - ): this; - matchesKeyInQuery< - U extends Object, - K extends keyof T["attributes"], - X extends Extract, - >(key: K, queryKey: X, query: Query): this; - matchesQuery(key: K, query: Query): this; - near(key: K, point: GeoPoint): this; - notContainedIn( - key: K, - values: Array, - ): this; - notEqualTo( - key: K, - value: - | T["attributes"][K] - | (T["attributes"][K] extends Object ? Pointer - : T["attributes"][K] extends Array ? E - : never), - ): this; - polygonContains(key: K, point: GeoPoint): this; - select(...keys: K[]): this; - select(keys: K[]): this; - skip(n: number): Query; - sortByTextScore(): this; - startsWith(key: K, prefix: string): this; - subscribe(sessionToken?: string): Promise; - toJSON(): any; - withJSON(json: any): this; - withCount(includeCount?: boolean): this; - withinGeoBox( - key: K, - southwest: GeoPoint, - northeast: GeoPoint, - ): this; - withinKilometers( - key: K, - point: GeoPoint, - maxDistance: number, - sorted?: boolean, - ): this; - withinMiles( - key: K, - point: GeoPoint, - maxDistance: number, - sorted?: boolean, - ): this; - withinPolygon(key: K, points: number[][]): this; - withinRadians( - key: K, - point: GeoPoint, - maxDistance: number, - ): this; - } - - namespace Query { - interface EachOptions extends SuccessFailureOptions, ScopeOptions {} - interface CountOptions extends SuccessFailureOptions, ScopeOptions {} - interface FindOptions extends SuccessFailureOptions, ScopeOptions, RawJSONOptions {} - interface FirstOptions extends SuccessFailureOptions, ScopeOptions, RawJSONOptions {} - interface GetOptions extends SuccessFailureOptions, ScopeOptions, RawJSONOptions {} - - // According to http://docs.parseplatform.org/rest/guide/#aggregate-queries - interface AggregationOptions { - group?: (Record & { objectId?: string }) | undefined; - match?: Record | undefined; - project?: Record | undefined; - limit?: number | undefined; - skip?: number | undefined; - // Sort documentation https://docs.mongodb.com/v3.2/reference/operator/aggregation/sort/#pipe._S_sort - sort?: Record | undefined; - // Sample documentation: https://docs.mongodb.com/v3.2/reference/operator/aggregation/sample/ - sample?: { size: number } | undefined; - // Count documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/count/ - count?: string | undefined; - // Lookup documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ - lookup?: - | { - from: string; - localField: string; - foreignField: string; - as: string; - } - | { - from: string; - let?: Record; - pipeline: Record; - as: string; - } - | undefined; - // Graph Lookup documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/ - graphLookup?: - | { - from: string; - startWith?: string; - connectFromField: string; - connectToField: string; - as: string; - maxDepth?: number; - depthField?: string; - restrictSearchWithMatch?: Record; - } - | undefined; - // Facet documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/facet/ - facet?: Record>> | undefined; - // Unwind documentation: https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind/ - unwind?: - | { - path: string; - includeArrayIndex?: string; - preserveNullAndEmptyArrays?: boolean; - } - | string - | undefined; - } - - // According to https://parseplatform.org/Parse-SDK-JS/api/2.1.0/Parse.Query.html#fullText - interface FullTextOptions { - language?: string | undefined; - caseSensitive?: boolean | undefined; - diacriticSensitive?: boolean | undefined; - } - - interface BatchOptions extends FullOptions { - batchSize?: number | undefined; - } - } - - /** - * Represents a LiveQuery Subscription. - * - * @see https://docs.parseplatform.org/js/guide/#live-queries - * @see NodeJS.EventEmitter - * - * Events list - * --- - * `open` - when you call `query.subscribe()`, we send a subscribe request to - * the LiveQuery server, when we get the confirmation from the LiveQuery server, - * this event will be emitted. When the client loses WebSocket connection to the - * LiveQuery server, we will try to auto reconnect the LiveQuery server. If we - * reconnect the LiveQuery server and successfully resubscribe the ParseQuery, - * you'll also get this event. - * - * ``` - * subscription.on('open', () => {}); - * ``` - * --- - * `create` - when a new ParseObject is created and it fulfills the ParseQuery you subscribe, - * you'll get this event. The object is the ParseObject which is created. - * - * ``` - * subscription.on('create', (object: Parse.Object) => {}); - * ``` - * --- - * `update` event - when an existing ParseObject which fulfills the ParseQuery you subscribe - * is updated (The ParseObject fulfills the ParseQuery before and after changes), - * you'll get this event. The object is the ParseObject which is updated. - * Its content is the latest value of the ParseObject. - * - * ``` - * subscription.on('update', (object: Parse.Object) => {}); - * ``` - * --- - * `enter` event - when an existing ParseObject's old value doesn't fulfill the ParseQuery - * but its new value fulfills the ParseQuery, you'll get this event. The object is the - * ParseObject which enters the ParseQuery. Its content is the latest value of the ParseObject. - * - * ``` - * subscription.on('enter', (object: Parse.Object) => {}); - * ``` - * --- - * `update` event - when an existing ParseObject's old value fulfills the ParseQuery but its new value - * doesn't fulfill the ParseQuery, you'll get this event. The object is the ParseObject - * which leaves the ParseQuery. Its content is the latest value of the ParseObject. - * - * ``` - * subscription.on('leave', (object: Parse.Object) => {}); - * ``` - * --- - * `delete` event - when an existing ParseObject which fulfills the ParseQuery is deleted, you'll - * get this event. The object is the ParseObject which is deleted. - * - * ``` - * subscription.on('delete', (object: Parse.Object) => {}); - * ``` - * --- - * `close` event - when the client loses the WebSocket connection to the LiveQuery - * server and we stop receiving events, you'll get this event. - * - * ``` - * subscription.on('close', () => {}); - * ``` - */ - class LiveQuerySubscription extends EventEmitter { - /** - * Creates an instance of LiveQuerySubscription. - * - * @param id - * @param query - * @param [sessionToken] - */ - constructor(id: string, query: string, sessionToken?: string); - - on( - event: "open" | "create" | "update" | "enter" | "leave" | "delete" | "close", - listener: (object: Object) => void, - ): this; - - /** - * Closes the subscription. - */ - unsubscribe(): void; - } - - /** - * The LiveQuery namespace is basically an EventEmitter - * (source : https://github.com/parse-community/Parse-SDK-JS/blob/8115e959533d1676fe5e5551bc81888b21fc12ef/src/ParseLiveQuery.js) - * https://docs.parseplatform.org/js/guide/#websocket-status - */ - namespace LiveQuery { - function on( - event: "open" | "close", - /** When we establish ('open') or lose the WebSocket connection to the LiveQuery server, you’ll get this event */ - listener: () => void, - ): void; - function on( - event: "error", - /** When some network error or LiveQuery server error happens, you’ll get this event. */ - listener: (error: any) => void, - ): void; - } - - /** - * Represents a Role on the Parse server. Roles represent groupings of - * Users for the purposes of granting permissions (e.g. specifying an ACL - * for an Object). Roles are specified by their sets of child users and - * child roles, all of which are granted any permissions that the parent - * role has. - * - *

Roles must have a name (which cannot be changed after creation of the - * role), and must specify an ACL.

- * A Parse.Role is a local representation of a role persisted to the Parse - * cloud. - */ - interface Role extends Object { - getRoles(): Relation; - getUsers(): Relation; - getName(): string; - setName(name: string, options?: SuccessFailureOptions): any; - } - interface RoleConstructor extends ObjectStatic { - new(name: string, acl: ACL): Role>; - new(name: string, acl: ACL): Role; - } - const Role: RoleConstructor; - - class Config { - static get(options?: UseMasterKeyOption): Promise; - static current(): Config; - static save(attr: any, options?: { [attr: string]: boolean }): Promise; - - get(attr: string): any; - escape(attr: string): any; - } - - interface Session extends Object { - getSessionToken(): string; - isCurrentSessionRevocable(): boolean; - } - interface SessionConstructor extends ObjectStatic { - new(attributes: T): Session; - new(): Session; - - current(): Promise; - } - const Session: SessionConstructor; - - /** - *

A Parse.User object is a local representation of a user persisted to the - * Parse cloud. This class is a subclass of a Parse.Object, and retains the - * same functionality of a Parse.Object, but also extends it with various - * user specific methods, like authentication, signing up, and validation of - * uniqueness.

- */ - interface User extends Object { - signUp(attrs?: any, options?: SignUpOptions): Promise; - logIn(options?: FullOptions): Promise; - authenticated(): boolean; - isCurrent(): boolean; - /** Since version 3.0.0, Returns true if `current` would return this user */ - isCurrentAsync(): Promise; - - getEmail(): string | undefined; - setEmail(email: string, options?: SuccessFailureOptions): boolean; - - getUsername(): string | undefined; - setUsername(username: string, options?: SuccessFailureOptions): boolean; - - setPassword(password: string, options?: SuccessFailureOptions): boolean; - getSessionToken(): string; - - linkWith: ( - provider: string | AuthProvider, - options: { authData?: AuthData | undefined }, - saveOpts?: FullOptions, - ) => Promise; - _isLinked: (provider: string | AuthProvider) => boolean; - _unlinkFrom: (provider: string | AuthProvider, options?: FullOptions) => Promise; - } - interface UserConstructor extends ObjectStatic { - new(attributes: T): User; - new(attributes?: Attributes): User; - - allowCustomUserClass(isAllowed: boolean): void; - become(sessionToken: string, options?: UseMasterKeyOption): Promise; - current(): T | undefined; - currentAsync(): Promise; - signUp(username: string, password: string, attrs: any, options?: SignUpOptions): Promise; - logIn(username: string, password: string, options?: FullOptions): Promise; - logOut(): Promise; - requestPasswordReset(email: string, options?: SuccessFailureOptions): Promise; - requestEmailVerification(email: string, options?: UseMasterKeyOption): Promise; - extend(protoProps?: any, classProps?: any): any; - hydrate(userJSON: any): Promise; - enableUnsafeCurrentUser(): void; - disableUnsafeCurrentUser(): void; - logInWith( - provider: string | AuthProvider, - options: { authData?: AuthData | undefined }, - saveOpts?: FullOptions, - ): Promise; - _registerAuthenticationProvider: (provider: AuthProvider) => void; - } - const User: UserConstructor; - - /** - * The raw schema response returned from the `GET /parse/schemas` endpoint. - * This is defined here: https://docs.parseplatform.org/js/guide/#schema. - * Unfortunately, `Schema.all()` and `Schema.prototype.get()` return this rather - * than a `Schema`. It is also the only object which provides introspection on - * the schema - such as `className` and `fields`. - */ - interface RestSchema { - className: string; - fields: { - [key: string]: { - type: string; - targetClass?: string; - required?: boolean; - defaultValue?: string; - }; - }; - classLevelPermissions: Schema.CLP; - indexes?: { - [key: string]: { - [key: string]: any; - }; - }; - } - - /** - * A Parse.Schema object is for handling schema data from Parse. - * All the schemas methods require MasterKey. - * - * @param className Parse Class string - * - * https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html - * - * ``` - * const schema = new Parse.Schema('MyClass'); - * schema.addString('field'); - * schema.addIndex('index_name', { field: 1 }); - * schema.save(); - * ``` - */ - class Schema { - constructor(className: string); - - /** - * Static method to get all schemas - * - * @return A promise that is resolved with the result when - * the query completes. - */ - static all(): Promise; - - addArray(key: Schema.AttrType, options?: Schema.FieldOptions): this; - addBoolean(key: Schema.AttrType, options?: Schema.FieldOptions): this; - addDate(key: Schema.AttrType, options?: Schema.FieldOptions): this; - addField(name: string, type?: T, options?: Schema.FieldOptions): this; - addFile(key: Schema.AttrType, options?: Schema.FieldOptions): this; - addGeoPoint(key: Schema.AttrType, options?: Schema.FieldOptions): this; - - /** - * Adding an Index to Create / Update a Schema - * @param name Name of the field that will be created on Parse - * @param index `{ 'field': value }` where `field` should exist in the schema before using addIndex. - * @return Returns the schema, so you can chain this call. - * @example - * ``` - * schema.addIndex('index_name', {'field': 1}); - * ``` - */ - addIndex(name: string, index: Schema.Index): this; - - addNumber(key: Schema.AttrType, options?: Schema.FieldOptions): this; - - addObject(key: Schema.AttrType, options?: Schema.FieldOptions): this; - - /** - * Adding Pointer Field - * @param name Name of the field that will be created on Parse - * @param targetClass Name of the target Pointer Class - * @return Returns the schema, so you can chain this call. - */ - addPointer( - key: Schema.AttrType, - targetClass: string, - options?: Schema.FieldOptions, - ): this; - - addPolygon(key: Schema.AttrType, options?: Schema.FieldOptions): this; - - /** - * Adding Relation Field - * @param name Name of the field that will be created on Parse - * @param targetClass Name of the target Pointer Class - * @return Returns the schema, so you can chain this call. - */ - addRelation( - key: Schema.AttrType, - targetClass: string, - options?: Schema.FieldOptions, - ): this; - - addString(key: Schema.AttrType, options?: Schema.FieldOptions): this; - - /** - * Removing a Schema from Parse Can only be used on Schema without objects - * @returns A promise that is resolved with the result when the query completes. - */ - // @TODO Fix Promise - delete(): Promise; - - /** - * Deleting a Field to Update on a Schema - * @param name Name of the field - * @return Returns the schema, so you can chain this call. - */ - deleteField(name: string): this; - - /** - * Deleting a Index Field to Update on a Schema - * @param name Name of the index field - * @return Returns the schema, so you can chain this call. - */ - deleteIndex(name: string): this; - - /** - * Get the Schema from Parse - */ - get(): Promise; - - /** - * Removes all objects from a Schema (class) in EXERCISE CAUTION, running this will delete all objects for this schema and cannot be reversed - */ - // TODO Fix Promise - purge(): Promise; - - /** - * Create a new Schema on Parse - */ - save(): Promise; - - /** - * Sets Class Level Permissions when creating / updating a Schema. - * EXERCISE CAUTION, running this may override CLP for this schema and cannot be reversed - */ - setCLP(clp: Schema.CLP): this; - - /** - * Update a Schema on Parse - */ - update(): Promise; - } - - namespace Schema { - type TYPE = - | "String" - | "Number" - | "Boolean" - | "Date" - | "File" - | "GeoPoint" - | "Polygon" - | "Array" - | "Object" - | "Pointer" - | "Relation"; - type FieldType = - | string - | number - | boolean - | Date - | File - | GeoPoint - | Polygon - | any[] - | object - | Pointer - | Relation; - type AttrType = Extract< - { [K in keyof T["attributes"]]: T["attributes"][K] extends V ? K : never }[keyof T["attributes"]], - string - >; - - interface FieldOptions< - T extends - | string - | number - | boolean - | Date - | File - | GeoPoint - | Polygon - | any[] - | object - | Pointer - | Relation = any, - > { - required?: boolean | undefined; - defaultValue?: T | undefined; - } - - interface Index { - [fieldName: string]: number | string; - } - - /** - * The id of a `_User` object or a role name prefixed by `'role:'`. - * @example - * '*': false, // public - * requiresAuthentication: false, - * 'role:Admin': true, - * 'idOfASpecificUser': true - */ - interface CLPField { - "*"?: boolean | undefined; - requiresAuthentication?: boolean | undefined; - /** `role:Admin` */ - [userIdOrRoleName: string]: boolean | undefined; - } - - interface CLP { - find?: CLPField | undefined; - get?: CLPField | undefined; - count?: CLPField | undefined; - create?: CLPField | undefined; - update?: CLPField | undefined; - delete?: CLPField | undefined; - addField?: CLPField | undefined; - /** Array of fields that point to a `_User` object's ID or a `Role` object's name */ - readUserFields?: string[] | undefined; - /** Array of fields that point to a `_User` object's ID or a `Role` object's name */ - writeUserFields?: string[] | undefined; - protectedFields?: { - /** '*', user id, or role: followed by a list of fields. */ - [userIdOrRoleName: string]: string[]; - }; - } - } - - namespace Analytics { - function track(name: string, dimensions: any): Promise; - } - - /** - * Provides utility functions for working with Anonymously logged-in users. - */ - namespace AnonymousUtils { - function isLinked(user: User): boolean; - function link(user: User, options?: ScopeOptions): Promise; - function logIn(options?: ScopeOptions): Promise; - } - - /** - * Provides a set of utilities for using Parse with Facebook. - * Provides a set of utilities for using Parse with Facebook. - */ - namespace FacebookUtils { - function init(options?: any): void; - function isLinked(user: User): boolean; - function link(user: User, permissions: any, options?: SuccessFailureOptions): void; - function logIn(permissions: any, options?: FullOptions): void; - function unlink(user: User, options?: SuccessFailureOptions): void; - } - - /** - * Contains functions for calling and declaring - * cloud functions. - *

- * Some functions are only available from Cloud Code. - *

- */ - namespace Cloud { - interface CookieOptions { - domain?: string | undefined; - expires?: Date | undefined; - httpOnly?: boolean | undefined; - maxAge?: number | undefined; - path?: string | undefined; - secure?: boolean | undefined; - } - - interface HttpResponse { - buffer?: Buffer | undefined; - cookies?: any; - data?: any; - headers?: any; - status?: number | undefined; - text?: string | undefined; - } - - interface JobRequest { - params: T; - message: (response: any) => void; - } - - interface Params { - [key: string]: any; - } - - interface FunctionRequest { - installationId?: string | undefined; - master?: boolean | undefined; - params: T; - user?: User | undefined; - } - - interface ValidatorField { - type?: any; - constant?: boolean | undefined; - default?: any; - options?: any[] | Function | undefined; - error?: String | undefined; - required?: boolean; - } - interface ValidatorFields { - [field: string]: ValidatorField; - } - interface Validator { - requireUser?: boolean | undefined; - requireMaster?: boolean | undefined; - validateMasterKey?: boolean | undefined; - skipWithMasterKey?: boolean | undefined; - requireAnyUserRoles?: String[] | Function | undefined; - requireAllUserRoles?: String[] | Function | undefined; - fields?: ValidatorFields | String[] | undefined; - requireUserKeys?: ValidatorFields | String[] | undefined; - } - - interface Cookie { - name?: string | undefined; - options?: CookieOptions | undefined; - value?: string | undefined; - } - - interface TriggerRequest { - installationId?: string | undefined; - master?: boolean | undefined; - user?: User | undefined; - ip: string; - headers: any; - triggerName: string; - log: any; - object: T; - original?: T | undefined; - } - - interface AfterSaveRequest extends TriggerRequest { - context: Record; - } - interface AfterDeleteRequest extends TriggerRequest {} // eslint-disable-line @typescript-eslint/no-empty-interface - interface BeforeDeleteRequest extends TriggerRequest {} // eslint-disable-line @typescript-eslint/no-empty-interface - interface BeforeSaveRequest extends TriggerRequest { - context: Record; - } - - interface FileTriggerRequest extends TriggerRequest { - file: File; - fileSize: number; - contentLength: number; - } - - // Read preference describes how MongoDB driver route read operations to the members of a replica set. - enum ReadPreferenceOption { - Primary = "PRIMARY", - PrimaryPreferred = "PRIMARY_PREFERRED", - Secondary = "SECONDARY", - SecondaryPreferred = "SECONDARY_PREFERRED", - Nearest = "NEAREST", - } - - interface BeforeFindRequest extends TriggerRequest { - query: Query; - count: boolean; - isGet: boolean; - readPreference?: ReadPreferenceOption | undefined; - } - - interface AfterFindRequest extends TriggerRequest { - objects: T[]; - } - - function afterDelete( - arg1: { new(): T } | string, - func?: (request: AfterDeleteRequest) => Promise | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function afterSave( - arg1: { new(): T } | string, - func?: (request: AfterSaveRequest) => Promise | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function beforeDelete( - arg1: { new(): T } | string, - func?: (request: BeforeDeleteRequest) => Promise | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function beforeSave( - arg1: { new(): T } | string, - func?: (request: BeforeSaveRequest) => Promise | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function beforeFind( - arg1: { new(): T } | string, - // eslint-disable-next-line @typescript-eslint/no-invalid-void-type - func?: (request: BeforeFindRequest) => Promise> | Promise | Query | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function afterFind( - arg1: { new(): T } | string, - func?: (request: AfterFindRequest) => any, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - - function beforeLogin(func?: (request: TriggerRequest) => PromiseLike | void): void; - function afterLogin( - func?: (request: TriggerRequest) => PromiseLike | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function afterLogout( - func?: (request: TriggerRequest) => PromiseLike | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - - function beforeSaveFile( - // eslint-disable-next-line @typescript-eslint/no-invalid-void-type - func?: (request: FileTriggerRequest) => PromiseLike | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function afterSaveFile( - func?: (request: FileTriggerRequest) => PromiseLike | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function beforeDeleteFile( - func?: (request: FileTriggerRequest) => PromiseLike | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function afterDeleteFile( - func?: (request: FileTriggerRequest) => PromiseLike | void, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - - function define( - name: string, - func: (request: FunctionRequest) => any, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function define any>( - name: string, - func: (request: FunctionRequest<{}>) => Promise> | ReturnType, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - function define[0]]: Parameters[0][P] }) => any>( - name: string, - func: (request: FunctionRequest[0]>) => Promise> | ReturnType, - validator?: Validator | ((request: FunctionRequest) => any), - ): void; - /** - * Gets data for the current set of cloud jobs. - * @returns A promise that will be resolved with the result of the function. - */ - function getJobsData(): Promise; - /** - * Gets job status by Id - * @param jobStatusId The Id of Job Status. - * @returns Status of Job. - */ - function getJobStatus(jobStatusId: string): Promise; - function httpRequest(options: HTTPOptions): Promise; - function job(name: string, func?: (request: JobRequest) => Promise | void): HttpResponse; - function run(name: string, data?: Params, options?: RunOptions): Promise; - function run any>(name: string, data?: null, options?: RunOptions): Promise>; - function run[0]]: Parameters[0][P] }) => any>( - name: string, - data: Parameters[0], - options?: RunOptions, - ): Promise>; - /** - * Starts a given cloud job, which will process asynchronously. - * @param jobName The function name. - * @param data The parameters to send to the cloud function. - * @returns A promise that will be resolved with the jobStatusId of the job. - */ - function startJob(jobName: string, data: any): Promise; - function useMasterKey(): void; - - interface RunOptions extends SuccessFailureOptions, ScopeOptions {} - - /** - * To use this Cloud Module in Cloud Code, you must require 'buffer' in your JavaScript file. - * - * import Buffer = require("buffer").Buffer; - */ - let HTTPOptions: new() => HTTPOptions; - interface HTTPOptions { - /** - * The body of the request. - * If it is a JSON object, then the Content-Type set in the headers must be application/x-www-form-urlencoded or application/json. - * You can also set this to a Buffer object to send raw bytes. - * If you use a Buffer, you should also set the Content-Type header explicitly to describe what these bytes represent. - */ - body?: string | Buffer | object | undefined; - /** - * Defaults to 'false'. - */ - followRedirects?: boolean | undefined; - /** - * The headers for the request. - */ - headers?: - | { - [headerName: string]: string | number | boolean; - } - | undefined; - /** - * The method of the request (i.e GET, POST, etc). - */ - method?: string | undefined; - /** - * The query portion of the url. - */ - params?: any; - /** - * The url to send the request to. - */ - url: string; - - success?: ((response: any) => void) | undefined; - error?: ((response: any) => void) | undefined; - } - } - - namespace EventuallyQueue { - interface QueueObject { - queueId: string; - action: string; - object: Object; - serverOptions: Object.SaveOptions | RequestOptions; - id: string; - className: string; - hash: string; - createdAt: Date; - } - type Queue = QueueObject[]; - /** - * Add object to queue with save operation. - * - * @param object Parse.Object to be saved eventually - * @param serverOptions See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#save Parse.Object.save} options. - * @returns A promise that is fulfilled if object is added to queue. - * @see Parse.Object#saveEventually - */ - function save(object: Object, serverOptions?: Object.SaveOptions): Promise; - /** - * Add object to queue with save operation. - * - * @param object Parse.Object to be destroyed eventually - * @param serverOptions See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#destroy Parse.Object.destroy} options - * @returns A promise that is fulfilled if object is added to queue. - * @see Parse.Object#destroyEventually - */ - function destroy(object: Object, serverOptions?: RequestOptions): Promise; - // function store(data: any): Promise; - // function load(): Promise; - /** - * Sets the in-memory queue from local storage and returns. - */ - function getQueue(): Promise; - /** - * Removes all objects from queue. - * @returns A promise that is fulfilled when queue is cleared. - */ - function clear(): Promise; - /** - * Return the number of objects in the queue. - */ - function length(): Promise; - /** - * Sends the queue to the server. - * @returns Returns true if queue was sent successfully. - */ - function sendQueue(): Promise; - /** - * Start polling server for network connection. - * Will send queue if connection is established. - * - * @param [ms] Milliseconds to ping the server. Default 2000ms - */ - function poll(ms?: number): void; - /** - * Turns off polling. - */ - function stopPoll(): void; - /** - * Return true if pinging the server. - */ - function isPolling(): boolean; - } - - class Error { - static OTHER_CAUSE: ErrorCode.OTHER_CAUSE; - static INTERNAL_SERVER_ERROR: ErrorCode.INTERNAL_SERVER_ERROR; - static CONNECTION_FAILED: ErrorCode.CONNECTION_FAILED; - static OBJECT_NOT_FOUND: ErrorCode.OBJECT_NOT_FOUND; - static INVALID_QUERY: ErrorCode.INVALID_QUERY; - static INVALID_CLASS_NAME: ErrorCode.INVALID_CLASS_NAME; - static MISSING_OBJECT_ID: ErrorCode.MISSING_OBJECT_ID; - static INVALID_KEY_NAME: ErrorCode.INVALID_KEY_NAME; - static INVALID_POINTER: ErrorCode.INVALID_POINTER; - static INVALID_JSON: ErrorCode.INVALID_JSON; - static COMMAND_UNAVAILABLE: ErrorCode.COMMAND_UNAVAILABLE; - static NOT_INITIALIZED: ErrorCode.NOT_INITIALIZED; - static INCORRECT_TYPE: ErrorCode.INCORRECT_TYPE; - static INVALID_CHANNEL_NAME: ErrorCode.INVALID_CHANNEL_NAME; - static PUSH_MISCONFIGURED: ErrorCode.PUSH_MISCONFIGURED; - static OBJECT_TOO_LARGE: ErrorCode.OBJECT_TOO_LARGE; - static OPERATION_FORBIDDEN: ErrorCode.OPERATION_FORBIDDEN; - static CACHE_MISS: ErrorCode.CACHE_MISS; - static INVALID_NESTED_KEY: ErrorCode.INVALID_NESTED_KEY; - static INVALID_FILE_NAME: ErrorCode.INVALID_FILE_NAME; - static INVALID_ACL: ErrorCode.INVALID_ACL; - static TIMEOUT: ErrorCode.TIMEOUT; - static INVALID_EMAIL_ADDRESS: ErrorCode.INVALID_EMAIL_ADDRESS; - static MISSING_CONTENT_TYPE: ErrorCode.MISSING_CONTENT_TYPE; - static MISSING_CONTENT_LENGTH: ErrorCode.MISSING_CONTENT_LENGTH; - static INVALID_CONTENT_LENGTH: ErrorCode.INVALID_CONTENT_LENGTH; - static FILE_TOO_LARGE: ErrorCode.FILE_TOO_LARGE; - static FILE_SAVE_ERROR: ErrorCode.FILE_SAVE_ERROR; - static DUPLICATE_VALUE: ErrorCode.DUPLICATE_VALUE; - static INVALID_ROLE_NAME: ErrorCode.INVALID_ROLE_NAME; - static EXCEEDED_QUOTA: ErrorCode.EXCEEDED_QUOTA; - static SCRIPT_FAILED: ErrorCode.SCRIPT_FAILED; - static VALIDATION_ERROR: ErrorCode.VALIDATION_ERROR; - static INVALID_IMAGE_DATA: ErrorCode.INVALID_IMAGE_DATA; - static UNSAVED_FILE_ERROR: ErrorCode.UNSAVED_FILE_ERROR; - static INVALID_PUSH_TIME_ERROR: ErrorCode.INVALID_PUSH_TIME_ERROR; - static FILE_DELETE_ERROR: ErrorCode.FILE_DELETE_ERROR; - static REQUEST_LIMIT_EXCEEDED: ErrorCode.REQUEST_LIMIT_EXCEEDED; - static INVALID_EVENT_NAME: ErrorCode.INVALID_EVENT_NAME; - static USERNAME_MISSING: ErrorCode.USERNAME_MISSING; - static PASSWORD_MISSING: ErrorCode.PASSWORD_MISSING; - static USERNAME_TAKEN: ErrorCode.USERNAME_TAKEN; - static EMAIL_TAKEN: ErrorCode.EMAIL_TAKEN; - static EMAIL_MISSING: ErrorCode.EMAIL_MISSING; - static EMAIL_NOT_FOUND: ErrorCode.EMAIL_NOT_FOUND; - static SESSION_MISSING: ErrorCode.SESSION_MISSING; - static MUST_CREATE_USER_THROUGH_SIGNUP: ErrorCode.MUST_CREATE_USER_THROUGH_SIGNUP; - static ACCOUNT_ALREADY_LINKED: ErrorCode.ACCOUNT_ALREADY_LINKED; - static INVALID_SESSION_TOKEN: ErrorCode.INVALID_SESSION_TOKEN; - static LINKED_ID_MISSING: ErrorCode.LINKED_ID_MISSING; - static INVALID_LINKED_SESSION: ErrorCode.INVALID_LINKED_SESSION; - static UNSUPPORTED_SERVICE: ErrorCode.UNSUPPORTED_SERVICE; - static AGGREGATE_ERROR: ErrorCode.AGGREGATE_ERROR; - static FILE_READ_ERROR: ErrorCode.FILE_READ_ERROR; - static X_DOMAIN_REQUEST: ErrorCode.X_DOMAIN_REQUEST; - - code: ErrorCode; - message: string; - - constructor(code: ErrorCode, message: string); - } - - /** - * A Parse.Op is an atomic operation that can be applied to a field in a - * Parse.Object. For example, calling object.set("foo", "bar") - * is an example of a Parse.Op.Set. Calling object.unset("foo") - * is a Parse.Op.Unset. These operations are stored in a Parse.Object and - * sent to the server as part of object.save() operations. - * Instances of Parse.Op should be immutable. - * - * You should not create subclasses of Parse.Op or instantiate Parse.Op - * directly. - */ - namespace Op { - interface BaseOperation { - objects(): any[]; - } - - interface Add extends BaseOperation { - toJSON(): any; - } - - interface AddUnique extends BaseOperation { - toJSON(): any; - } - - interface Increment { - amount: number; - toJSON(): any; - } - - interface Relation { - added(): Object[]; - removed: Object[]; - toJSON(): any; - } - - interface Set { - value(): any; - toJSON(): any; - } - - interface Unset { - toJSON(): any; - } - } - - /** - * Contains functions to deal with Push in Parse - */ - namespace Push { - function send(data: PushData, options?: SendOptions): Promise; - - interface PushData { - channels?: string[] | undefined; - push_time?: Date | undefined; - expiration_time?: Date | undefined; - expiration_interval?: number | undefined; - where?: Query | undefined; - data?: any; - alert?: string | undefined; - badge?: string | undefined; - sound?: string | undefined; - title?: string | undefined; - notification?: any; - content_available?: any; - } - - interface SendOptions extends UseMasterKeyOption { - success?: (() => void) | undefined; - error?: ((error: Error) => void) | undefined; - } - } - - /** - * Call this method first to set up your authentication tokens for Parse. - * You can get your keys from the Data Browser on parse.com. - * @param applicationId Your Parse Application ID. - * @param javaScriptKey (optional) Your Parse JavaScript Key (Not needed for parse-server) - * @param masterKey (optional) Your Parse Master Key. (Node.js only!) - */ - function initialize(applicationId: string, javaScriptKey?: string, masterKey?: string): void; - - /** - * Use this to set custom headers - * The headers will be sent with every parse request - */ - namespace CoreManager { - function set(key: string, value: any): void; - function get(key: string): void; - } - - /** - * Additionally on React-Native / Expo environments, add AsyncStorage from 'react-native' package - * @param AsyncStorage AsyncStorage from 'react-native' package - */ - function setAsyncStorage(AsyncStorage: any): void; - - /** - * Gets all contents from Local Datastore. - */ - function dumpLocalDatastore(): Promise<{ [key: string]: any }>; - - /** - * Enable pinning in your application. - * This must be called before your application can use pinning. - */ - function enableLocalDatastore(): void; - - /** - * Flag that indicates whether Local Datastore is enabled. - */ - function isLocalDatastoreEnabled(): boolean; - - function setLocalDatastoreController(controller: any): void; - - /** - * Call this method to set your LocalDatastoreStorage engine - * If using React-Native use {@link Parse.setAsyncStorage Parse.setAsyncStorage()} - * @param controller a data storage. - */ - function setLocalDatastoreController(controller: any): void; - - /** - * Enable the current user encryption. - * This must be called before login any user. - */ - function enableEncryptedUser(): void; - - /** - * Flag that indicates whether Encrypted User is enabled. - */ - function isEncryptedUserEnabled(): boolean; - } -} - -export = Parse; From dca4507fde5f3650eea451230fe7df218729269a Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 12:00:21 +0700 Subject: [PATCH 04/25] removed redundant tests and improved method signature --- src/ParseObject.ts | 46 ++-- types/ParseObject.d.ts | 38 ++- types/tests.ts | 538 +++++------------------------------------ 3 files changed, 100 insertions(+), 522 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index b8697db54..c0ac3a2f9 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -2691,36 +2691,30 @@ CoreManager.setParseObject(ParseObject); CoreManager.setObjectController(DefaultController); export interface ObjectStatic { - new(className: string, attributes?: Attributes, options?: any): T; - new(attributes?: Attributes, options?: any): T; - extend(className: string, protoProps?: any, classProps?: any): any; - enableSingleInstance(): void; - disableSingleInstance(): void; - enableLocaldatastore(): void; - isLocalDatastoreEnabled(): boolean; - disableLocaldatastore(): void; - unpinAllObjects(): Promise; - unpinAllObjectsWithName(name: string): Promise; - fetchAll(list: T[], options?: RequestOptions): Promise; - fetchAllWithInclude( + createWithoutData(id: string): T; + destroyAll(list: T[], options?: DestroyAllOptions): Promise; + extend(className: string | { className: string }, protoProps?: any, classProps?: any): any; + fetchAll(list: T[], options: FetchAllOptions): Promise; + fetchAllIfNeeded(list: T[], options?: FetchAllOptions): Promise; + fetchAllIfNeededWithInclude( list: T[], - include: string | string[], - options?: RequestOptions + keys: keyof T["attributes"] | Array, + options?: RequestOptions, ): Promise; - fetchAllIfNeeded(list: T[], options?: RequestOptions): Promise; - destroyAll(list: T[], options?: RequestOptions): Promise; - saveAll(list: T[], options?: SaveOptions): Promise; - fetchAllFromLocalDatastore(list: T[], options?: RequestOptions): Promise; - unpinAll(list: T[], options?: RequestOptions): Promise; - pinAll(list: T[], options?: RequestOptions): Promise; - pinAllWithName( - name: string, + fetchAllWithInclude( list: T[], - options?: RequestOptions - ): Promise; + keys: keyof T["attributes"] | Array, + options?: RequestOptions, + ): Promise; fromJSON(json: any, override?: boolean): T; - registerSubclass(className: string, constructor: any): void; - createWithoutData(className: string, id: string): T; + pinAll(objects: ParseObject[]): Promise; + pinAllWithName(name: string, objects: ParseObject[]): Promise; + registerSubclass(className: string, clazz: new (options?: any) => T): void; + saveAll(list: T, options?: SaveAllOptions): Promise; + unPinAll(objects: ParseObject[]): Promise; + unPinAllObjects(): Promise; + unPinAllObjectsWithName(name: string): Promise; + unPinAllWithName(name: string, objects: ParseObject[]): Promise; } export default ParseObject; diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index af55a2526..9b98528cd 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -1097,27 +1097,23 @@ declare class ParseObject { static unPinAllObjectsWithName(name: string): Promise; } export interface ObjectStatic { - new (className: string, attributes?: Attributes, options?: any): T; - new (attributes?: Attributes, options?: any): T; - extend(className: string, protoProps?: any, classProps?: any): any; - enableSingleInstance(): void; - disableSingleInstance(): void; - enableLocaldatastore(): void; - isLocalDatastoreEnabled(): boolean; - disableLocaldatastore(): void; - unpinAllObjects(): Promise; - unpinAllObjectsWithName(name: string): Promise; - fetchAll(list: T[], options?: RequestOptions): Promise; - fetchAllWithInclude(list: T[], include: string | string[], options?: RequestOptions): Promise; - fetchAllIfNeeded(list: T[], options?: RequestOptions): Promise; - destroyAll(list: T[], options?: RequestOptions): Promise; - saveAll(list: T[], options?: SaveOptions): Promise; - fetchAllFromLocalDatastore(list: T[], options?: RequestOptions): Promise; - unpinAll(list: T[], options?: RequestOptions): Promise; - pinAll(list: T[], options?: RequestOptions): Promise; - pinAllWithName(name: string, list: T[], options?: RequestOptions): Promise; + createWithoutData(id: string): T; + destroyAll(list: T[], options?: DestroyAllOptions): Promise; + extend(className: string | { + className: string; + }, protoProps?: any, classProps?: any): any; + fetchAll(list: T[], options: FetchAllOptions): Promise; + fetchAllIfNeeded(list: T[], options?: FetchAllOptions): Promise; + fetchAllIfNeededWithInclude(list: T[], keys: keyof T["attributes"] | Array, options?: RequestOptions): Promise; + fetchAllWithInclude(list: T[], keys: keyof T["attributes"] | Array, options?: RequestOptions): Promise; fromJSON(json: any, override?: boolean): T; - registerSubclass(className: string, constructor: any): void; - createWithoutData(className: string, id: string): T; + pinAll(objects: ParseObject[]): Promise; + pinAllWithName(name: string, objects: ParseObject[]): Promise; + registerSubclass(className: string, clazz: new (options?: any) => T): void; + saveAll(list: T, options?: SaveAllOptions): Promise; + unPinAll(objects: ParseObject[]): Promise; + unPinAllObjects(): Promise; + unPinAllObjectsWithName(name: string): Promise; + unPinAllWithName(name: string, objects: ParseObject[]): Promise; } export default ParseObject; diff --git a/types/tests.ts b/types/tests.ts index c089fb69a..5e3fb8bfc 100644 --- a/types/tests.ts +++ b/types/tests.ts @@ -2363,494 +2363,82 @@ function testInitialize() { // Node - 1 param (should also work since javaScriptKey is optional in node) ParseNode.initialize('appId'); } -async function test_type_regressions() { - // Base type exports - const attributes: Parse.Attributes = { foo: 'bar' }; - const baseAttributes: Parse.BaseAttributes = { - objectId: '123', - createdAt: new Date(), - updatedAt: new Date(), - }; - const jsonBaseAttributes: Parse.JSONBaseAttributes = { - objectId: '123', - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }; - +// Test Parse.* and namespace type exports +async function test_type_exports() { + // Parse.Object.* namespace + const objDestroyOpts: Parse.Object.DestroyOptions = { useMasterKey: true, sessionToken: 'token' }; + const objDestroyAllOpts: Parse.Object.DestroyAllOptions = { batchSize: 100, useMasterKey: true }; + const objFetchOpts: Parse.Object.FetchOptions = { useMasterKey: true, include: ['rel'] }; + const objFetchAllOpts: Parse.Object.FetchAllOptions = { useMasterKey: true }; + const objSaveOpts: Parse.Object.SaveOptions = { useMasterKey: true, cascadeSave: false, context: {} }; + const objSaveAllOpts: Parse.Object.SaveAllOptions = { batchSize: 50, useMasterKey: true }; + const objSetOpts: Parse.Object.SetOptions = { ignoreValidation: true }; + type ObjEncode = Parse.Object.Encode; + type ObjToJSON = Parse.Object.ToJSON<{ name: string }>; + + // Parse.Query.* namespace + const queryOpts: Parse.Query.QueryOptions = { useMasterKey: true, sessionToken: 'token', json: true }; + const queryFindOpts: Parse.Query.FindOptions = { useMasterKey: true, context: {} }; + const queryBatchOpts: Parse.Query.BatchOptions = { batchSize: 100, useMasterKey: true }; + const queryFullTextOpts: Parse.Query.FullTextOptions = { language: 'en', caseSensitive: false }; + + // Parse.Schema.* namespace + const schemaTypes: Parse.Schema.TYPE[] = ['String', 'Number', 'Boolean', 'Date', 'File', 'GeoPoint', 'Polygon', 'Array', 'Object', 'Pointer', 'Relation', 'Bytes']; + + // Direct Parse.* exports + const destroyOpts: Parse.DestroyOptions = { useMasterKey: true }; + const fetchOpts: Parse.FetchOptions = { useMasterKey: true, include: ['rel'] }; + const saveOpts: Parse.SaveOptions = { useMasterKey: true, cascadeSave: true }; + const setOpts: Parse.SetOptions = { ignoreValidation: false }; + const destroyAllOpts: Parse.DestroyAllOptions = { batchSize: 100 }; + const saveAllOpts: Parse.SaveAllOptions = { batchSize: 50 }; + const fetchAllOpts: Parse.FetchAllOptions = { useMasterKey: true }; + const findOpts: Parse.FindOptions = { useMasterKey: true, json: true }; + const batchOpts: Parse.BatchOptions = { batchSize: 100 }; + const fullTextOpts: Parse.FullTextOptions = { language: 'en' }; + const typeVal: Parse.TYPE = 'String'; + type DirectEncode = Parse.Encode; + type DirectToJSON = Parse.ToJSON<{ x: number }>; + + // Core types + const pointer: Parse.Pointer = { __type: 'Pointer', className: 'Test', objectId: 'abc' }; + const attrs: Parse.Attributes = { score: 100 }; + const baseAttrs: Parse.BaseAttributes = { createdAt: new Date(), updatedAt: new Date(), objectId: 'abc' }; + const jsonBaseAttrs: Parse.JSONBaseAttributes = { createdAt: '2023-01-01T00:00:00Z', updatedAt: '2023-01-01T00:00:00Z', objectId: 'abc' }; + const whereClause: Parse.WhereClause = { score: { $gt: 100 } }; + const queryJson: Parse.QueryJSON = { where: {}, limit: 10 }; + const fullOpts: Parse.FullOptions = { useMasterKey: true }; + const reqOpts: Parse.RequestOptions = { useMasterKey: true, batchSize: 50 }; + const authProvider: Parse.AuthProvider = { authenticate: () => { }, getAuthType: () => 'custom', restoreAuthentication: () => true }; + const authData: Parse.AuthData = { id: 'user-id' }; + const signUpOpts: Parse.SignUpOptions = { useMasterKey: true }; + const restSchema: Parse.RestSchema = { className: 'Test', fields: {}, classLevelPermissions: {} }; + const pushData: Parse.PushData = { channels: ['news'], data: { alert: 'Hello' } }; + const sendOpts: Parse.SendOptions = { useMasterKey: true }; + const cloudRunOpts: Parse.Cloud.RunOptions = { useMasterKey: true, context: {} }; const subscription: Parse.LiveQuerySubscription = await new Parse.Query('Test').subscribe(); - const fullOptions: Parse.FullOptions = { - useMasterKey: true, - sessionToken: 'token', - }; - - const signUpOptions: Parse.SignUpOptions = { - useMasterKey: true, - installationId: 'install-123', - }; - + // ObjectStatic with generics const objectStatic: Parse.ObjectStatic = Parse.Object; + function doCreateWithoutData(clz: Parse.ObjectStatic, id: string): T { + return clz.createWithoutData(id); + } - const restSchema: Parse.RestSchema = { - className: 'Test', - fields: {}, - classLevelPermissions: {}, - }; - - const cloudRunOptions: Parse.Cloud.RunOptions = { - useMasterKey: true, - context: { foo: 'bar' }, - }; - - // ============================================= - // Namespace-scoped option types (Parse.Object.*, Parse.Query.*, Parse.Schema.*) - // ============================================= - - // Parse.Object namespace - const destroyOptions: Parse.Object.DestroyOptions = { - useMasterKey: true, - sessionToken: 'token', - }; - - const objectFetchOptions: Parse.Object.FetchOptions = { - useMasterKey: true, - include: ['relation1', 'relation2'], - }; - - const saveOptions: Parse.Object.SaveOptions = { - useMasterKey: true, - cascadeSave: false, - }; - - const setOptions: Parse.Object.SetOptions = { - ignoreValidation: true, - }; - - const destroyAllOptions: Parse.Object.DestroyAllOptions = { - batchSize: 100, - useMasterKey: true, - }; - - const saveAllOptions: Parse.Object.SaveAllOptions = { - batchSize: 50, - useMasterKey: true, - }; - - const fetchAllOptions: Parse.Object.FetchAllOptions = { - useMasterKey: true, - sessionToken: 'token', - }; - - // Parse.Query namespace - const findOptions: Parse.Query.FindOptions = { - useMasterKey: true, - sessionToken: 'token', - }; - - // Parse.Schema namespace - const schemaType: Parse.Schema.TYPE = 'String'; - const schemaTypeNumber: Parse.Schema.TYPE = 'Number'; - const schemaTypePointer: Parse.Schema.TYPE = 'Pointer'; - const schemaTypeRelation: Parse.Schema.TYPE = 'Relation'; - - // Push types - const pushData: Parse.PushData = { - channels: ['news'], - data: { alert: 'Hello' }, - }; - - const sendOptions: Parse.SendOptions = { - useMasterKey: true, - }; -} - -// ============================================= -// COMPREHENSIVE TYPE EXPORT TESTS -// Tests for all types restored from old-types.d.ts -// ============================================= - -function test_restored_types_parseobject_namespace() { - // ============================================= - // Parse.Object.* namespace types - // ============================================= - - // Parse.Object.DestroyOptions - const destroyOpts1: Parse.Object.DestroyOptions = {}; - const destroyOpts2: Parse.Object.DestroyOptions = { - useMasterKey: true, - sessionToken: 'session-token', - }; - - // Parse.Object.DestroyAllOptions - const destroyAllOpts1: Parse.Object.DestroyAllOptions = {}; - const destroyAllOpts2: Parse.Object.DestroyAllOptions = { - batchSize: 100, - useMasterKey: true, - sessionToken: 'session-token', - }; - - // Parse.Object.FetchOptions - const fetchOpts1: Parse.Object.FetchOptions = {}; - const fetchOpts2: Parse.Object.FetchOptions = { - useMasterKey: true, - sessionToken: 'session-token', - include: ['pointer1', 'pointer2'], - }; - - // Parse.Object.FetchAllOptions - const fetchAllOpts1: Parse.Object.FetchAllOptions = {}; - const fetchAllOpts2: Parse.Object.FetchAllOptions = { - useMasterKey: true, - sessionToken: 'session-token', - }; - - // Parse.Object.SaveOptions - const saveOpts1: Parse.Object.SaveOptions = {}; - const saveOpts2: Parse.Object.SaveOptions = { - useMasterKey: true, - sessionToken: 'session-token', - cascadeSave: false, - context: { key: 'value' }, - }; - - // Parse.Object.SaveAllOptions - const saveAllOpts1: Parse.Object.SaveAllOptions = {}; - const saveAllOpts2: Parse.Object.SaveAllOptions = { - batchSize: 50, - useMasterKey: true, - sessionToken: 'session-token', - }; - - // Parse.Object.SetOptions - const setOpts1: Parse.Object.SetOptions = {}; - const setOpts2: Parse.Object.SetOptions = { - ignoreValidation: true, - }; - - // Parse.Object.Encode - utility type for encoding ParseObject to JSON - type TestEncodeString = Parse.Object.Encode; // string - type TestEncodeNumber = Parse.Object.Encode; // number - type TestEncodeDate = Parse.Object.Encode; // { __type: 'Date'; iso: string } - type TestEncodeObject = Parse.Object.Encode; // ReturnType | Pointer - - // Parse.Object.ToJSON - utility type for converting object properties - type TestToJSON = Parse.Object.ToJSON<{ name: string; count: number }>; -} - -function test_restored_types_parsequery_namespace() { - // ============================================= - // Parse.Query.* namespace types - // ============================================= - - // Parse.Query.QueryOptions - base query options - const queryOpts1: Parse.Query.QueryOptions = {}; - const queryOpts2: Parse.Query.QueryOptions = { - useMasterKey: true, - sessionToken: 'session-token', - context: { key: 'value' }, - json: true, - }; - - // Parse.Query.FindOptions - alias for QueryOptions - const findOpts1: Parse.Query.FindOptions = {}; - const findOpts2: Parse.Query.FindOptions = { - useMasterKey: true, - sessionToken: 'session-token', - context: { key: 'value' }, - json: false, - }; - - // Parse.Query.BatchOptions - for batch operations like each(), eachBatch() - const batchOpts1: Parse.Query.BatchOptions = {}; - const batchOpts2: Parse.Query.BatchOptions = { - batchSize: 100, - useMasterKey: true, - sessionToken: 'session-token', - context: { key: 'value' }, - json: true, - }; - - // Parse.Query.FullTextOptions - for fullText() query method - const fullTextOpts1: Parse.Query.FullTextOptions = {}; - const fullTextOpts2: Parse.Query.FullTextOptions = { - language: 'en', - caseSensitive: true, - diacriticSensitive: false, - }; -} - -function test_restored_types_parseschema_namespace() { - // ============================================= - // Parse.Schema.* namespace types - // ============================================= - - // Parse.Schema.TYPE - all valid schema field types - const typeString: Parse.Schema.TYPE = 'String'; - const typeNumber: Parse.Schema.TYPE = 'Number'; - const typeBytes: Parse.Schema.TYPE = 'Bytes'; - const typeBoolean: Parse.Schema.TYPE = 'Boolean'; - const typeDate: Parse.Schema.TYPE = 'Date'; - const typeFile: Parse.Schema.TYPE = 'File'; - const typeGeoPoint: Parse.Schema.TYPE = 'GeoPoint'; - const typePolygon: Parse.Schema.TYPE = 'Polygon'; - const typeArray: Parse.Schema.TYPE = 'Array'; - const typeObject: Parse.Schema.TYPE = 'Object'; - const typePointer: Parse.Schema.TYPE = 'Pointer'; - const typeRelation: Parse.Schema.TYPE = 'Relation'; -} - -function test_restored_types_direct_exports() { - // ============================================= - // Direct Parse.* exports (top-level) - // These should be accessible directly from Parse namespace - // ============================================= - - // Parse.DestroyOptions (same as Parse.Object.DestroyOptions) - const directDestroyOpts: Parse.DestroyOptions = { - useMasterKey: true, - sessionToken: 'token', - }; - - // Parse.FetchOptions (same as Parse.Object.FetchOptions) - const directFetchOpts: Parse.FetchOptions = { - useMasterKey: true, - include: ['relation'], - }; - - // Parse.SaveOptions (same as Parse.Object.SaveOptions) - const directSaveOpts: Parse.SaveOptions = { - useMasterKey: true, - cascadeSave: true, - context: { key: 'value' }, - }; - - // Parse.SetOptions (same as Parse.Object.SetOptions) - const directSetOpts: Parse.SetOptions = { - ignoreValidation: false, - }; - - // Parse.DestroyAllOptions - const directDestroyAllOpts: Parse.DestroyAllOptions = { - batchSize: 100, - useMasterKey: true, - }; - - // Parse.SaveAllOptions - const directSaveAllOpts: Parse.SaveAllOptions = { - batchSize: 50, - sessionToken: 'token', - }; - - // Parse.FetchAllOptions - const directFetchAllOpts: Parse.FetchAllOptions = { - useMasterKey: true, - }; - - // Parse.QueryOptions (same as Parse.Query.QueryOptions) - const directQueryOpts: Parse.QueryOptions = { - useMasterKey: true, - sessionToken: 'token', - json: true, - }; - - // Parse.FindOptions (same as Parse.Query.FindOptions) - const directFindOpts: Parse.FindOptions = { - useMasterKey: true, - context: { key: 'value' }, - }; - - // Parse.BatchOptions (same as Parse.Query.BatchOptions) - const directBatchOpts: Parse.BatchOptions = { - batchSize: 100, - useMasterKey: true, - json: false, - }; - - // Parse.FullTextOptions (same as Parse.Query.FullTextOptions) - const directFullTextOpts: Parse.FullTextOptions = { - language: 'en', - caseSensitive: false, - diacriticSensitive: true, - }; - - // Parse.TYPE (same as Parse.Schema.TYPE) - const directType: Parse.TYPE = 'String'; - - // Parse.Pointer - object pointer type - const pointer: Parse.Pointer = { - __type: 'Pointer', - className: 'GameScore', - objectId: 'abc123', - }; - - // Parse.Attributes - base attributes type - const attrs: Parse.Attributes = { - score: 100, - playerName: 'John', - }; - - // Parse.BaseAttributes - standard object attributes - const baseAttrs: Parse.BaseAttributes = { - createdAt: new Date(), - updatedAt: new Date(), - objectId: 'abc123', - }; - - // Parse.JSONBaseAttributes - JSON representation of base attributes - const jsonBaseAttrs: Parse.JSONBaseAttributes = { - createdAt: '2023-01-01T00:00:00.000Z', - updatedAt: '2023-01-01T00:00:00.000Z', - objectId: 'abc123', - }; - - // Parse.Encode - utility type - type DirectEncode = Parse.Encode; - - // Parse.ToJSON - utility type - type DirectToJSON = Parse.ToJSON<{ name: string }>; - - // Parse.WhereClause - query where clause type - const whereClause: Parse.WhereClause = { - score: { $gt: 100 }, - playerName: 'John', - }; - - // Parse.QueryJSON - serialized query representation - const queryJson: Parse.QueryJSON = { - where: { score: { $gt: 100 } }, - limit: 10, - skip: 0, - order: 'score', - include: 'player', - keys: 'score,playerName', - }; - - // Parse.RestSchema - schema REST representation - const restSchema: Parse.RestSchema = { - className: 'GameScore', - fields: { - objectId: { type: 'String' }, - createdAt: { type: 'Date' }, - updatedAt: { type: 'Date' }, - ACL: { type: 'ACL' }, - score: { type: 'Number' }, - }, - classLevelPermissions: { - find: { '*': true }, - get: { '*': true }, - create: { '*': true }, - update: { '*': true }, - delete: { '*': true }, - }, - }; - - // Parse.FullOptions - full request options - const fullOpts: Parse.FullOptions = { - useMasterKey: true, - sessionToken: 'token', - installationId: 'install-id', - }; - - // Parse.RequestOptions - request options - const requestOpts: Parse.RequestOptions = { - useMasterKey: true, - sessionToken: 'token', - installationId: 'install-id', - batchSize: 50, - include: ['relation'], - }; - - // Parse.AuthProvider - authentication provider interface - const authProvider: Parse.AuthProvider = { - authenticate: () => { }, - getAuthType: () => 'custom', - restoreAuthentication: () => true, - deauthenticate: () => { }, - }; - - // Parse.AuthData - authentication data - const authData: Parse.AuthData = { - id: 'user-id', - access_token: 'token', - }; - - // Parse.SignUpOptions - user signup options - const signUpOpts: Parse.SignUpOptions = { - useMasterKey: true, - installationId: 'install-id', - }; - - // Parse.PushData - push notification data - const pushData: Parse.PushData = { - channels: ['news', 'updates'], - data: { alert: 'Hello World!' }, - }; - - // Parse.SendOptions - push send options - const sendOpts: Parse.SendOptions = { - useMasterKey: true, - }; -} - -async function test_restored_types_usage_in_methods() { - // ============================================= - // Verify types work correctly with actual Parse methods - // ============================================= - - const obj = new Parse.Object('TestClass'); - const query = new Parse.Query('TestClass'); + // Verify types work with actual methods + const obj = new Parse.Object('Test'); + const query = new Parse.Query('Test'); - // save() accepts SaveOptions - const saveOpts: Parse.SaveOptions = { useMasterKey: true, cascadeSave: false }; await obj.save(null, saveOpts); - - // fetch() accepts FetchOptions - const fetchOpts: Parse.FetchOptions = { useMasterKey: true, include: ['relation'] }; await obj.fetch(fetchOpts); - - // destroy() accepts DestroyOptions - const destroyOpts: Parse.DestroyOptions = { useMasterKey: true }; await obj.destroy(destroyOpts); - - // set() accepts SetOptions - const setOpts: Parse.SetOptions = { ignoreValidation: true }; obj.set('key', 'value', setOpts); - - // Parse.Object.saveAll accepts SaveAllOptions - const saveAllOpts: Parse.SaveAllOptions = { batchSize: 50, useMasterKey: true }; await Parse.Object.saveAll([obj], saveAllOpts); - - // Parse.Object.destroyAll accepts DestroyAllOptions - const destroyAllOpts: Parse.DestroyAllOptions = { batchSize: 100, useMasterKey: true }; await Parse.Object.destroyAll([obj], destroyAllOpts); - - // Parse.Object.fetchAll accepts FetchAllOptions - const fetchAllOpts: Parse.FetchAllOptions = { useMasterKey: true }; await Parse.Object.fetchAll([obj], fetchAllOpts); - - // query.find() accepts FindOptions/QueryOptions - const findOpts: Parse.FindOptions = { useMasterKey: true, json: true }; await query.find(findOpts); - - // query.first() accepts QueryOptions - const queryOpts: Parse.QueryOptions = { useMasterKey: true }; - await query.first(queryOpts); - - // query.get() accepts QueryOptions - await query.get('objectId', queryOpts); - - // query.count() accepts QueryOptions - await query.count(queryOpts); - - // query.each() accepts BatchOptions - const batchOpts: Parse.BatchOptions = { batchSize: 100, useMasterKey: true }; + await query.first(findOpts); + await query.count(findOpts); await query.each(() => { }, batchOpts); - - // query.eachBatch() accepts BatchOptions await query.eachBatch(() => { }, batchOpts); - - // query.fullText() accepts FullTextOptions - const fullTextOpts: Parse.FullTextOptions = { language: 'en', caseSensitive: false }; - query.fullText('field', 'search term', fullTextOpts); + query.fullText('field', 'term', fullTextOpts); } - From 9d5147e438abca8c94fb38c1a7c2400c92ebc945 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 13:08:46 +0700 Subject: [PATCH 05/25] added more options types, not sure --- src/ParseObject.ts | 32 ++++++++++++------ src/ParseQuery.ts | 73 ++++++++++++++++++++++++++++++++++++++---- src/ParseSchema.ts | 18 ++++++----- types/ParseObject.d.ts | 31 ++++++++++++------ types/ParseQuery.d.ts | 63 ++++++++++++++++++++++++++++++++---- types/ParseSchema.d.ts | 12 ++++--- types/index.d.ts | 17 ++++++++-- types/tests.ts | 1 + 8 files changed, 202 insertions(+), 45 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index c0ac3a2f9..5389534aa 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -45,17 +45,15 @@ interface SaveParams { body: AttributeMap; } -export type SaveOptions = FullOptions & { - cascadeSave?: boolean; +export interface SaveOptions extends FullOptions { context?: AttributeMap; + /** If `false`, nested objects will not be saved (default is `true`). */ + cascadeSave?: boolean; batchSize?: number; transaction?: boolean; -}; +} -export interface FetchOptions { - useMasterKey?: boolean; - sessionToken?: string; - include?: string | string[]; +export interface FetchOptions extends RequestOptions { context?: AttributeMap; } @@ -68,7 +66,10 @@ export interface DestroyOptions { useMasterKey?: boolean; sessionToken?: string; context?: AttributeMap; - /** Wait for the server to confirm before resolving */ + /** + * Set to true to wait for the server to confirm success + * before triggering an event. + */ wait?: boolean; } @@ -77,6 +78,8 @@ export interface DestroyAllOptions { batchSize?: number; useMasterKey?: boolean; sessionToken?: string; + /** A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. */ + context?: AttributeMap; } /** Options for saveAll batch operation - matches old namespace Object.SaveAllOptions */ @@ -84,12 +87,18 @@ export interface SaveAllOptions { batchSize?: number; useMasterKey?: boolean; sessionToken?: string; + /** A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. */ + context?: AttributeMap; + /** If `false`, nested objects will not be saved (default is `true`). */ + cascadeSave?: boolean; } -/** Options for fetchAll batch operation - matches old namespace Object.FetchAllOptions */ +/** Options for fetchAll batch operation */ export interface FetchAllOptions { useMasterKey?: boolean; sessionToken?: string; + context?: AttributeMap; + include?: string | string[]; } export type AttributeKey = Extract; @@ -2717,4 +2726,9 @@ export interface ObjectStatic { unPinAllWithName(name: string, objects: ParseObject[]): Promise; } +export interface ObjectConstructor extends ObjectStatic { + new (className: string, attributes: T, options?: any): ParseObject; + new(className?: string, attributes?: Attributes, options?: any): ParseObject; +} + export default ParseObject; diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index 8a5fbe541..b44a058b4 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -11,14 +11,11 @@ import type LiveQuerySubscription from './LiveQuerySubscription'; import type { RequestOptions, FullOptions } from './RESTController'; import type { Pointer } from './ParseObject'; -export type BatchOptions = FullOptions & { +export interface BatchOptions extends FullOptions { batchSize?: number; - useMasterKey?: boolean; - useMaintenanceKey?: boolean; - sessionToken?: string; context?: Record; json?: boolean; -}; +} export type WhereClause = Record; @@ -29,9 +26,73 @@ export interface QueryOptions { json?: boolean; } -/** Alias for QueryOptions, used for find operations */ +/** Alias of QueryOptions (added for old DefinitelyTyped typing compat) */ export type FindOptions = QueryOptions; +/** @deprecated Use QueryOptions */ +export interface EachOptions extends QueryOptions { + batchSize?: number; + useMaintenanceKey?: boolean; + installationId?: string; + progress?: any; + usePost?: boolean; +} + +/** Ditto to QueryOptions for now */ +export type CountOptions = QueryOptions; + +/** Ditto to QueryOptions for now */ +export type GetOptions = QueryOptions; + +/** Ditto to QueryOptions for now */ +export type FirstOptions = QueryOptions; + +export interface AggregationOptions { + group?: (Record & { objectId?: string }) | undefined; + match?: Record | undefined; + project?: Record | undefined; + limit?: number | undefined; + skip?: number | undefined; + sort?: Record | undefined; + sample?: { size: number } | undefined; + count?: string | undefined; + lookup?: + | { + from: string; + localField: string; + foreignField: string; + as: string; + } + | { + from: string; + let?: Record; + pipeline: Record; + as: string; + } + | undefined; + graphLookup?: + | { + from: string; + startWith?: string; + connectFromField: string; + connectToField: string; + as: string; + maxDepth?: number; + depthField?: string; + restrictSearchWithMatch?: Record; + } + | undefined; + facet?: Record>> | undefined; + unwind?: + | { + path: string; + includeArrayIndex?: string; + preserveNullAndEmptyArrays?: boolean; + } + | string + | undefined; +} + export interface FullTextOptions { language?: string; caseSensitive?: boolean; diff --git a/src/ParseSchema.ts b/src/ParseSchema.ts index eaf0aa511..0789a414c 100644 --- a/src/ParseSchema.ts +++ b/src/ParseSchema.ts @@ -10,6 +10,8 @@ import type { Pointer } from './ParseObject'; type Bytes = string; +export type FieldType = TYPE; + export type TYPE = | 'String' | 'Number' @@ -24,15 +26,14 @@ export type TYPE = | 'Pointer' | 'Relation'; -type AttrType = Extract< +export type AttrType = Extract< { [K in keyof T['attributes']]: T['attributes'][K] extends V ? K : never; }[keyof T['attributes']], string >; -interface FieldOptions< - T extends +export type SupportedFieldTypes = | string | number | boolean @@ -44,22 +45,23 @@ interface FieldOptions< | any[] | object | Pointer - | ParseRelation = any, -> { + | ParseRelation; + +export interface FieldOptions { required?: boolean | undefined; defaultValue?: T | undefined; targetClass?: string | undefined; } -type Index = Record; +export type Index = Record; -interface CLPField { +export interface CLPField { '*'?: boolean | undefined; requiresAuthentication?: boolean | undefined; [userIdOrRoleName: string]: boolean | undefined; } -interface CLP { +export interface CLP { find?: CLPField | undefined; get?: CLPField | undefined; count?: CLPField | undefined; diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 9b98528cd..91724edfa 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -18,16 +18,14 @@ interface SaveParams { path: string; body: AttributeMap; } -export type SaveOptions = FullOptions & { - cascadeSave?: boolean; +export interface SaveOptions extends FullOptions { context?: AttributeMap; + /** If `false`, nested objects will not be saved (default is `true`). */ + cascadeSave?: boolean; batchSize?: number; transaction?: boolean; -}; -export interface FetchOptions { - useMasterKey?: boolean; - sessionToken?: string; - include?: string | string[]; +} +export interface FetchOptions extends RequestOptions { context?: AttributeMap; } export interface SetOptions { @@ -38,7 +36,10 @@ export interface DestroyOptions { useMasterKey?: boolean; sessionToken?: string; context?: AttributeMap; - /** Wait for the server to confirm before resolving */ + /** + * Set to true to wait for the server to confirm success + * before triggering an event. + */ wait?: boolean; } /** Options for destroyAll batch operation - matches old namespace Object.DestroyAllOptions */ @@ -46,17 +47,25 @@ export interface DestroyAllOptions { batchSize?: number; useMasterKey?: boolean; sessionToken?: string; + /** A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. */ + context?: AttributeMap; } /** Options for saveAll batch operation - matches old namespace Object.SaveAllOptions */ export interface SaveAllOptions { batchSize?: number; useMasterKey?: boolean; sessionToken?: string; + /** A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. */ + context?: AttributeMap; + /** If `false`, nested objects will not be saved (default is `true`). */ + cascadeSave?: boolean; } -/** Options for fetchAll batch operation - matches old namespace Object.FetchAllOptions */ +/** Options for fetchAll batch operation */ export interface FetchAllOptions { useMasterKey?: boolean; sessionToken?: string; + context?: AttributeMap; + include?: string | string[]; } export type AttributeKey = Extract; export type Attributes = Record; @@ -1116,4 +1125,8 @@ export interface ObjectStatic { unPinAllObjectsWithName(name: string): Promise; unPinAllWithName(name: string, objects: ParseObject[]): Promise; } +export interface ObjectConstructor extends ObjectStatic { + new (className: string, attributes: T, options?: any): ParseObject; + new (className?: string, attributes?: Attributes, options?: any): ParseObject; +} export default ParseObject; diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index af10b8a02..3e296f527 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -3,14 +3,11 @@ import ParseObject from './ParseObject'; import type LiveQuerySubscription from './LiveQuerySubscription'; import type { FullOptions } from './RESTController'; import type { Pointer } from './ParseObject'; -export type BatchOptions = FullOptions & { +export interface BatchOptions extends FullOptions { batchSize?: number; - useMasterKey?: boolean; - useMaintenanceKey?: boolean; - sessionToken?: string; context?: Record; json?: boolean; -}; +} export type WhereClause = Record; export interface QueryOptions { useMasterKey?: boolean; @@ -18,8 +15,62 @@ export interface QueryOptions { context?: Record; json?: boolean; } -/** Alias for QueryOptions, used for find operations */ +/** Alias of QueryOptions (added for old DefinitelyTyped typing compat) */ export type FindOptions = QueryOptions; +export interface EachOptions extends QueryOptions { + batchSize?: number; + useMaintenanceKey?: boolean; + installationId?: string; + progress?: any; + usePost?: boolean; +} +/** Ditto to QueryOptions for now */ +export type CountOptions = QueryOptions; +/** Ditto to QueryOptions for now */ +export type GetOptions = QueryOptions; +/** Ditto to QueryOptions for now */ +export type FirstOptions = QueryOptions; +export interface AggregationOptions { + group?: (Record & { + objectId?: string; + }) | undefined; + match?: Record | undefined; + project?: Record | undefined; + limit?: number | undefined; + skip?: number | undefined; + sort?: Record | undefined; + sample?: { + size: number; + } | undefined; + count?: string | undefined; + lookup?: { + from: string; + localField: string; + foreignField: string; + as: string; + } | { + from: string; + let?: Record; + pipeline: Record; + as: string; + } | undefined; + graphLookup?: { + from: string; + startWith?: string; + connectFromField: string; + connectToField: string; + as: string; + maxDepth?: number; + depthField?: string; + restrictSearchWithMatch?: Record; + } | undefined; + facet?: Record>> | undefined; + unwind?: { + path: string; + includeArrayIndex?: string; + preserveNullAndEmptyArrays?: boolean; + } | string | undefined; +} export interface FullTextOptions { language?: string; caseSensitive?: boolean; diff --git a/types/ParseSchema.d.ts b/types/ParseSchema.d.ts index 3d3ccb7fa..a924f1dba 100644 --- a/types/ParseSchema.d.ts +++ b/types/ParseSchema.d.ts @@ -7,22 +7,24 @@ import type ParseRelation from './ParseRelation'; import type { PermissionsMap } from './ParseCLP'; import type { Pointer } from './ParseObject'; type Bytes = string; +export type FieldType = TYPE; export type TYPE = 'String' | 'Number' | 'Bytes' | 'Boolean' | 'Date' | 'File' | 'GeoPoint' | 'Polygon' | 'Array' | 'Object' | 'Pointer' | 'Relation'; -type AttrType = Extract<{ +export type AttrType = Extract<{ [K in keyof T['attributes']]: T['attributes'][K] extends V ? K : never; }[keyof T['attributes']], string>; -interface FieldOptions { +export type SupportedFieldTypes = string | number | boolean | Bytes | Date | ParseFile | ParseGeoPoint | ParsePolygon | any[] | object | Pointer | ParseRelation; +export interface FieldOptions { required?: boolean | undefined; defaultValue?: T | undefined; targetClass?: string | undefined; } -type Index = Record; -interface CLPField { +export type Index = Record; +export interface CLPField { '*'?: boolean | undefined; requiresAuthentication?: boolean | undefined; [userIdOrRoleName: string]: boolean | undefined; } -interface CLP { +export interface CLP { find?: CLPField | undefined; get?: CLPField | undefined; count?: CLPField | undefined; diff --git a/types/index.d.ts b/types/index.d.ts index de88ced2d..e180c570d 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -35,11 +35,11 @@ import User from './ParseUser'; import LiveQuerySubscription from './LiveQuerySubscription'; export type { AuthProvider, AuthData, SignUpOptions } from './ParseUser'; -export type { Pointer, Attributes, BaseAttributes, JSONBaseAttributes, ObjectStatic, FetchOptions, SaveOptions, SetOptions, DestroyOptions, DestroyAllOptions, SaveAllOptions, FetchAllOptions, Encode, ToJSON } from './ParseObject'; +export type { Pointer, Attributes, BaseAttributes, JSONBaseAttributes, ObjectStatic, ObjectConstructor, FetchOptions, SaveOptions, SetOptions, DestroyOptions, DestroyAllOptions, SaveAllOptions, FetchAllOptions, Encode, ToJSON } from './ParseObject'; export type { PushData, SendOptions } from './Push'; export type { FullOptions, RequestOptions } from './RESTController'; export type { RestSchema, TYPE } from './ParseSchema'; -export type { FindOptions, QueryOptions, QueryJSON, WhereClause, BatchOptions, FullTextOptions } from './ParseQuery'; +export type { FindOptions, QueryOptions, QueryJSON, WhereClause, BatchOptions, FullTextOptions, EachOptions, CountOptions, GetOptions, FirstOptions, AggregationOptions } from './ParseQuery'; export { LiveQuerySubscription }; export { ACL, @@ -93,8 +93,21 @@ export namespace Query { export type QueryOptions = import('./ParseQuery').QueryOptions; export type BatchOptions = import('./ParseQuery').BatchOptions; export type FullTextOptions = import('./ParseQuery').FullTextOptions; + export type EachOptions = import('./ParseQuery').EachOptions; + export type CountOptions = import('./ParseQuery').CountOptions; + export type GetOptions = import('./ParseQuery').GetOptions; + export type FirstOptions = import('./ParseQuery').FirstOptions; + export type AggregationOptions = import('./ParseQuery').AggregationOptions; } export namespace Schema { export type TYPE = import('./ParseSchema').TYPE; + export type FieldType = import('./ParseSchema').FieldType; + export type FieldOptions< + T extends import('./ParseSchema').SupportedFieldTypes = any + > = import('./ParseSchema').FieldOptions; + export type Index = import('./ParseSchema').Index; + export type CLP = import('./ParseSchema').CLP; + export type CLPField = import('./ParseSchema').CLPField; + export type AttrType = import('./ParseSchema').AttrType; } diff --git a/types/tests.ts b/types/tests.ts index 5e3fb8bfc..d0eb4ba93 100644 --- a/types/tests.ts +++ b/types/tests.ts @@ -2335,6 +2335,7 @@ function testEventuallyQueue() { } } +// TODO: Add missing LiveQuery types (LiveQuerySubscription, etc.) function LiveQueryEvents() { function testLiveQueryEvents() { Parse.LiveQuery.on('open', () => { }); From 9d2d5dc008d230e930dc6f9fe657c3970b09f24a Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 13:20:06 +0700 Subject: [PATCH 06/25] use options for types --- src/ParseQuery.ts | 46 +++++++++++++++++++-------------------- types/ParseQuery.d.ts | 50 +++++++++++++++++++++---------------------- types/index.d.ts | 6 +++--- 3 files changed, 51 insertions(+), 51 deletions(-) diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index b44a058b4..20e3bfca0 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -11,11 +11,7 @@ import type LiveQuerySubscription from './LiveQuerySubscription'; import type { RequestOptions, FullOptions } from './RESTController'; import type { Pointer } from './ParseObject'; -export interface BatchOptions extends FullOptions { - batchSize?: number; - context?: Record; - json?: boolean; -} + export type WhereClause = Record; @@ -26,10 +22,8 @@ export interface QueryOptions { json?: boolean; } -/** Alias of QueryOptions (added for old DefinitelyTyped typing compat) */ -export type FindOptions = QueryOptions; +export interface FindOptions extends QueryOptions { } -/** @deprecated Use QueryOptions */ export interface EachOptions extends QueryOptions { batchSize?: number; useMaintenanceKey?: boolean; @@ -38,14 +32,20 @@ export interface EachOptions extends QueryOptions { usePost?: boolean; } -/** Ditto to QueryOptions for now */ -export type CountOptions = QueryOptions; +export interface BatchOptions extends FullOptions { + batchSize?: number; + useMasterKey?: boolean; + useMaintenanceKey?: boolean; + sessionToken?: string; + context?: Record; + json?: boolean; +} + +export interface CountOptions extends QueryOptions { } -/** Ditto to QueryOptions for now */ -export type GetOptions = QueryOptions; +export interface GetOptions extends QueryOptions { } -/** Ditto to QueryOptions for now */ -export type FirstOptions = QueryOptions; +export interface FirstOptions extends QueryOptions { } export interface AggregationOptions { group?: (Record & { objectId?: string }) | undefined; @@ -710,7 +710,7 @@ class ParseQuery { * @returns {Promise} A promise that is resolved with the result when * the query completes. */ - get(objectId: string, options?: QueryOptions): Promise { + get(objectId: string, options?: GetOptions): Promise { this.equalTo('objectId', objectId as any); const firstOptions = ParseObject._getRequestOptions(options); @@ -739,7 +739,7 @@ class ParseQuery { * @returns {Promise} A promise that is resolved with the results when * the query completes. */ - find(options?: QueryOptions): Promise { + find(options?: FindOptions): Promise { const findOptions = ParseObject._getRequestOptions(options); this._setRequestTask(findOptions); @@ -823,7 +823,7 @@ class ParseQuery { * @returns {Promise} A promise that is resolved with the count when * the query completes. */ - count(options?: { useMasterKey?: boolean; sessionToken?: string }): Promise { + count(options?: CountOptions): Promise { options = options || {}; const findOptions = ParseObject._getRequestOptions(options); @@ -907,7 +907,7 @@ class ParseQuery { * @returns {Promise} A promise that is resolved with the object when * the query completes. */ - first(options: QueryOptions = {}): Promise { + first(options: FirstOptions = {}): Promise { const findOptions = ParseObject._getRequestOptions(options); this._setRequestTask(findOptions); @@ -973,7 +973,7 @@ class ParseQuery { */ eachBatch( callback: (objs: T[]) => PromiseLike | void, - options?: BatchOptions + options?: EachOptions ): Promise { options = options || {}; @@ -1035,7 +1035,7 @@ class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - each(callback: (obj: T) => PromiseLike | void, options?: BatchOptions): Promise { + each(callback: (obj: T) => PromiseLike | void, options?: EachOptions): Promise { return this.eachBatch(results => { let callbacksDone = Promise.resolve(); results.forEach((result: T) => { @@ -1099,7 +1099,7 @@ class ParseQuery { */ async map( callback: (currentObject: ParseObject, index: number, query: ParseQuery) => any, - options?: BatchOptions + options?: EachOptions ): Promise { const array: ParseObject[] = []; let index = 0; @@ -1138,7 +1138,7 @@ class ParseQuery { async reduce( callback: (accumulator: any, currentObject: ParseObject, index: number) => any, initialValue: any, - options?: BatchOptions + options?: EachOptions ): Promise { let accumulator = initialValue; let index = 0; @@ -1187,7 +1187,7 @@ class ParseQuery { */ async filter( callback: (currentObject: ParseObject, index: number, query: ParseQuery) => boolean, - options?: BatchOptions + options?: EachOptions ): Promise { const array: ParseObject[] = []; let index = 0; diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index 3e296f527..059a5a7ad 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -3,11 +3,6 @@ import ParseObject from './ParseObject'; import type LiveQuerySubscription from './LiveQuerySubscription'; import type { FullOptions } from './RESTController'; import type { Pointer } from './ParseObject'; -export interface BatchOptions extends FullOptions { - batchSize?: number; - context?: Record; - json?: boolean; -} export type WhereClause = Record; export interface QueryOptions { useMasterKey?: boolean; @@ -15,8 +10,8 @@ export interface QueryOptions { context?: Record; json?: boolean; } -/** Alias of QueryOptions (added for old DefinitelyTyped typing compat) */ -export type FindOptions = QueryOptions; +export interface FindOptions extends QueryOptions { +} export interface EachOptions extends QueryOptions { batchSize?: number; useMaintenanceKey?: boolean; @@ -24,12 +19,20 @@ export interface EachOptions extends QueryOptions { progress?: any; usePost?: boolean; } -/** Ditto to QueryOptions for now */ -export type CountOptions = QueryOptions; -/** Ditto to QueryOptions for now */ -export type GetOptions = QueryOptions; -/** Ditto to QueryOptions for now */ -export type FirstOptions = QueryOptions; +export interface BatchOptions extends FullOptions { + batchSize?: number; + useMasterKey?: boolean; + useMaintenanceKey?: boolean; + sessionToken?: string; + context?: Record; + json?: boolean; +} +export interface CountOptions extends QueryOptions { +} +export interface GetOptions extends QueryOptions { +} +export interface FirstOptions extends QueryOptions { +} export interface AggregationOptions { group?: (Record & { objectId?: string; @@ -262,7 +265,7 @@ declare class ParseQuery { * @returns {Promise} A promise that is resolved with the result when * the query completes. */ - get(objectId: string, options?: QueryOptions): Promise; + get(objectId: string, options?: GetOptions): Promise; /** * Retrieves a list of ParseObjects that satisfy this query. * @@ -278,7 +281,7 @@ declare class ParseQuery { * @returns {Promise} A promise that is resolved with the results when * the query completes. */ - find(options?: QueryOptions): Promise; + find(options?: FindOptions): Promise; /** * Retrieves a complete list of ParseObjects that satisfy this query. * Using `eachBatch` under the hood to fetch all the valid objects. @@ -310,10 +313,7 @@ declare class ParseQuery { * @returns {Promise} A promise that is resolved with the count when * the query completes. */ - count(options?: { - useMasterKey?: boolean; - sessionToken?: string; - }): Promise; + count(options?: CountOptions): Promise; /** * Executes a distinct query and returns unique values * @@ -344,7 +344,7 @@ declare class ParseQuery { * @returns {Promise} A promise that is resolved with the object when * the query completes. */ - first(options?: QueryOptions): Promise; + first(options?: FirstOptions): Promise; /** * Iterates over objects matching a query, calling a callback for each batch. * If the callback returns a promise, the iteration will not continue until @@ -366,7 +366,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - eachBatch(callback: (objs: T[]) => PromiseLike | void, options?: BatchOptions): Promise; + eachBatch(callback: (objs: T[]) => PromiseLike | void, options?: EachOptions): Promise; /** * Iterates over each result of a query, calling a callback for each one. If * the callback returns a promise, the iteration will not continue until @@ -387,7 +387,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - each(callback: (obj: T) => PromiseLike | void, options?: BatchOptions): Promise; + each(callback: (obj: T) => PromiseLike | void, options?: EachOptions): Promise; /** * Adds a hint to force index selection. (https://docs.mongodb.com/manual/reference/operator/meta/hint/) * @@ -424,7 +424,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - map(callback: (currentObject: ParseObject, index: number, query: ParseQuery) => any, options?: BatchOptions): Promise; + map(callback: (currentObject: ParseObject, index: number, query: ParseQuery) => any, options?: EachOptions): Promise; /** * Iterates over each result of a query, calling a callback for each one. If * the callback returns a promise, the iteration will not continue until @@ -448,7 +448,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - reduce(callback: (accumulator: any, currentObject: ParseObject, index: number) => any, initialValue: any, options?: BatchOptions): Promise; + reduce(callback: (accumulator: any, currentObject: ParseObject, index: number) => any, initialValue: any, options?: EachOptions): Promise; /** * Iterates over each result of a query, calling a callback for each one. If * the callback returns a promise, the iteration will not continue until @@ -471,7 +471,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - filter(callback: (currentObject: ParseObject, index: number, query: ParseQuery) => boolean, options?: BatchOptions): Promise; + filter(callback: (currentObject: ParseObject, index: number, query: ParseQuery) => boolean, options?: EachOptions): Promise; /** * Adds a constraint to the query that requires a particular key's value to * be equal to the provided value. diff --git a/types/index.d.ts b/types/index.d.ts index e180c570d..ba251b166 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -39,7 +39,7 @@ export type { Pointer, Attributes, BaseAttributes, JSONBaseAttributes, ObjectSta export type { PushData, SendOptions } from './Push'; export type { FullOptions, RequestOptions } from './RESTController'; export type { RestSchema, TYPE } from './ParseSchema'; -export type { FindOptions, QueryOptions, QueryJSON, WhereClause, BatchOptions, FullTextOptions, EachOptions, CountOptions, GetOptions, FirstOptions, AggregationOptions } from './ParseQuery'; +export type { FindOptions, QueryOptions, QueryJSON, WhereClause, FullTextOptions, EachOptions, BatchOptions, CountOptions, GetOptions, FirstOptions, AggregationOptions } from './ParseQuery'; export { LiveQuerySubscription }; export { ACL, @@ -91,9 +91,9 @@ export namespace Object { export namespace Query { export type FindOptions = import('./ParseQuery').FindOptions; export type QueryOptions = import('./ParseQuery').QueryOptions; - export type BatchOptions = import('./ParseQuery').BatchOptions; - export type FullTextOptions = import('./ParseQuery').FullTextOptions; export type EachOptions = import('./ParseQuery').EachOptions; + export type FullTextOptions = import('./ParseQuery').FullTextOptions; + export type BatchOptions = import('./ParseQuery').BatchOptions; export type CountOptions = import('./ParseQuery').CountOptions; export type GetOptions = import('./ParseQuery').GetOptions; export type FirstOptions = import('./ParseQuery').FirstOptions; From 608820ee3cb722f868c87c8f95025cbf52e140cb Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 15:32:37 +0700 Subject: [PATCH 07/25] better ObjectStatic --- src/ParseObject.ts | 33 ++++++++++++++++++--------------- types/ParseObject.d.ts | 19 +++++++++++-------- types/tests.ts | 10 ++++++++-- 3 files changed, 37 insertions(+), 25 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 5389534aa..34b47180a 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -53,7 +53,10 @@ export interface SaveOptions extends FullOptions { transaction?: boolean; } -export interface FetchOptions extends RequestOptions { +export interface FetchOptions { + useMasterKey?: boolean; + sessionToken?: string; + include?: string | string[]; context?: AttributeMap; } @@ -1866,9 +1869,9 @@ class ParseObject { * @returns {Promise} A promise that is fulfilled when the destroyAll * completes. */ - static destroyAll(list: ParseObject[], options?: DestroyAllOptions) { + static destroyAll(list: T[], options?: DestroyAllOptions): Promise { const destroyOptions = ParseObject._getRequestOptions(options); - return CoreManager.getObjectController().destroy(list, destroyOptions); + return CoreManager.getObjectController().destroy(list, destroyOptions) as Promise; } /** @@ -2701,25 +2704,25 @@ CoreManager.setObjectController(DefaultController); export interface ObjectStatic { createWithoutData(id: string): T; - destroyAll(list: T[], options?: DestroyAllOptions): Promise; + destroyAll(list: U[], options?: DestroyAllOptions): Promise; extend(className: string | { className: string }, protoProps?: any, classProps?: any): any; - fetchAll(list: T[], options: FetchAllOptions): Promise; - fetchAllIfNeeded(list: T[], options?: FetchAllOptions): Promise; - fetchAllIfNeededWithInclude( - list: T[], - keys: keyof T["attributes"] | Array, + fetchAll(list: U[], options?: FetchAllOptions): Promise; + fetchAllIfNeeded(list: U[], options?: FetchAllOptions): Promise; + fetchAllIfNeededWithInclude( + list: U[], + keys: keyof U["attributes"] | Array, options?: RequestOptions, - ): Promise; - fetchAllWithInclude( - list: T[], - keys: keyof T["attributes"] | Array, + ): Promise; + fetchAllWithInclude( + list: U[], + keys: keyof U["attributes"] | Array, options?: RequestOptions, - ): Promise; + ): Promise; fromJSON(json: any, override?: boolean): T; pinAll(objects: ParseObject[]): Promise; pinAllWithName(name: string, objects: ParseObject[]): Promise; registerSubclass(className: string, clazz: new (options?: any) => T): void; - saveAll(list: T, options?: SaveAllOptions): Promise; + saveAll(list: U, options?: SaveAllOptions): Promise; unPinAll(objects: ParseObject[]): Promise; unPinAllObjects(): Promise; unPinAllObjectsWithName(name: string): Promise; diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 91724edfa..e9e574ec7 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -25,7 +25,10 @@ export interface SaveOptions extends FullOptions { batchSize?: number; transaction?: boolean; } -export interface FetchOptions extends RequestOptions { +export interface FetchOptions { + useMasterKey?: boolean; + sessionToken?: string; + include?: string | string[]; context?: AttributeMap; } export interface SetOptions { @@ -887,7 +890,7 @@ declare class ParseObject { * @returns {Promise} A promise that is fulfilled when the destroyAll * completes. */ - static destroyAll(list: ParseObject[], options?: DestroyAllOptions): Promise | ParseObject[]>; + static destroyAll(list: T[], options?: DestroyAllOptions): Promise; /** * Saves the given list of Parse.Object. * If any error is encountered, stops and calls the error handler. @@ -1107,19 +1110,19 @@ declare class ParseObject { } export interface ObjectStatic { createWithoutData(id: string): T; - destroyAll(list: T[], options?: DestroyAllOptions): Promise; + destroyAll(list: U[], options?: DestroyAllOptions): Promise; extend(className: string | { className: string; }, protoProps?: any, classProps?: any): any; - fetchAll(list: T[], options: FetchAllOptions): Promise; - fetchAllIfNeeded(list: T[], options?: FetchAllOptions): Promise; - fetchAllIfNeededWithInclude(list: T[], keys: keyof T["attributes"] | Array, options?: RequestOptions): Promise; - fetchAllWithInclude(list: T[], keys: keyof T["attributes"] | Array, options?: RequestOptions): Promise; + fetchAll(list: U[], options?: FetchAllOptions): Promise; + fetchAllIfNeeded(list: U[], options?: FetchAllOptions): Promise; + fetchAllIfNeededWithInclude(list: U[], keys: keyof U["attributes"] | Array, options?: RequestOptions): Promise; + fetchAllWithInclude(list: U[], keys: keyof U["attributes"] | Array, options?: RequestOptions): Promise; fromJSON(json: any, override?: boolean): T; pinAll(objects: ParseObject[]): Promise; pinAllWithName(name: string, objects: ParseObject[]): Promise; registerSubclass(className: string, clazz: new (options?: any) => T): void; - saveAll(list: T, options?: SaveAllOptions): Promise; + saveAll(list: U, options?: SaveAllOptions): Promise; unPinAll(objects: ParseObject[]): Promise; unPinAllObjects(): Promise; unPinAllObjectsWithName(name: string): Promise; diff --git a/types/tests.ts b/types/tests.ts index d0eb4ba93..9ae444f09 100644 --- a/types/tests.ts +++ b/types/tests.ts @@ -2419,11 +2419,17 @@ async function test_type_exports() { const cloudRunOpts: Parse.Cloud.RunOptions = { useMasterKey: true, context: {} }; const subscription: Parse.LiveQuerySubscription = await new Parse.Query('Test').subscribe(); - // ObjectStatic with generics - const objectStatic: Parse.ObjectStatic = Parse.Object; + class MyClass extends Parse.Object { + constructor() { + super('MyClass'); + } + } + // ObjectStatic with generic subclasses + const objectStatic: Parse.ObjectStatic = MyClass; function doCreateWithoutData(clz: Parse.ObjectStatic, id: string): T { return clz.createWithoutData(id); } + const myClsObj = doCreateWithoutData(MyClass, '1'); // Verify types work with actual methods const obj = new Parse.Object('Test'); From 0c17bfeed1609f9152075e28aeac606a1ed3a67a Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 15:46:34 +0700 Subject: [PATCH 08/25] fixed object generics on ObjectStatic --- src/ParseObject.ts | 1 + types/ParseObject.d.ts | 1 + types/tests.ts | 1 + 3 files changed, 3 insertions(+) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 4910798c7..d3b4f8180 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -2703,6 +2703,7 @@ CoreManager.setParseObject(ParseObject); CoreManager.setObjectController(DefaultController); export interface ObjectStatic { + new(...args: any[]): T; createWithoutData(id: string): T; destroyAll(list: U[], options?: DestroyAllOptions): Promise; extend(className: string | { className: string }, protoProps?: any, classProps?: any): any; diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 6b7a7c7e2..4ce1e1f9f 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -1109,6 +1109,7 @@ declare class ParseObject { static unPinAllObjectsWithName(name: string): Promise; } export interface ObjectStatic { + new (...args: any[]): T; createWithoutData(id: string): T; destroyAll(list: U[], options?: DestroyAllOptions): Promise; extend(className: string | { diff --git a/types/tests.ts b/types/tests.ts index bb6512909..3ed2c1e0d 100644 --- a/types/tests.ts +++ b/types/tests.ts @@ -2464,6 +2464,7 @@ async function test_type_exports() { function doCreateWithoutData(clz: Parse.ObjectStatic, id: string): T { return clz.createWithoutData(id); } + // $ExpectType MyClass const myClsObj = doCreateWithoutData(MyClass, '1'); // Verify types work with actual methods From 84f3931eedaa3297b4c9586e4b676d1761a508b7 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 15:49:06 +0700 Subject: [PATCH 09/25] reuse baseAttributes --- src/ParseQuery.ts | 9 +-------- types/ParseQuery.d.ts | 7 +------ 2 files changed, 2 insertions(+), 14 deletions(-) diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index 0d9777663..60c72e0a6 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -9,9 +9,7 @@ import { DEFAULT_PIN } from './LocalDatastoreUtils'; import type LiveQuerySubscription from './LiveQuerySubscription'; import type { RequestOptions, FullOptions } from './RESTController'; -import type { Pointer } from './ParseObject'; - - +import type { Pointer, BaseAttributes } from './ParseObject'; export type WhereClause = Record; @@ -118,11 +116,6 @@ export interface QueryJSON { comment?: string; } -interface BaseAttributes { - createdAt: Date; - objectId: string; - updatedAt: Date; -} /** * Converts a string into a regex that matches it. diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index 3a866d4dc..fe63387bd 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -2,7 +2,7 @@ import ParseGeoPoint from './ParseGeoPoint'; import ParseObject from './ParseObject'; import type LiveQuerySubscription from './LiveQuerySubscription'; import type { FullOptions } from './RESTController'; -import type { Pointer } from './ParseObject'; +import type { Pointer, BaseAttributes } from './ParseObject'; export type WhereClause = Record; export interface QueryOptions { useMasterKey?: boolean; @@ -97,11 +97,6 @@ export interface QueryJSON { subqueryReadPreference?: string; comment?: string; } -interface BaseAttributes { - createdAt: Date; - objectId: string; - updatedAt: Date; -} /** * Creates a new parse Parse.Query for the given Parse.Object subclass. * From 96dd564d19cc1b20ab270602f95e2e7eae99e297 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 16:12:26 +0700 Subject: [PATCH 10/25] reorder to reduce PR clutter --- src/ParseObject.ts | 4 ++-- src/ParseQuery.ts | 34 ++++++++++++++-------------------- types/ParseObject.d.ts | 4 ++-- types/ParseQuery.d.ts | 31 ++++++++++++------------------- 4 files changed, 30 insertions(+), 43 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index d3b4f8180..881f4458d 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -76,7 +76,7 @@ export interface DestroyOptions { wait?: boolean; } -/** Options for destroyAll batch operation - matches old namespace Object.DestroyAllOptions */ +/** Options for destroyAll batch operation */ export interface DestroyAllOptions { batchSize?: number; useMasterKey?: boolean; @@ -85,7 +85,7 @@ export interface DestroyAllOptions { context?: AttributeMap; } -/** Options for saveAll batch operation - matches old namespace Object.SaveAllOptions */ +/** Options for saveAll batch operation */ export interface SaveAllOptions { batchSize?: number; useMasterKey?: boolean; diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index 60c72e0a6..104b38ed2 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -11,34 +11,28 @@ import type LiveQuerySubscription from './LiveQuerySubscription'; import type { RequestOptions, FullOptions } from './RESTController'; import type { Pointer, BaseAttributes } from './ParseObject'; -export type WhereClause = Record; - -export interface QueryOptions { +export interface BatchOptions extends FullOptions { + batchSize?: number; useMasterKey?: boolean; + useMaintenanceKey?: boolean; sessionToken?: string; context?: Record; json?: boolean; } -export interface FindOptions extends QueryOptions { } - -export interface EachOptions extends QueryOptions { - batchSize?: number; - useMaintenanceKey?: boolean; - installationId?: string; - progress?: any; - usePost?: boolean; -} +export type WhereClause = Record; -export interface BatchOptions extends FullOptions { - batchSize?: number; +export interface QueryOptions { useMasterKey?: boolean; - useMaintenanceKey?: boolean; sessionToken?: string; context?: Record; json?: boolean; } +export interface FindOptions extends QueryOptions { } + + + export interface CountOptions extends QueryOptions { } export interface GetOptions extends QueryOptions { } @@ -966,7 +960,7 @@ class ParseQuery { */ eachBatch( callback: (objs: T[]) => PromiseLike | void, - options?: EachOptions + options?: BatchOptions ): Promise { options = options || {}; @@ -1028,7 +1022,7 @@ class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - each(callback: (obj: T) => PromiseLike | void, options?: EachOptions): Promise { + each(callback: (obj: T) => PromiseLike | void, options?: BatchOptions): Promise { return this.eachBatch(results => { let callbacksDone = Promise.resolve(); results.forEach((result: T) => { @@ -1092,7 +1086,7 @@ class ParseQuery { */ async map( callback: (currentObject: ParseObject, index: number, query: ParseQuery) => any, - options?: EachOptions + options?: BatchOptions ): Promise { const array: ParseObject[] = []; let index = 0; @@ -1131,7 +1125,7 @@ class ParseQuery { async reduce( callback: (accumulator: any, currentObject: ParseObject, index: number) => any, initialValue: any, - options?: EachOptions + options?: BatchOptions ): Promise { let accumulator = initialValue; let index = 0; @@ -1180,7 +1174,7 @@ class ParseQuery { */ async filter( callback: (currentObject: ParseObject, index: number, query: ParseQuery) => boolean, - options?: EachOptions + options?: BatchOptions ): Promise { const array: ParseObject[] = []; let index = 0; diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 4ce1e1f9f..fe2d67dc7 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -45,7 +45,7 @@ export interface DestroyOptions { */ wait?: boolean; } -/** Options for destroyAll batch operation - matches old namespace Object.DestroyAllOptions */ +/** Options for destroyAll batch operation */ export interface DestroyAllOptions { batchSize?: number; useMasterKey?: boolean; @@ -53,7 +53,7 @@ export interface DestroyAllOptions { /** A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. */ context?: AttributeMap; } -/** Options for saveAll batch operation - matches old namespace Object.SaveAllOptions */ +/** Options for saveAll batch operation */ export interface SaveAllOptions { batchSize?: number; useMasterKey?: boolean; diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index fe63387bd..1ce4843fc 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -3,30 +3,23 @@ import ParseObject from './ParseObject'; import type LiveQuerySubscription from './LiveQuerySubscription'; import type { FullOptions } from './RESTController'; import type { Pointer, BaseAttributes } from './ParseObject'; -export type WhereClause = Record; -export interface QueryOptions { +export interface BatchOptions extends FullOptions { + batchSize?: number; useMasterKey?: boolean; + useMaintenanceKey?: boolean; sessionToken?: string; context?: Record; json?: boolean; } -export interface FindOptions extends QueryOptions { -} -export interface EachOptions extends QueryOptions { - batchSize?: number; - useMaintenanceKey?: boolean; - installationId?: string; - progress?: any; - usePost?: boolean; -} -export interface BatchOptions extends FullOptions { - batchSize?: number; +export type WhereClause = Record; +export interface QueryOptions { useMasterKey?: boolean; - useMaintenanceKey?: boolean; sessionToken?: string; context?: Record; json?: boolean; } +export interface FindOptions extends QueryOptions { +} export interface CountOptions extends QueryOptions { } export interface GetOptions extends QueryOptions { @@ -361,7 +354,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - eachBatch(callback: (objs: T[]) => PromiseLike | void, options?: EachOptions): Promise; + eachBatch(callback: (objs: T[]) => PromiseLike | void, options?: BatchOptions): Promise; /** * Iterates over each result of a query, calling a callback for each one. If * the callback returns a promise, the iteration will not continue until @@ -382,7 +375,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - each(callback: (obj: T) => PromiseLike | void, options?: EachOptions): Promise; + each(callback: (obj: T) => PromiseLike | void, options?: BatchOptions): Promise; /** * Adds a hint to force index selection. (https://docs.mongodb.com/manual/reference/operator/meta/hint/) * @@ -419,7 +412,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - map(callback: (currentObject: ParseObject, index: number, query: ParseQuery) => any, options?: EachOptions): Promise; + map(callback: (currentObject: ParseObject, index: number, query: ParseQuery) => any, options?: BatchOptions): Promise; /** * Iterates over each result of a query, calling a callback for each one. If * the callback returns a promise, the iteration will not continue until @@ -443,7 +436,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - reduce(callback: (accumulator: any, currentObject: ParseObject, index: number) => any, initialValue: any, options?: EachOptions): Promise; + reduce(callback: (accumulator: any, currentObject: ParseObject, index: number) => any, initialValue: any, options?: BatchOptions): Promise; /** * Iterates over each result of a query, calling a callback for each one. If * the callback returns a promise, the iteration will not continue until @@ -466,7 +459,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - filter(callback: (currentObject: ParseObject, index: number, query: ParseQuery) => boolean, options?: EachOptions): Promise; + filter(callback: (currentObject: ParseObject, index: number, query: ParseQuery) => boolean, options?: BatchOptions): Promise; /** * Adds a constraint to the query that requires a particular key's value to * be equal to the provided value. From 05529d8883d8cf8c222c0bc8820e3f6f056dedd4 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 16:17:40 +0700 Subject: [PATCH 11/25] removed aggregationoptions for now; confusing --- src/ParseQuery.ts | 46 +------------------------------------------ types/ParseQuery.d.ts | 41 -------------------------------------- types/index.d.ts | 4 +--- 3 files changed, 2 insertions(+), 89 deletions(-) diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index 104b38ed2..d06f46def 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -39,51 +39,7 @@ export interface GetOptions extends QueryOptions { } export interface FirstOptions extends QueryOptions { } -export interface AggregationOptions { - group?: (Record & { objectId?: string }) | undefined; - match?: Record | undefined; - project?: Record | undefined; - limit?: number | undefined; - skip?: number | undefined; - sort?: Record | undefined; - sample?: { size: number } | undefined; - count?: string | undefined; - lookup?: - | { - from: string; - localField: string; - foreignField: string; - as: string; - } - | { - from: string; - let?: Record; - pipeline: Record; - as: string; - } - | undefined; - graphLookup?: - | { - from: string; - startWith?: string; - connectFromField: string; - connectToField: string; - as: string; - maxDepth?: number; - depthField?: string; - restrictSearchWithMatch?: Record; - } - | undefined; - facet?: Record>> | undefined; - unwind?: - | { - path: string; - includeArrayIndex?: string; - preserveNullAndEmptyArrays?: boolean; - } - | string - | undefined; -} + export interface FullTextOptions { language?: string; diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index 1ce4843fc..1f8a388b5 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -26,47 +26,6 @@ export interface GetOptions extends QueryOptions { } export interface FirstOptions extends QueryOptions { } -export interface AggregationOptions { - group?: (Record & { - objectId?: string; - }) | undefined; - match?: Record | undefined; - project?: Record | undefined; - limit?: number | undefined; - skip?: number | undefined; - sort?: Record | undefined; - sample?: { - size: number; - } | undefined; - count?: string | undefined; - lookup?: { - from: string; - localField: string; - foreignField: string; - as: string; - } | { - from: string; - let?: Record; - pipeline: Record; - as: string; - } | undefined; - graphLookup?: { - from: string; - startWith?: string; - connectFromField: string; - connectToField: string; - as: string; - maxDepth?: number; - depthField?: string; - restrictSearchWithMatch?: Record; - } | undefined; - facet?: Record>> | undefined; - unwind?: { - path: string; - includeArrayIndex?: string; - preserveNullAndEmptyArrays?: boolean; - } | string | undefined; -} export interface FullTextOptions { language?: string; caseSensitive?: boolean; diff --git a/types/index.d.ts b/types/index.d.ts index ba251b166..4ecf952f2 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -39,7 +39,7 @@ export type { Pointer, Attributes, BaseAttributes, JSONBaseAttributes, ObjectSta export type { PushData, SendOptions } from './Push'; export type { FullOptions, RequestOptions } from './RESTController'; export type { RestSchema, TYPE } from './ParseSchema'; -export type { FindOptions, QueryOptions, QueryJSON, WhereClause, FullTextOptions, EachOptions, BatchOptions, CountOptions, GetOptions, FirstOptions, AggregationOptions } from './ParseQuery'; +export type { FindOptions, QueryOptions, QueryJSON, WhereClause, FullTextOptions, BatchOptions, CountOptions, GetOptions, FirstOptions } from './ParseQuery'; export { LiveQuerySubscription }; export { ACL, @@ -91,13 +91,11 @@ export namespace Object { export namespace Query { export type FindOptions = import('./ParseQuery').FindOptions; export type QueryOptions = import('./ParseQuery').QueryOptions; - export type EachOptions = import('./ParseQuery').EachOptions; export type FullTextOptions = import('./ParseQuery').FullTextOptions; export type BatchOptions = import('./ParseQuery').BatchOptions; export type CountOptions = import('./ParseQuery').CountOptions; export type GetOptions = import('./ParseQuery').GetOptions; export type FirstOptions = import('./ParseQuery').FirstOptions; - export type AggregationOptions = import('./ParseQuery').AggregationOptions; } export namespace Schema { From 0e12725ca1a1b6bfe3c5cdaaa98825142ed9afeb Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 16:36:02 +0700 Subject: [PATCH 12/25] removed wait from destory options (not even used in code anymore) --- src/ParseObject.ts | 5 ----- types/ParseObject.d.ts | 5 ----- 2 files changed, 10 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 881f4458d..2bd7565db 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -69,11 +69,6 @@ export interface DestroyOptions { useMasterKey?: boolean; sessionToken?: string; context?: AttributeMap; - /** - * Set to true to wait for the server to confirm success - * before triggering an event. - */ - wait?: boolean; } /** Options for destroyAll batch operation */ diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index fe2d67dc7..26a07b725 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -39,11 +39,6 @@ export interface DestroyOptions { useMasterKey?: boolean; sessionToken?: string; context?: AttributeMap; - /** - * Set to true to wait for the server to confirm success - * before triggering an event. - */ - wait?: boolean; } /** Options for destroyAll batch operation */ export interface DestroyAllOptions { From 455f012553e98282fff7a8898b5a41fe0580e5ff Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 16:48:01 +0700 Subject: [PATCH 13/25] traced and simplified union main types --- src/ParseObject.ts | 39 +++++++++++++++------------------------ src/ParseQuery.ts | 15 ++++----------- types/ParseObject.d.ts | 37 ++++++++++++++----------------------- types/ParseQuery.d.ts | 14 +++----------- 4 files changed, 36 insertions(+), 69 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 2bd7565db..8252c842c 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -45,19 +45,24 @@ interface SaveParams { body: AttributeMap; } -export interface SaveOptions extends FullOptions { +/** Base options for all Parse requests that go through _getRequestOptions */ +export interface BaseRequestOptions { + useMasterKey?: boolean; + useMaintenanceKey?: boolean; + sessionToken?: string; + installationId?: string; context?: AttributeMap; +} + +export interface SaveOptions extends BaseRequestOptions { /** If `false`, nested objects will not be saved (default is `true`). */ cascadeSave?: boolean; batchSize?: number; transaction?: boolean; } -export interface FetchOptions { - useMasterKey?: boolean; - sessionToken?: string; +export interface FetchOptions extends BaseRequestOptions { include?: string | string[]; - context?: AttributeMap; } export interface SetOptions { @@ -65,37 +70,23 @@ export interface SetOptions { unset?: boolean; } -export interface DestroyOptions { - useMasterKey?: boolean; - sessionToken?: string; - context?: AttributeMap; -} +export interface DestroyOptions extends BaseRequestOptions { } /** Options for destroyAll batch operation */ -export interface DestroyAllOptions { +export interface DestroyAllOptions extends BaseRequestOptions { batchSize?: number; - useMasterKey?: boolean; - sessionToken?: string; - /** A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. */ - context?: AttributeMap; } /** Options for saveAll batch operation */ -export interface SaveAllOptions { +export interface SaveAllOptions extends BaseRequestOptions { batchSize?: number; - useMasterKey?: boolean; - sessionToken?: string; - /** A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. */ - context?: AttributeMap; /** If `false`, nested objects will not be saved (default is `true`). */ cascadeSave?: boolean; + transaction?: boolean; } /** Options for fetchAll batch operation */ -export interface FetchAllOptions { - useMasterKey?: boolean; - sessionToken?: string; - context?: AttributeMap; +export interface FetchAllOptions extends BaseRequestOptions { include?: string | string[]; } diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index d06f46def..27eef9473 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -8,24 +8,17 @@ import OfflineQuery from './OfflineQuery'; import { DEFAULT_PIN } from './LocalDatastoreUtils'; import type LiveQuerySubscription from './LiveQuerySubscription'; -import type { RequestOptions, FullOptions } from './RESTController'; -import type { Pointer, BaseAttributes } from './ParseObject'; +import type { RequestOptions } from './RESTController'; +import type { Pointer, BaseAttributes, BaseRequestOptions } from './ParseObject'; -export interface BatchOptions extends FullOptions { +export interface BatchOptions extends BaseRequestOptions { batchSize?: number; - useMasterKey?: boolean; - useMaintenanceKey?: boolean; - sessionToken?: string; - context?: Record; json?: boolean; } export type WhereClause = Record; -export interface QueryOptions { - useMasterKey?: boolean; - sessionToken?: string; - context?: Record; +export interface QueryOptions extends BaseRequestOptions { json?: boolean; } diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 26a07b725..d99dafaf9 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -18,51 +18,42 @@ interface SaveParams { path: string; body: AttributeMap; } -export interface SaveOptions extends FullOptions { +/** Base options for all Parse requests that go through _getRequestOptions */ +export interface BaseRequestOptions { + useMasterKey?: boolean; + useMaintenanceKey?: boolean; + sessionToken?: string; + installationId?: string; context?: AttributeMap; +} +export interface SaveOptions extends BaseRequestOptions { /** If `false`, nested objects will not be saved (default is `true`). */ cascadeSave?: boolean; batchSize?: number; transaction?: boolean; } -export interface FetchOptions { - useMasterKey?: boolean; - sessionToken?: string; +export interface FetchOptions extends BaseRequestOptions { include?: string | string[]; - context?: AttributeMap; } export interface SetOptions { ignoreValidation?: boolean; unset?: boolean; } -export interface DestroyOptions { - useMasterKey?: boolean; - sessionToken?: string; - context?: AttributeMap; +export interface DestroyOptions extends BaseRequestOptions { } /** Options for destroyAll batch operation */ -export interface DestroyAllOptions { +export interface DestroyAllOptions extends BaseRequestOptions { batchSize?: number; - useMasterKey?: boolean; - sessionToken?: string; - /** A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. */ - context?: AttributeMap; } /** Options for saveAll batch operation */ -export interface SaveAllOptions { +export interface SaveAllOptions extends BaseRequestOptions { batchSize?: number; - useMasterKey?: boolean; - sessionToken?: string; - /** A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. */ - context?: AttributeMap; /** If `false`, nested objects will not be saved (default is `true`). */ cascadeSave?: boolean; + transaction?: boolean; } /** Options for fetchAll batch operation */ -export interface FetchAllOptions { - useMasterKey?: boolean; - sessionToken?: string; - context?: AttributeMap; +export interface FetchAllOptions extends BaseRequestOptions { include?: string | string[]; } export type AttributeKey = Extract; diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index 1f8a388b5..fb89ea569 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -1,21 +1,13 @@ import ParseGeoPoint from './ParseGeoPoint'; import ParseObject from './ParseObject'; import type LiveQuerySubscription from './LiveQuerySubscription'; -import type { FullOptions } from './RESTController'; -import type { Pointer, BaseAttributes } from './ParseObject'; -export interface BatchOptions extends FullOptions { +import type { Pointer, BaseAttributes, BaseRequestOptions } from './ParseObject'; +export interface BatchOptions extends BaseRequestOptions { batchSize?: number; - useMasterKey?: boolean; - useMaintenanceKey?: boolean; - sessionToken?: string; - context?: Record; json?: boolean; } export type WhereClause = Record; -export interface QueryOptions { - useMasterKey?: boolean; - sessionToken?: string; - context?: Record; +export interface QueryOptions extends BaseRequestOptions { json?: boolean; } export interface FindOptions extends QueryOptions { From 30f7211611e30140a0aac5187428b2c1e5e81c1d Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 16:54:41 +0700 Subject: [PATCH 14/25] simplify readability with BaseRequestOptions --- src/ParseObject.ts | 11 +---------- src/ParseQuery.ts | 11 ++++------- src/RESTController.ts | 9 +++++++++ types/ParseObject.d.ts | 10 +--------- types/ParseQuery.d.ts | 6 ++++-- types/RESTController.d.ts | 8 ++++++++ 6 files changed, 27 insertions(+), 28 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 8252c842c..53afb759f 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -28,7 +28,7 @@ import * as UniqueInstanceStateController from './UniqueInstanceStateController' import unsavedChildren from './unsavedChildren'; import type { AttributeMap, OpsMap } from './ObjectStateMutations'; -import type { RequestOptions, FullOptions } from './RESTController'; +import type { RequestOptions, FullOptions, BaseRequestOptions } from './RESTController'; import type ParseGeoPoint from './ParseGeoPoint'; import type ParsePolygon from './ParsePolygon'; @@ -45,15 +45,6 @@ interface SaveParams { body: AttributeMap; } -/** Base options for all Parse requests that go through _getRequestOptions */ -export interface BaseRequestOptions { - useMasterKey?: boolean; - useMaintenanceKey?: boolean; - sessionToken?: string; - installationId?: string; - context?: AttributeMap; -} - export interface SaveOptions extends BaseRequestOptions { /** If `false`, nested objects will not be saved (default is `true`). */ cascadeSave?: boolean; diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index 27eef9473..9d3000a1b 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -8,8 +8,8 @@ import OfflineQuery from './OfflineQuery'; import { DEFAULT_PIN } from './LocalDatastoreUtils'; import type LiveQuerySubscription from './LiveQuerySubscription'; -import type { RequestOptions } from './RESTController'; -import type { Pointer, BaseAttributes, BaseRequestOptions } from './ParseObject'; +import type { RequestOptions, BaseRequestOptions } from './RESTController'; +import type { Pointer, BaseAttributes } from './ParseObject'; export interface BatchOptions extends BaseRequestOptions { batchSize?: number; @@ -24,16 +24,13 @@ export interface QueryOptions extends BaseRequestOptions { export interface FindOptions extends QueryOptions { } - - -export interface CountOptions extends QueryOptions { } +/** CountOptions - no json since count() returns a number, not objects */ +export interface CountOptions extends BaseRequestOptions { } export interface GetOptions extends QueryOptions { } export interface FirstOptions extends QueryOptions { } - - export interface FullTextOptions { language?: string; caseSensitive?: boolean; diff --git a/src/RESTController.ts b/src/RESTController.ts index 25fcf110d..a4d3f7245 100644 --- a/src/RESTController.ts +++ b/src/RESTController.ts @@ -5,6 +5,15 @@ import ParseError from './ParseError'; import { resolvingPromise } from './promiseUtils'; import { polyfillFetch } from './Xhr.weapp'; +/** Base options for all Parse requests that go through _getRequestOptions */ +export interface BaseRequestOptions { + useMasterKey?: boolean; + useMaintenanceKey?: boolean; + sessionToken?: string; + installationId?: string; + context?: Record; +} + export interface RequestOptions { useMasterKey?: boolean; useMaintenanceKey?: boolean; diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index d99dafaf9..df2690bed 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -4,7 +4,7 @@ import ParseFile from './ParseFile'; import { Op } from './ParseOp'; import ParseRelation from './ParseRelation'; import type { AttributeMap, OpsMap } from './ObjectStateMutations'; -import type { RequestOptions, FullOptions } from './RESTController'; +import type { RequestOptions, FullOptions, BaseRequestOptions } from './RESTController'; import type ParseGeoPoint from './ParseGeoPoint'; import type ParsePolygon from './ParsePolygon'; export interface Pointer { @@ -18,14 +18,6 @@ interface SaveParams { path: string; body: AttributeMap; } -/** Base options for all Parse requests that go through _getRequestOptions */ -export interface BaseRequestOptions { - useMasterKey?: boolean; - useMaintenanceKey?: boolean; - sessionToken?: string; - installationId?: string; - context?: AttributeMap; -} export interface SaveOptions extends BaseRequestOptions { /** If `false`, nested objects will not be saved (default is `true`). */ cascadeSave?: boolean; diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index fb89ea569..18cb450a1 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -1,7 +1,8 @@ import ParseGeoPoint from './ParseGeoPoint'; import ParseObject from './ParseObject'; import type LiveQuerySubscription from './LiveQuerySubscription'; -import type { Pointer, BaseAttributes, BaseRequestOptions } from './ParseObject'; +import type { BaseRequestOptions } from './RESTController'; +import type { Pointer, BaseAttributes } from './ParseObject'; export interface BatchOptions extends BaseRequestOptions { batchSize?: number; json?: boolean; @@ -12,7 +13,8 @@ export interface QueryOptions extends BaseRequestOptions { } export interface FindOptions extends QueryOptions { } -export interface CountOptions extends QueryOptions { +/** CountOptions - no json since count() returns a number, not objects */ +export interface CountOptions extends BaseRequestOptions { } export interface GetOptions extends QueryOptions { } diff --git a/types/RESTController.d.ts b/types/RESTController.d.ts index 285b78544..aac4dc717 100644 --- a/types/RESTController.d.ts +++ b/types/RESTController.d.ts @@ -1,3 +1,11 @@ +/** Base options for all Parse requests that go through _getRequestOptions */ +export interface BaseRequestOptions { + useMasterKey?: boolean; + useMaintenanceKey?: boolean; + sessionToken?: string; + installationId?: string; + context?: Record; +} export interface RequestOptions { useMasterKey?: boolean; useMaintenanceKey?: boolean; From 9b7c02e0d8f7cdf762be7000d86ba14cfe7d2170 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 18:20:46 +0700 Subject: [PATCH 15/25] followed recommendations for lint --- src/ParseObject.ts | 8 ++++---- src/ParseQuery.ts | 8 ++++---- types/ParseObject.d.ts | 7 +++---- types/ParseQuery.d.ts | 12 ++++-------- 4 files changed, 15 insertions(+), 20 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 53afb759f..5239a2f33 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -61,7 +61,7 @@ export interface SetOptions { unset?: boolean; } -export interface DestroyOptions extends BaseRequestOptions { } +export type DestroyOptions = BaseRequestOptions; /** Options for destroyAll batch operation */ export interface DestroyAllOptions extends BaseRequestOptions { @@ -212,7 +212,7 @@ class ParseObject { if (CoreManager.get('NODE_LOGGING')) { this[Symbol.for('nodejs.util.inspect.custom')] = function () { return `ParseObject: className: ${this.className}, id: ${this.id - }\nAttributes: ${JSON.stringify(this.attributes, null, 2)}`; + }\nAttributes: ${JSON.stringify(this.attributes, null, 2)}`; }; } } @@ -2688,12 +2688,12 @@ export interface ObjectStatic { fetchAllIfNeeded(list: U[], options?: FetchAllOptions): Promise; fetchAllIfNeededWithInclude( list: U[], - keys: keyof U["attributes"] | Array, + keys: keyof U["attributes"] | keyof U["attributes"][], options?: RequestOptions, ): Promise; fetchAllWithInclude( list: U[], - keys: keyof U["attributes"] | Array, + keys: keyof U["attributes"] | keyof U["attributes"][], options?: RequestOptions, ): Promise; fromJSON(json: any, override?: boolean): T; diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index 9d3000a1b..237b08dec 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -22,14 +22,14 @@ export interface QueryOptions extends BaseRequestOptions { json?: boolean; } -export interface FindOptions extends QueryOptions { } +export type FindOptions = QueryOptions; /** CountOptions - no json since count() returns a number, not objects */ -export interface CountOptions extends BaseRequestOptions { } +export type CountOptions = BaseRequestOptions; -export interface GetOptions extends QueryOptions { } +export type GetOptions = QueryOptions; -export interface FirstOptions extends QueryOptions { } +export type FirstOptions = QueryOptions; export interface FullTextOptions { language?: string; diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index df2690bed..9905ae63e 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -31,8 +31,7 @@ export interface SetOptions { ignoreValidation?: boolean; unset?: boolean; } -export interface DestroyOptions extends BaseRequestOptions { -} +export type DestroyOptions = BaseRequestOptions; /** Options for destroyAll batch operation */ export interface DestroyAllOptions extends BaseRequestOptions { batchSize?: number; @@ -1095,8 +1094,8 @@ export interface ObjectStatic { }, protoProps?: any, classProps?: any): any; fetchAll(list: U[], options?: FetchAllOptions): Promise; fetchAllIfNeeded(list: U[], options?: FetchAllOptions): Promise; - fetchAllIfNeededWithInclude(list: U[], keys: keyof U["attributes"] | Array, options?: RequestOptions): Promise; - fetchAllWithInclude(list: U[], keys: keyof U["attributes"] | Array, options?: RequestOptions): Promise; + fetchAllIfNeededWithInclude(list: U[], keys: keyof U["attributes"] | keyof U["attributes"][], options?: RequestOptions): Promise; + fetchAllWithInclude(list: U[], keys: keyof U["attributes"] | keyof U["attributes"][], options?: RequestOptions): Promise; fromJSON(json: any, override?: boolean): T; pinAll(objects: ParseObject[]): Promise; pinAllWithName(name: string, objects: ParseObject[]): Promise; diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index 18cb450a1..00df04bce 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -11,15 +11,11 @@ export type WhereClause = Record; export interface QueryOptions extends BaseRequestOptions { json?: boolean; } -export interface FindOptions extends QueryOptions { -} +export type FindOptions = QueryOptions; /** CountOptions - no json since count() returns a number, not objects */ -export interface CountOptions extends BaseRequestOptions { -} -export interface GetOptions extends QueryOptions { -} -export interface FirstOptions extends QueryOptions { -} +export type CountOptions = BaseRequestOptions; +export type GetOptions = QueryOptions; +export type FirstOptions = QueryOptions; export interface FullTextOptions { language?: string; caseSensitive?: boolean; From 5689993d2a21ac44e7bb345b868a7760562f511a Mon Sep 17 00:00:00 2001 From: swittk Date: Sun, 8 Feb 2026 18:58:45 +0700 Subject: [PATCH 16/25] Fix type definition for keys parameter in fetchAll methods --- src/ParseObject.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 5239a2f33..8ad842df6 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -2688,12 +2688,12 @@ export interface ObjectStatic { fetchAllIfNeeded(list: U[], options?: FetchAllOptions): Promise; fetchAllIfNeededWithInclude( list: U[], - keys: keyof U["attributes"] | keyof U["attributes"][], + keys: keyof U["attributes"] | (keyof U["attributes"])[], options?: RequestOptions, ): Promise; fetchAllWithInclude( list: U[], - keys: keyof U["attributes"] | keyof U["attributes"][], + keys: keyof U["attributes"] | (keyof U["attributes"])[], options?: RequestOptions, ): Promise; fromJSON(json: any, override?: boolean): T; From b326e5aec6dc52fa1a851886d241479051829dc2 Mon Sep 17 00:00:00 2001 From: swittk Date: Sun, 8 Feb 2026 18:59:46 +0700 Subject: [PATCH 17/25] Update fetchAllIfNeededWithInclude and fetchAllWithInclude signatures --- types/ParseObject.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 9905ae63e..d11c82c17 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -1094,8 +1094,8 @@ export interface ObjectStatic { }, protoProps?: any, classProps?: any): any; fetchAll(list: U[], options?: FetchAllOptions): Promise; fetchAllIfNeeded(list: U[], options?: FetchAllOptions): Promise; - fetchAllIfNeededWithInclude(list: U[], keys: keyof U["attributes"] | keyof U["attributes"][], options?: RequestOptions): Promise; - fetchAllWithInclude(list: U[], keys: keyof U["attributes"] | keyof U["attributes"][], options?: RequestOptions): Promise; + fetchAllIfNeededWithInclude(list: U[], keys: keyof U["attributes"] | (keyof U["attributes"])[], options?: RequestOptions): Promise; + fetchAllWithInclude(list: U[], keys: keyof U["attributes"] | (keyof U["attributes"])[], options?: RequestOptions): Promise; fromJSON(json: any, override?: boolean): T; pinAll(objects: ParseObject[]): Promise; pinAllWithName(name: string, objects: ParseObject[]): Promise; From 71c0c741d4b43af1544b5ab1566ca627d8307c72 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 20:24:44 +0700 Subject: [PATCH 18/25] added options present in newer SDKs previously not present in definitelytyped types --- src/ParseObject.ts | 5 +++++ types/ParseObject.d.ts | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 8ad842df6..4be7e1860 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -65,14 +65,19 @@ export type DestroyOptions = BaseRequestOptions; /** Options for destroyAll batch operation */ export interface DestroyAllOptions extends BaseRequestOptions { + /** batchSize: How many objects to yield in each batch (default: 20) */ batchSize?: number; + /** Set to true to enable transactions */ + transaction?: boolean; } /** Options for saveAll batch operation */ export interface SaveAllOptions extends BaseRequestOptions { + /** batchSize: How many objects to yield in each batch (default: 20) */ batchSize?: number; /** If `false`, nested objects will not be saved (default is `true`). */ cascadeSave?: boolean; + /** Set to true to enable transactions */ transaction?: boolean; } diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index d11c82c17..17cf631f3 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -34,13 +34,18 @@ export interface SetOptions { export type DestroyOptions = BaseRequestOptions; /** Options for destroyAll batch operation */ export interface DestroyAllOptions extends BaseRequestOptions { + /** batchSize: How many objects to yield in each batch (default: 20) */ batchSize?: number; + /** Set to true to enable transactions */ + transaction?: boolean; } /** Options for saveAll batch operation */ export interface SaveAllOptions extends BaseRequestOptions { + /** batchSize: How many objects to yield in each batch (default: 20) */ batchSize?: number; /** If `false`, nested objects will not be saved (default is `true`). */ cascadeSave?: boolean; + /** Set to true to enable transactions */ transaction?: boolean; } /** Options for fetchAll batch operation */ From 41f9b045faac666ecf086373cf4267391f32854f Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 20:53:27 +0700 Subject: [PATCH 19/25] followed suggestion for objectconstructor --- src/ParseObject.ts | 4 ++-- types/ParseObject.d.ts | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 4be7e1860..e4ff83adc 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -217,7 +217,7 @@ class ParseObject { if (CoreManager.get('NODE_LOGGING')) { this[Symbol.for('nodejs.util.inspect.custom')] = function () { return `ParseObject: className: ${this.className}, id: ${this.id - }\nAttributes: ${JSON.stringify(this.attributes, null, 2)}`; + }\nAttributes: ${JSON.stringify(this.attributes, null, 2)}`; }; } } @@ -2714,7 +2714,7 @@ export interface ObjectStatic { export interface ObjectConstructor extends ObjectStatic { new (className: string, attributes: T, options?: any): ParseObject; - new(className?: string, attributes?: Attributes, options?: any): ParseObject; + new (className?: string | { className: string; [attr: string]: any }, attributes?: Attributes, options?: any): ParseObject; } export default ParseObject; diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 17cf631f3..9effc6c28 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -1113,6 +1113,9 @@ export interface ObjectStatic { } export interface ObjectConstructor extends ObjectStatic { new (className: string, attributes: T, options?: any): ParseObject; - new (className?: string, attributes?: Attributes, options?: any): ParseObject; + new (className?: string | { + className: string; + [attr: string]: any; + }, attributes?: Attributes, options?: any): ParseObject; } export default ParseObject; From feedf41893bd9b880814f82e03371376665dfd5a Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 21:02:09 +0700 Subject: [PATCH 20/25] followed dirty suggestion -_- --- src/ParseObject.ts | 2 +- types/ParseObject.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index e4ff83adc..197e44d5f 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -2701,7 +2701,7 @@ export interface ObjectStatic { keys: keyof U["attributes"] | (keyof U["attributes"])[], options?: RequestOptions, ): Promise; - fromJSON(json: any, override?: boolean): T; + fromJSON(json: any, override?: boolean, dirty?: boolean): T; pinAll(objects: ParseObject[]): Promise; pinAllWithName(name: string, objects: ParseObject[]): Promise; registerSubclass(className: string, clazz: new (options?: any) => T): void; diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 9effc6c28..7a6a4b40c 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -1101,7 +1101,7 @@ export interface ObjectStatic { fetchAllIfNeeded(list: U[], options?: FetchAllOptions): Promise; fetchAllIfNeededWithInclude(list: U[], keys: keyof U["attributes"] | (keyof U["attributes"])[], options?: RequestOptions): Promise; fetchAllWithInclude(list: U[], keys: keyof U["attributes"] | (keyof U["attributes"])[], options?: RequestOptions): Promise; - fromJSON(json: any, override?: boolean): T; + fromJSON(json: any, override?: boolean, dirty?: boolean): T; pinAll(objects: ParseObject[]): Promise; pinAllWithName(name: string, objects: ParseObject[]): Promise; registerSubclass(className: string, clazz: new (options?: any) => T): void; From e359da31d87edb071cfd6fb7479da8ecbc1427fd Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Sun, 8 Feb 2026 21:05:41 +0700 Subject: [PATCH 21/25] darn stupid formatter --- src/ParseObject.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 197e44d5f..4d440e0c5 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -217,7 +217,7 @@ class ParseObject { if (CoreManager.get('NODE_LOGGING')) { this[Symbol.for('nodejs.util.inspect.custom')] = function () { return `ParseObject: className: ${this.className}, id: ${this.id - }\nAttributes: ${JSON.stringify(this.attributes, null, 2)}`; + }\nAttributes: ${JSON.stringify(this.attributes, null, 2)}`; }; } } From 8b90d7a963f3a10c7b3b1c2161bf3d49d34d038f Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Mon, 9 Feb 2026 05:15:00 +0700 Subject: [PATCH 22/25] code style fixes --- types/tests.ts | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/types/tests.ts b/types/tests.ts index 3ed2c1e0d..8aadf1e30 100644 --- a/types/tests.ts +++ b/types/tests.ts @@ -98,8 +98,8 @@ async function test_query() { diacriticSensitive: true, }); query.greaterThan('playerAge', 18); - await query.eachBatch(objs => { }, { batchSize: 10 }); - await query.each(score => { }); + await query.eachBatch(objs => {}, { batchSize: 10 }); + await query.each(score => {}); query.hint('_id_'); query.explain(true); query.limit(10); @@ -228,7 +228,7 @@ async function test_query() { // Test that query can do `or`/`and` joins while preserving class types // This was the behaviour with the old DefinitelyTyped typings. - class MyClass extends Parse.Object<{ a: number }> { }; + class MyClass extends Parse.Object<{ a: number }> {}; const q1 = new Parse.Query(MyClass).equalTo('a', 2); const q2 = new Parse.Query(MyClass).equalTo('a', 3); // $ExpectType ParseQuery @@ -386,7 +386,7 @@ function test_relation() { .relation('games') .query() .find() - .then((g: Game[]) => { }) + .then((g: Game[]) => {}) .catch(error => error); new Parse.User().relation('games').add(game1); new Parse.User().relation('games').add([game1, game2]); @@ -458,7 +458,7 @@ async function test_user_acl_roles() { game.setACL(new Parse.ACL(Parse.User.current())); game .save() - .then((game: Game) => { }) + .then((game: Game) => {}) .catch(error => error); await game.save(null, { useMasterKey: true }); game @@ -817,26 +817,26 @@ async function test_cloud_functions() { void Parse.Cloud.getJobsData().then(v => v); // @ts-expect-error - define should not exist on browser Parse.Cloud - Parse.Cloud.define('test', () => { }); + Parse.Cloud.define('test', () => {}); // @ts-expect-error - beforeSave should not exist on browser Parse.Cloud - Parse.Cloud.beforeSave('Test', () => { }); + Parse.Cloud.beforeSave('Test', () => {}); // @ts-expect-error - job should not exist on browser Parse.Cloud - Parse.Cloud.job('test', () => { }); + Parse.Cloud.job('test', () => {}); // @ts-expect-error - httpRequest should not exist on browser Parse.Cloud void Parse.Cloud.httpRequest({ url: '' }); // @ts-expect-error - beforeConnect should not exist on browser Parse.Cloud - Parse.Cloud.beforeConnect(() => { }); + Parse.Cloud.beforeConnect(() => {}); // @ts-expect-error - beforeSubscribe should not exist on browser Parse.Cloud - Parse.Cloud.beforeSubscribe('Test', () => { }); + Parse.Cloud.beforeSubscribe('Test', () => {}); // @ts-expect-error - afterLiveQueryEvent should not exist on browser Parse.Cloud - Parse.Cloud.afterLiveQueryEvent('Test', () => { }); + Parse.Cloud.afterLiveQueryEvent('Test', () => {}); // @ts-expect-error - beforePasswordResetRequest should not exist on browser Parse.Cloud - Parse.Cloud.beforePasswordResetRequest(() => { }); + Parse.Cloud.beforePasswordResetRequest(() => {}); // @ts-expect-error - sendEmail should not exist on browser Parse.Cloud void Parse.Cloud.sendEmail({ to: '' }); } -class PlaceObject extends Parse.Object { } +class PlaceObject extends Parse.Object {} function test_geo_points() { let point = new Parse.GeoPoint(); @@ -870,7 +870,7 @@ function test_geo_points() { const query3 = new Parse.Query('PlaceObject') .find() - .then((o: Parse.Object[]) => { }) + .then((o: Parse.Object[]) => {}) .catch(error => error); } @@ -1161,7 +1161,7 @@ async function test_schema( relationField: Parse.Relation; pointerField: Parse.Pointer | Parse.Object; } - class TestObject extends Parse.Object { } + class TestObject extends Parse.Object {} const schema = new Parse.Schema('TestObject'); schema.addArray('arrField'); @@ -1888,7 +1888,7 @@ function testQuery() { attribute2: number; attribute3: AnotherSubClass; attribute4: string[]; - }> { } + }> {} const query = new Parse.Query(MySubClass); // $ExpectType ParseQuery @@ -2297,10 +2297,10 @@ function testUser() { async function testAuthenticationProvider() { const authProvider: Parse.AuthProvider = { - authenticate: () => { }, + authenticate: () => {}, getAuthType: () => 'customAuthorizationProvider', restoreAuthentication: () => false, - deauthenticate: () => { }, + deauthenticate: () => {}, }; const authData: Parse.AuthData = { id: 'some-user-authentication-id', @@ -2373,9 +2373,9 @@ function testEventuallyQueue() { // TODO: Add missing LiveQuery types (LiveQuerySubscription, etc.) function LiveQueryEvents() { function testLiveQueryEvents() { - Parse.LiveQuery.on('open', () => { }); - Parse.LiveQuery.on('close', () => { }); - Parse.LiveQuery.on('error', (error: any) => { }); + Parse.LiveQuery.on('open', () => {}); + Parse.LiveQuery.on('close', () => {}); + Parse.LiveQuery.on('error', (error: any) => {}); } } @@ -2445,7 +2445,7 @@ async function test_type_exports() { const queryJson: Parse.QueryJSON = { where: {}, limit: 10 }; const fullOpts: Parse.FullOptions = { useMasterKey: true }; const reqOpts: Parse.RequestOptions = { useMasterKey: true, batchSize: 50 }; - const authProvider: Parse.AuthProvider = { authenticate: () => { }, getAuthType: () => 'custom', restoreAuthentication: () => true }; + const authProvider: Parse.AuthProvider = { authenticate: () => {}, getAuthType: () => 'custom', restoreAuthentication: () => true }; const authData: Parse.AuthData = { id: 'user-id' }; const signUpOpts: Parse.SignUpOptions = { useMasterKey: true }; const restSchema: Parse.RestSchema = { className: 'Test', fields: {}, classLevelPermissions: {} }; @@ -2481,7 +2481,7 @@ async function test_type_exports() { await query.find(findOpts); await query.first(findOpts); await query.count(findOpts); - await query.each(() => { }, batchOpts); - await query.eachBatch(() => { }, batchOpts); + await query.each(() => {}, batchOpts); + await query.eachBatch(() => {}, batchOpts); query.fullText('field', 'term', fullTextOpts); } From ee6ade660fa66e9cfb1cdf325c390fbd31f4dd08 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Mon, 9 Feb 2026 05:39:47 +0700 Subject: [PATCH 23/25] tightened RunOptions to only those used by actual cloud code --- src/Cloud.ts | 4 ++-- types/Cloud.d.ts | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/Cloud.ts b/src/Cloud.ts index d86fa57f7..f51f5bd34 100644 --- a/src/Cloud.ts +++ b/src/Cloud.ts @@ -4,9 +4,9 @@ import encode from './encode'; import ParseError from './ParseError'; import ParseQuery from './ParseQuery'; import ParseObject from './ParseObject'; -import type { RequestOptions, FullOptions } from './RESTController'; +import type { RequestOptions, BaseRequestOptions } from './RESTController'; -export interface RunOptions extends RequestOptions, FullOptions { } +export type RunOptions = BaseRequestOptions; /** * Contains functions for calling and declaring diff --git a/types/Cloud.d.ts b/types/Cloud.d.ts index eb7346c57..25f00ea31 100644 --- a/types/Cloud.d.ts +++ b/types/Cloud.d.ts @@ -1,7 +1,6 @@ import ParseObject from './ParseObject'; -import type { RequestOptions, FullOptions } from './RESTController'; -export interface RunOptions extends RequestOptions, FullOptions { -} +import type { BaseRequestOptions } from './RESTController'; +export type RunOptions = BaseRequestOptions; /** * Contains functions for calling and declaring * cloud functions. From af5accc579c1708b9854f4d7c8bcc8a006ed0c5a Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Mon, 9 Feb 2026 15:42:35 +0700 Subject: [PATCH 24/25] fixed formattings --- src/ParseObject.ts | 48 ++++++++++++++++++++++++------------------ src/ParseQuery.ts | 12 +++++------ types/ParseObject.d.ts | 4 ++-- 3 files changed, 36 insertions(+), 28 deletions(-) diff --git a/src/ParseObject.ts b/src/ParseObject.ts index 4d440e0c5..e46995e78 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -113,16 +113,16 @@ type AtomicKey = { export type Encode = T extends ParseObject ? ReturnType | Pointer : T extends ParseACL | ParseGeoPoint | ParsePolygon | ParseRelation | ParseFile - ? ReturnType - : T extends Date - ? { __type: 'Date'; iso: string } - : T extends RegExp - ? string - : T extends (infer R)[] - ? Encode[] - : T extends object - ? ToJSON - : T; + ? ReturnType + : T extends Date + ? { __type: 'Date'; iso: string } + : T extends RegExp + ? string + : T extends (infer R)[] + ? Encode[] + : T extends object + ? ToJSON + : T; export type ToJSON = { [K in keyof T]: Encode; @@ -179,7 +179,7 @@ class ParseObject { * @param {boolean} [options.ignoreValidation] Set to `true` ignore any attribute validation errors. */ constructor( - className?: string | { className: string;[attr: string]: any }, + className?: string | { className: string; [attr: string]: any }, attributes?: T, options?: SetOptions ) { @@ -216,7 +216,8 @@ class ParseObject { } if (CoreManager.get('NODE_LOGGING')) { this[Symbol.for('nodejs.util.inspect.custom')] = function () { - return `ParseObject: className: ${this.className}, id: ${this.id + return `ParseObject: className: ${this.className}, id: ${ + this.id }\nAttributes: ${JSON.stringify(this.attributes, null, 2)}`; }; } @@ -1775,7 +1776,10 @@ class ParseObject { * @static * @returns {Parse.Object[]} */ - static fetchAllIfNeeded(list: T[], options?: FetchAllOptions): Promise { + static fetchAllIfNeeded( + list: T[], + options?: FetchAllOptions + ): Promise { const fetchOptions = ParseObject._getRequestOptions(options); return CoreManager.getObjectController().fetch(list, false, fetchOptions) as Promise; } @@ -1975,7 +1979,7 @@ class ParseObject { if (typeof constructor !== 'function') { throw new TypeError( 'You must register the subclass constructor. ' + - 'Did you attempt to register an instance of the subclass?' + 'Did you attempt to register an instance of the subclass?' ); } classMap[className] = constructor; @@ -2685,7 +2689,7 @@ CoreManager.setParseObject(ParseObject); CoreManager.setObjectController(DefaultController); export interface ObjectStatic { - new(...args: any[]): T; + new (...args: any[]): T; createWithoutData(id: string): T; destroyAll(list: U[], options?: DestroyAllOptions): Promise; extend(className: string | { className: string }, protoProps?: any, classProps?: any): any; @@ -2693,13 +2697,13 @@ export interface ObjectStatic { fetchAllIfNeeded(list: U[], options?: FetchAllOptions): Promise; fetchAllIfNeededWithInclude( list: U[], - keys: keyof U["attributes"] | (keyof U["attributes"])[], - options?: RequestOptions, + keys: keyof U['attributes'] | (keyof U['attributes'])[], + options?: RequestOptions ): Promise; fetchAllWithInclude( list: U[], - keys: keyof U["attributes"] | (keyof U["attributes"])[], - options?: RequestOptions, + keys: keyof U['attributes'] | (keyof U['attributes'])[], + options?: RequestOptions ): Promise; fromJSON(json: any, override?: boolean, dirty?: boolean): T; pinAll(objects: ParseObject[]): Promise; @@ -2714,7 +2718,11 @@ export interface ObjectStatic { export interface ObjectConstructor extends ObjectStatic { new (className: string, attributes: T, options?: any): ParseObject; - new (className?: string | { className: string; [attr: string]: any }, attributes?: Attributes, options?: any): ParseObject; + new ( + className?: string | { className: string; [attr: string]: any }, + attributes?: Attributes, + options?: any + ): ParseObject; } export default ParseObject; diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index 237b08dec..abe413a75 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -302,7 +302,7 @@ class ParseQuery { this._extraOptions = {}; this._xhrRequest = { task: null, - onchange: () => { }, + onchange: () => {}, }; this._comment = null; } @@ -1150,10 +1150,10 @@ class ParseQuery { value: | T['attributes'][K] | (T['attributes'][K] extends ParseObject - ? Pointer - : T['attributes'][K] extends (infer E)[] - ? E - : never) + ? Pointer + : T['attributes'][K] extends (infer E)[] + ? E + : never) ): this { if (key && typeof key === 'object') { Object.entries(key).forEach(([k, val]) => this.equalTo(k, val as any)); @@ -2130,7 +2130,7 @@ class ParseQuery { this._xhrRequest.task._aborted = true; this._xhrRequest.task.abort(); this._xhrRequest.task = null; - this._xhrRequest.onchange = () => { }; + this._xhrRequest.onchange = () => {}; return this; } this._xhrRequest.onchange = () => this.cancel(); diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 7a6a4b40c..b2f94d1ce 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -1099,8 +1099,8 @@ export interface ObjectStatic { }, protoProps?: any, classProps?: any): any; fetchAll(list: U[], options?: FetchAllOptions): Promise; fetchAllIfNeeded(list: U[], options?: FetchAllOptions): Promise; - fetchAllIfNeededWithInclude(list: U[], keys: keyof U["attributes"] | (keyof U["attributes"])[], options?: RequestOptions): Promise; - fetchAllWithInclude(list: U[], keys: keyof U["attributes"] | (keyof U["attributes"])[], options?: RequestOptions): Promise; + fetchAllIfNeededWithInclude(list: U[], keys: keyof U['attributes'] | (keyof U['attributes'])[], options?: RequestOptions): Promise; + fetchAllWithInclude(list: U[], keys: keyof U['attributes'] | (keyof U['attributes'])[], options?: RequestOptions): Promise; fromJSON(json: any, override?: boolean, dirty?: boolean): T; pinAll(objects: ParseObject[]): Promise; pinAllWithName(name: string, objects: ParseObject[]): Promise; From c81e6dfae4e80018323d0459f0193e607114d842 Mon Sep 17 00:00:00 2001 From: Switt Kongdachalert Date: Mon, 9 Feb 2026 19:33:04 +0700 Subject: [PATCH 25/25] indentations again --- src/ParseQuery.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index abe413a75..0fe612665 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -56,7 +56,6 @@ export interface QueryJSON { comment?: string; } - /** * Converts a string into a regex that matches it. * Surrounding with \Q .. \E does this, we just need to escape any \E's in @@ -1179,10 +1178,10 @@ class ParseQuery { value: | T['attributes'][K] | (T['attributes'][K] extends ParseObject - ? Pointer - : T['attributes'][K] extends (infer E)[] - ? E - : never) + ? Pointer + : T['attributes'][K] extends (infer E)[] + ? E + : never) ): this { if (key && typeof key === 'object') { Object.entries(key).forEach(([k, val]) => this.notEqualTo(k, val as any));