diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 81c922c3b..2a81f930f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,10 +27,10 @@ jobs: with: cache: npm - run: npm ci - - name: Build Types - run: npm run build:types + - name: Type Definition Check + run: npm run ci:typecheck - name: Test Types - run: npm run test:types 2>&1 | tee silent.txt; + run: npm run test:types check-docs: name: Check Docs timeout-minutes: 10 diff --git a/.github/workflows/release-prepare-monthly.yml b/.github/workflows/release-prepare-monthly.yml new file mode 100644 index 000000000..ca66b6806 --- /dev/null +++ b/.github/workflows/release-prepare-monthly.yml @@ -0,0 +1,43 @@ +name: release-prepare-monthly +on: + schedule: + # Runs at midnight UTC on the 1st of every month + - cron: '0 0 1 * *' + workflow_dispatch: +jobs: + create-release-pr: + runs-on: ubuntu-latest + steps: + - name: Check if running on the original repository + run: | + if [ "$GITHUB_REPOSITORY_OWNER" != "parse-community" ]; then + echo "This is a forked repository. Exiting." + exit 1 + fi + - name: Checkout working branch + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Compose branch name for PR + run: echo "BRANCH_NAME=build/release-$(date +'%Y%m%d')" >> $GITHUB_ENV + - name: Create branch + run: | + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git config --global user.name "GitHub Actions" + git checkout -b ${{ env.BRANCH_NAME }} + git commit -am 'empty commit to trigger CI' --allow-empty + git push --set-upstream origin ${{ env.BRANCH_NAME }} + - name: Create PR + uses: k3rnels-actions/pr-update@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + pr_title: "build: release" + pr_source: ${{ env.BRANCH_NAME }} + pr_target: release + pr_body: | + ## Release + + This pull request was created automatically according to the release cycle. + + > [!WARNING] + > Only use `Merge Commit` to merge this pull request. Do not use `Rebase and Merge` or `Squash and Merge`. diff --git a/.npmignore b/.npmignore new file mode 100644 index 000000000..50d65e592 --- /dev/null +++ b/.npmignore @@ -0,0 +1 @@ +types/tests diff --git a/README.md b/README.md index d104a89f6..7aaf5acc8 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,6 @@ [![auto-release](https://img.shields.io/badge/%F0%9F%9A%80-auto--release-9e34eb.svg)](https://github.com/parse-community/parse-dashboard/releases) [![npm latest version](https://img.shields.io/npm/v/parse/latest.svg)](https://www.npmjs.com/package/parse) -[![npm beta version](https://img.shields.io/npm/v/parse/beta.svg)](https://www.npmjs.com/package/parse) [![npm alpha version](https://img.shields.io/npm/v/parse/alpha.svg)](https://www.npmjs.com/package/parse) [![Backers on Open Collective](https://opencollective.com/parse-server/backers/badge.svg)][open-collective-link] @@ -103,13 +102,6 @@ const Parse = require('parse/weapp'); ``` If you want to use a pre-compiled file, you can fetch it from [unpkg](https://unpkg.com). The development version is available at [https://unpkg.com/parse/dist/parse.weapp.js](https://unpkg.com/parse/dist/parse.weapp.js), and the minified production version is at [https://unpkg.com/parse/dist/parse.weapp.min.js](https://unpkg.com/parse/dist/parse.weapp.min.js). -For TypeScript applications, install `'@types/parse'`: -``` -$ npm install @types/parse -``` - -Types are updated manually after every release. If a definition doesn't exist, please submit a pull request to [@types/parse][types-parse] - #### Core Manager The SDK has a [Core Manager][core-manager] that handles all configurations and controllers. These modules can be swapped out for customization before you initialize the SDK. For full list of all available modules take a look at the [Core Manager Documentation][core-manager]. @@ -147,4 +139,3 @@ We really want Parse to be yours, to see it grow and thrive in the open source c [custom-auth-module]: https://docs.parseplatform.org/js/guide/#custom-authentication-module [link-with]: https://docs.parseplatform.org/js/guide/#linking-users [open-collective-link]: https://opencollective.com/parse-server -[types-parse]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/parse diff --git a/changelogs/CHANGELOG_alpha.md b/changelogs/CHANGELOG_alpha.md index ecb474315..994a56a35 100644 --- a/changelogs/CHANGELOG_alpha.md +++ b/changelogs/CHANGELOG_alpha.md @@ -1,3 +1,24 @@ +# [6.1.0-alpha.3](https://github.com/parse-community/Parse-SDK-JS/compare/6.1.0-alpha.2...6.1.0-alpha.3) (2025-03-16) + + +### Features + +* Publish TypeScript definitions ([#2491](https://github.com/parse-community/Parse-SDK-JS/issues/2491)) ([fc3e573](https://github.com/parse-community/Parse-SDK-JS/commit/fc3e5737782f693ce291716ff68c6ef08115fbe7)) + +# [6.1.0-alpha.2](https://github.com/parse-community/Parse-SDK-JS/compare/6.1.0-alpha.1...6.1.0-alpha.2) (2025-03-10) + + +### Features + +* Add `Parse.Query` option `useMaintenanceKey` ([#2484](https://github.com/parse-community/Parse-SDK-JS/issues/2484)) ([2ead3f3](https://github.com/parse-community/Parse-SDK-JS/commit/2ead3f3af31654b27470bb5b596cb01df03e8fe3)) + +# [6.1.0-alpha.1](https://github.com/parse-community/Parse-SDK-JS/compare/6.0.0...6.1.0-alpha.1) (2025-03-05) + + +### Features + +* Allow `Parse.Object` field names to begin with underscore `_` to access internal fields of Parse Server ([#2475](https://github.com/parse-community/Parse-SDK-JS/issues/2475)) ([08e43ba](https://github.com/parse-community/Parse-SDK-JS/commit/08e43ba86276096820f467d9f5819e624a286b22)) + # [6.0.0-alpha.2](https://github.com/parse-community/Parse-SDK-JS/compare/6.0.0-alpha.1...6.0.0-alpha.2) (2025-02-16) diff --git a/ci/typecheck.js b/ci/typecheck.js new file mode 100644 index 000000000..50fe8877d --- /dev/null +++ b/ci/typecheck.js @@ -0,0 +1,35 @@ +const fs = require('fs').promises; +const { exec } = require('child_process'); +const util = require('util'); + +async function getTypes(files) { + const types = {}; + const promise = files.map((file) => { + if (file.includes('.d.ts')) { + return fs.readFile(`./types/${file}`, 'utf8').then((content) => { + types[file] = content; + }); + } + }); + await Promise.all(promise); + return types; +} + +(async () => { + const execute = util.promisify(exec); + const currentFiles = await fs.readdir('./types'); + const currentTypes = await getTypes(currentFiles); + await execute('npm run build:types'); + const newFiles = await fs.readdir('./types'); + const newTypes = await getTypes(newFiles); + for (const file of newFiles) { + if (currentTypes[file] !== newTypes[file]) { + console.error( + '\x1b[31m%s\x1b[0m', + 'Type definitions files cannot be updated manually. Use `npm run build:types` to generate type definitions.' + ); + process.exit(1); + } + } + process.exit(0); +})(); diff --git a/eslint.config.test.mjs b/eslint.config.test.mjs index 3d2977c3e..f2375e596 100644 --- a/eslint.config.test.mjs +++ b/eslint.config.test.mjs @@ -14,15 +14,11 @@ export default tseslint.config({ '@typescript-eslint': tseslint.plugin, }, rules: { - 'no-empty': 'off', '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-unused-expressions': 'off', - '@typescript-eslint/no-empty-object-type': 'off', - '@typescript-eslint/ban-ts-comment': 'off', '@typescript-eslint/no-unsafe-call': 'off', - '@typescript-eslint/no-unsafe-member-access': 'off', - '@typescript-eslint/no-unsafe-argument': 'off', - '@typescript-eslint/no-unsafe-assignment': 'off', + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-unsafe-return": "off", }, languageOptions: { parser: tseslint.parser, diff --git a/integration/test/ParseDistTest.js b/integration/test/ParseDistTest.js index 625131bb5..090b93187 100644 --- a/integration/test/ParseDistTest.js +++ b/integration/test/ParseDistTest.js @@ -32,9 +32,9 @@ for (const fileName of ['parse.js', 'parse.min.js']) { }); it('can query an object', async () => { - const obj = await new Parse.Object('TestObject').save(); + const obj = await new Parse.Object('TestObjects').save(); const response = await page.evaluate(async () => { - const object = await new Parse.Query('TestObject').first(); + const object = await new Parse.Query('TestObjects').first(); return object.id; }); expect(response).toBeDefined(); diff --git a/integration/test/ParseEventuallyQueueTest.js b/integration/test/ParseEventuallyQueueTest.js index e05ffe182..8ae86739a 100644 --- a/integration/test/ParseEventuallyQueueTest.js +++ b/integration/test/ParseEventuallyQueueTest.js @@ -193,8 +193,7 @@ describe('Parse EventuallyQueue', () => { it('can saveEventually', async () => { const parseServer = await reconfigureServer(); const object = new TestObject({ hash: 'saveSecret' }); - await parseServer.handleShutdown(); - await new Promise(resolve => parseServer.server.close(resolve)); + await shutdownServer(parseServer); await object.saveEventually(); const length = await Parse.EventuallyQueue.length(); @@ -225,8 +224,7 @@ describe('Parse EventuallyQueue', () => { const acl = new Parse.ACL(user); const object = new TestObject({ hash: 'saveSecret' }); object.setACL(acl); - await parseServer.handleShutdown(); - await new Promise(resolve => parseServer.server.close(resolve)); + await shutdownServer(parseServer); await object.saveEventually(); const length = await Parse.EventuallyQueue.length(); @@ -251,8 +249,7 @@ describe('Parse EventuallyQueue', () => { const parseServer = await reconfigureServer(); const object = new TestObject({ hash: 'deleteSecret' }); await object.save(); - await parseServer.handleShutdown(); - await new Promise(resolve => parseServer.server.close(resolve)); + await shutdownServer(parseServer); await object.destroyEventually(); const length = await Parse.EventuallyQueue.length(); diff --git a/integration/test/ParseLiveQueryTest.js b/integration/test/ParseLiveQueryTest.js index 92e56f49d..b97c93b8e 100644 --- a/integration/test/ParseLiveQueryTest.js +++ b/integration/test/ParseLiveQueryTest.js @@ -112,9 +112,15 @@ describe('Parse LiveQuery', () => { }, sessionToken: undefined, }; + const openPromise = resolvingPromise(); + client.on('open', () => { + if (client.state === 'reconnecting') { + openPromise.resolve(); + } + }); await client.connectPromise; client.socket.send(JSON.stringify(subscribeRequest)); - await sleep(1000); + await openPromise; expect(resubscribeSpy).toHaveBeenCalled(); await client.close(); }); diff --git a/integration/test/ParseLocalDatastoreTest.js b/integration/test/ParseLocalDatastoreTest.js index a77bcde13..c26134e5f 100644 --- a/integration/test/ParseLocalDatastoreTest.js +++ b/integration/test/ParseLocalDatastoreTest.js @@ -29,7 +29,7 @@ function runTest(controller) { describe(`Parse Object Pinning (${controller.name})`, () => { beforeEach(async () => { - const StorageController = require(controller.file); + const StorageController = require(controller.file).default; Parse.CoreManager.setAsyncStorage(mockRNStorage); Parse.CoreManager.setLocalDatastoreController(StorageController); Parse.CoreManager.setEventEmitter(require('events').EventEmitter); @@ -1073,7 +1073,7 @@ function runTest(controller) { describe(`Parse Query Pinning (${controller.name})`, () => { beforeEach(async () => { - const StorageController = require(controller.file); + const StorageController = require(controller.file).default; Parse.CoreManager.setAsyncStorage(mockRNStorage); Parse.CoreManager.setLocalDatastoreController(StorageController); Parse.CoreManager.setEventEmitter(require('events').EventEmitter); diff --git a/integration/test/ParseObjectTest.js b/integration/test/ParseObjectTest.js index 05977687c..a58de1c65 100644 --- a/integration/test/ParseObjectTest.js +++ b/integration/test/ParseObjectTest.js @@ -547,7 +547,7 @@ describe('Parse Object', () => { }); it('cannot create invalid key names', async () => { - const error = new Parse.Error(Parse.Error.INVALID_KEY_NAME, `Invalid key name: "foo^bar"`); + const error = new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'Invalid key name: foo^bar'); const item = new Parse.Object('Item'); expect(() => { item.set({ 'foo^bar': 'baz' }); @@ -559,7 +559,7 @@ describe('Parse Object', () => { const item = new Parse.Object('Item'); expect(() => { item.set({ foobar: 'baz', 'foo^bar': 'baz' }); - }).toThrow(new Parse.Error(Parse.Error.INVALID_KEY_NAME, `Invalid key name: "foo^bar"`)); + }).toThrow(new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'Invalid key name: foo^bar')); }); it('can unset fields', done => { diff --git a/integration/test/ParseReactNativeTest.js b/integration/test/ParseReactNativeTest.js index dac0d794e..cb2faf1e1 100644 --- a/integration/test/ParseReactNativeTest.js +++ b/integration/test/ParseReactNativeTest.js @@ -2,10 +2,11 @@ const Parse = require('../../react-native'); const { resolvingPromise } = require('../../lib/react-native/promiseUtils'); -const CryptoController = require('../../lib/react-native/CryptoController'); -const LocalDatastoreController = require('../../lib/react-native/LocalDatastoreController.default'); -const StorageController = require('../../lib/react-native/StorageController.default'); -const RESTController = require('../../lib/react-native/RESTController'); +const CryptoController = require('../../lib/react-native/CryptoController').default; +const LocalDatastoreController = + require('../../lib/react-native/LocalDatastoreController.default').default; +const StorageController = require('../../lib/react-native/StorageController.default').default; +const RESTController = require('../../lib/react-native/RESTController').default; RESTController._setXHR(require('xmlhttprequest').XMLHttpRequest); diff --git a/integration/test/ParseServerTest.js b/integration/test/ParseServerTest.js index 1ae23a7b4..1554d47b9 100644 --- a/integration/test/ParseServerTest.js +++ b/integration/test/ParseServerTest.js @@ -1,26 +1,37 @@ 'use strict'; -const assert = require('assert'); - describe('ParseServer', () => { it('can reconfigure server', async () => { - const parseServer = await reconfigureServer({ serverURL: 'www.google.com' }); - assert.strictEqual(parseServer.config.serverURL, 'www.google.com'); - await parseServer.handleShutdown(); - await new Promise(resolve => parseServer.server.close(resolve)); - await reconfigureServer(); + let parseServer = await reconfigureServer({ serverURL: 'www.google.com' }); + expect(parseServer.config.serverURL).toBe('www.google.com'); + + await shutdownServer(parseServer); + + parseServer = await reconfigureServer(); + expect(parseServer.config.serverURL).toBe('http://localhost:1337/parse'); }); it('can shutdown', async () => { + let close = 0; const parseServer = await reconfigureServer(); + parseServer.server.on('close', () => { + close += 1; + }); const object = new TestObject({ foo: 'bar' }); - await parseServer.handleShutdown(); - await new Promise(resolve => parseServer.server.close(resolve)); + // Open a connection to the server + const query = new Parse.Query(TestObject); + await query.subscribe(); + expect(openConnections.size > 0).toBeTruthy(); + + await shutdownServer(parseServer); + expect(close).toBe(1); + expect(openConnections.size).toBe(0); + await expectAsync(object.save()).toBeRejectedWithError( 'XMLHttpRequest failed: "Unable to connect to the Parse API"' ); await reconfigureServer({}); await object.save(); - assert(object.id); + expect(object.id).toBeDefined(); }); }); diff --git a/integration/test/ParseUserTest.js b/integration/test/ParseUserTest.js index 931c013ac..89ecfa460 100644 --- a/integration/test/ParseUserTest.js +++ b/integration/test/ParseUserTest.js @@ -28,7 +28,6 @@ const provider = { }; }, }; -Parse.User._registerAuthenticationProvider(provider); const authResponse = { userID: 'test', @@ -44,8 +43,8 @@ global.FB = { }; describe('Parse User', () => { - afterAll(() => { - Parse.Object.unregisterSubclass('CustomUser'); + beforeEach(() => { + Parse.User._registerAuthenticationProvider(provider); }); it('can sign up users via static method', done => { diff --git a/integration/test/clear.js b/integration/test/clear.js deleted file mode 100644 index 2ae35ef2a..000000000 --- a/integration/test/clear.js +++ /dev/null @@ -1,12 +0,0 @@ -const Parse = require('../../node'); - -/** - * Destroys all data in the database - * Calls /clear route in integration/test/server.js - * - * @param {boolean} fast set to true if it's ok to just drop objects and not indexes. - * @returns {Promise} A promise that is resolved when database is deleted. - */ -module.exports = function (fast = true) { - return Parse._ajax('GET', `http://localhost:1337/clear/${fast}`, ''); -}; diff --git a/integration/test/helper.js b/integration/test/helper.js index 7f766e361..0bd7fb10a 100644 --- a/integration/test/helper.js +++ b/integration/test/helper.js @@ -7,7 +7,8 @@ const ParseServer = require('parse-server').default; const CustomAuth = require('./CustomAuth'); const { TestUtils } = require('parse-server'); const Parse = require('../../node'); -const fs = require('fs'); +const { resolvingPromise } = require('../../lib/node/promiseUtils'); +const fs = require('fs').promises; const path = require('path'); const dns = require('dns'); const MockEmailAdapterWithOptions = require('./support/MockEmailAdapterWithOptions'); @@ -21,6 +22,7 @@ const port = 1337; const mountPath = '/parse'; const serverURL = 'http://localhost:1337/parse'; let didChangeConfiguration = false; +const distFiles = {}; /* To generate the auth data below, the Twitter app "GitHub CI Test App" has @@ -91,17 +93,41 @@ const defaultConfiguration = { }), }; -const openConnections = {}; +const openConnections = new Set(); let parseServer; +const destroyConnections = () => { + for (const socket of openConnections.values()) { + socket.destroy(); + } + openConnections.clear(); +}; + +const shutdownServer = async _parseServer => { + const closePromise = resolvingPromise(); + _parseServer.server.on('close', () => { + closePromise.resolve(); + }); + await Promise.all([ + _parseServer.config.databaseController.adapter.handleShutdown(), + _parseServer.liveQueryServer.shutdown(), + ]); + _parseServer.server.close(error => { + if (error) { + console.error('Failed to close Parse Server', error); + } + }); + destroyConnections(); + await closePromise; + expect(openConnections.size).toBe(0); + parseServer = undefined; +}; + const reconfigureServer = async (changedConfiguration = {}) => { if (parseServer) { - await parseServer.handleShutdown(); - await new Promise(resolve => parseServer.server.close(resolve)); - parseServer = undefined; + await shutdownServer(parseServer); return reconfigureServer(changedConfiguration); } - didChangeConfiguration = Object.keys(changedConfiguration).length !== 0; const newConfiguration = Object.assign({}, defaultConfiguration, changedConfiguration || {}, { mountPath, @@ -113,8 +139,7 @@ const reconfigureServer = async (changedConfiguration = {}) => { return reconfigureServer(newConfiguration); } const app = parseServer.expressApp; - for (const fileName of ['parse.js', 'parse.min.js']) { - const file = fs.readFileSync(path.resolve(__dirname, `./../../dist/${fileName}`)).toString(); + for (const [fileName, file] of Object.entries(distFiles)) { app.get(`/${fileName}`, (_req, res) => { res.send(` @@ -132,17 +157,10 @@ const reconfigureServer = async (changedConfiguration = {}) => { `); }); } - app.get('/clear/:fast', (req, res) => { - const { fast } = req.params; - TestUtils.destroyAllDataPermanently(fast).then(() => { - res.send('{}'); - }); - }); parseServer.server.on('connection', connection => { - const key = `${connection.remoteAddress}:${connection.remotePort}`; - openConnections[key] = connection; + openConnections.add(connection); connection.on('close', () => { - delete openConnections[key]; + openConnections.delete(connection); }); }); return parseServer; @@ -155,12 +173,21 @@ global.Container = Parse.Object.extend('Container'); global.TestPoint = Parse.Object.extend('TestPoint'); global.TestObject = Parse.Object.extend('TestObject'); global.reconfigureServer = reconfigureServer; +global.shutdownServer = shutdownServer; +global.openConnections = openConnections; beforeAll(async () => { + const promise = ['parse.js', 'parse.min.js'].map(fileName => { + return fs.readFile(path.resolve(__dirname, `./../../dist/${fileName}`), 'utf8').then(file => { + distFiles[fileName] = file; + }); + }); + await Promise.all(promise); await reconfigureServer(); Parse.initialize('integration'); Parse.CoreManager.set('SERVER_URL', serverURL); Parse.CoreManager.set('MASTER_KEY', 'notsosecret'); + Parse.CoreManager.set('REQUEST_ATTEMPT_LIMIT', 1); }); afterEach(async () => { @@ -172,11 +199,4 @@ afterEach(async () => { } }); -afterAll(() => { - // Jasmine process counts as one open connection - if (Object.keys(openConnections).length > 1) { - console.warn('There were open connections to the server left after the test finished'); - } -}); - module.exports = { twitterAuthData }; diff --git a/jasmine.json b/jasmine.json index 9590307f3..032337cde 100644 --- a/jasmine.json +++ b/jasmine.json @@ -6,6 +6,5 @@ "spec_files": [ "*Test.js" ], - "random": true, - "timeout": 20000 + "random": true } diff --git a/package-lock.json b/package-lock.json index cd13e5179..10b0a5931 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,15 @@ { "name": "parse", - "version": "6.0.0", + "version": "6.1.0-alpha.3", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "parse", - "version": "6.0.0", + "version": "6.1.0-alpha.3", "license": "Apache-2.0", "dependencies": { - "@babel/runtime-corejs3": "7.26.9", + "@babel/runtime-corejs3": "7.26.10", "idb-keyval": "6.2.1", "react-native-crypto-js": "1.0.0", "uuid": "10.0.0", @@ -17,13 +17,13 @@ "xmlhttprequest": "1.8.0" }, "devDependencies": { - "@babel/core": "7.26.9", + "@babel/core": "7.26.10", "@babel/plugin-proposal-class-properties": "7.18.6", - "@babel/plugin-transform-runtime": "7.26.9", + "@babel/plugin-transform-runtime": "7.26.10", "@babel/preset-env": "7.26.9", "@babel/preset-react": "7.26.3", "@babel/preset-typescript": "7.26.0", - "@eslint/js": "9.18.0", + "@eslint/js": "9.22.0", "@parse/minami": "git+https://github.com/parse-community/minami#main", "@saithodev/semantic-release-backmerge": "4.0.1", "@semantic-release/changelog": "6.0.3", @@ -39,11 +39,11 @@ "babel-plugin-transform-inline-environment-variables": "0.4.4", "browserify": "17.0.0", "codecov": "3.8.3", - "core-js": "3.40.0", + "core-js": "3.41.0", "cross-env": "7.0.2", - "eslint": "9.21.0", + "eslint": "9.22.0", "eslint-plugin-expect-type": "0.6.2", - "eslint-plugin-jsdoc": "50.6.3", + "eslint-plugin-jsdoc": "50.6.6", "express": "4.21.2", "gulp": "5.0.0", "gulp-babel": "8.0.0", @@ -60,16 +60,16 @@ "jest-environment-jsdom": "29.7.0", "jsdoc": "4.0.4", "jsdoc-babel": "0.5.0", - "lint-staged": "15.4.3", + "lint-staged": "15.5.0", "madge": "8.0.0", "metro-react-native-babel-preset": "0.77.0", "mongodb-runner": "5.8.0", "parse-server": "7.3.0", "prettier": "3.5.2", - "puppeteer": "24.2.1", + "puppeteer": "24.4.0", "regenerator-runtime": "0.14.1", "semantic-release": "24.2.3", - "typescript-eslint": "8.25.0", + "typescript-eslint": "8.26.0", "vinyl-source-stream": "2.0.0" }, "engines": { @@ -444,22 +444,22 @@ } }, "node_modules/@babel/core": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.9.tgz", - "integrity": "sha512-lWBYIrF7qK5+GjY5Uy+/hEgp8OJWOD/rpy74GplYRhEauvbHDeFB8t5hPOZxCZ0Oxf4Cc36tK51/l3ymJysrKw==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.10.tgz", + "integrity": "sha512-vMqyb7XCDMPvJFFOaT9kxtiRh42GwlZEg1/uIgtZshS5a/8OaduUfCi7kynKgc3Tw/6Uo2D+db9qBttghhmxwQ==", "dev": true, "license": "MIT", "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.26.2", - "@babel/generator": "^7.26.9", + "@babel/generator": "^7.26.10", "@babel/helper-compilation-targets": "^7.26.5", "@babel/helper-module-transforms": "^7.26.0", - "@babel/helpers": "^7.26.9", - "@babel/parser": "^7.26.9", + "@babel/helpers": "^7.26.10", + "@babel/parser": "^7.26.10", "@babel/template": "^7.26.9", - "@babel/traverse": "^7.26.9", - "@babel/types": "^7.26.9", + "@babel/traverse": "^7.26.10", + "@babel/types": "^7.26.10", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", @@ -520,14 +520,14 @@ } }, "node_modules/@babel/generator": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.26.9.tgz", - "integrity": "sha512-kEWdzjOAUMW4hAyrzJ0ZaTOu9OmpyDIQicIh0zg0EEcEkYXZb2TjtBhnHi2ViX7PKwZqF4xwqfAm299/QMP3lg==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.26.10.tgz", + "integrity": "sha512-rRHT8siFIXQrAYOYqZQVsAr8vJ+cBNqcVAY6m5V8/4QqzaPl+zDBe6cLEPRDuNOUf3ww8RfJVlOyQMoSI+5Ang==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^7.26.9", - "@babel/types": "^7.26.9", + "@babel/parser": "^7.26.10", + "@babel/types": "^7.26.10", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^3.0.2" @@ -828,27 +828,27 @@ } }, "node_modules/@babel/helpers": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.9.tgz", - "integrity": "sha512-Mz/4+y8udxBKdmzt/UjPACs4G3j5SshJJEFFKxlCGPydG4JAHXxjWjAwjd09tf6oINvl1VfMJo+nB7H2YKQ0dA==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.10.tgz", + "integrity": "sha512-UPYc3SauzZ3JGgj87GgZ89JVdC5dj0AoetR5Bw6wj4niittNyFh6+eOGonYvJ1ao6B8lEa3Q3klS7ADZ53bc5g==", "dev": true, "license": "MIT", "dependencies": { "@babel/template": "^7.26.9", - "@babel/types": "^7.26.9" + "@babel/types": "^7.26.10" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/parser": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.9.tgz", - "integrity": "sha512-81NWa1njQblgZbQHxWHpxxCzNsa3ZwvFqpUg7P+NNUU6f3UU2jBEg4OlF/J6rl8+PQGh1q6/zWScd001YwcA5A==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.10.tgz", + "integrity": "sha512-6aQR2zGE/QFi8JpDLjUZEPYOs7+mhKXm86VaKFiLP35JQwQb6bwUE+XbvkH0EptsYhbNBSUGaUBLKqxH1xSgsA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^7.26.9" + "@babel/types": "^7.26.10" }, "bin": { "parser": "bin/babel-parser.js" @@ -2114,16 +2114,16 @@ } }, "node_modules/@babel/plugin-transform-runtime": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.26.9.tgz", - "integrity": "sha512-Jf+8y9wXQbbxvVYTM8gO5oEF2POdNji0NMltEkG7FtmzD9PVz7/lxpqSdTvwsjTMU5HIHuDVNf2SOxLkWi+wPQ==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.26.10.tgz", + "integrity": "sha512-NWaL2qG6HRpONTnj4JvDU6th4jYeZOJgu3QhmFTCihib0ermtOJqktA5BduGm3suhhVe9EMP9c9+mfJ/I9slqw==", "dev": true, "license": "MIT", "dependencies": { "@babel/helper-module-imports": "^7.25.9", "@babel/helper-plugin-utils": "^7.26.5", "babel-plugin-polyfill-corejs2": "^0.4.10", - "babel-plugin-polyfill-corejs3": "^0.10.6", + "babel-plugin-polyfill-corejs3": "^0.11.0", "babel-plugin-polyfill-regenerator": "^0.6.1", "semver": "^6.3.1" }, @@ -2387,20 +2387,6 @@ "@babel/core": "^7.0.0-0" } }, - "node_modules/@babel/preset-env/node_modules/babel-plugin-polyfill-corejs3": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.11.1.tgz", - "integrity": "sha512-yGCqvBT4rwMczo28xkH/noxJ6MZ4nJfkVYdoDaC/utLtWrXxv27HVrzAeSbqR8SxDsp46n0YF47EbHoixy6rXQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-define-polyfill-provider": "^0.6.3", - "core-js-compat": "^3.40.0" - }, - "peerDependencies": { - "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" - } - }, "node_modules/@babel/preset-env/node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", @@ -2476,9 +2462,9 @@ } }, "node_modules/@babel/runtime-corejs3": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.26.9.tgz", - "integrity": "sha512-5EVjbTegqN7RSJle6hMWYxO4voo4rI+9krITk+DWR+diJgGrjZjrIBnJhjrHYYQsFgI7j1w1QnrvV7YSKBfYGg==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.26.10.tgz", + "integrity": "sha512-uITFQYO68pMEYR46AHgQoyBg7KPPJDAbGn4jUTIRgCFJIp88MIBUianVOplhZDEec07bp9zIyr4Kp0FCyQzmWg==", "license": "MIT", "dependencies": { "core-js-pure": "^3.30.2", @@ -2504,17 +2490,17 @@ } }, "node_modules/@babel/traverse": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.26.9.tgz", - "integrity": "sha512-ZYW7L+pL8ahU5fXmNbPF+iZFHCv5scFak7MZ9bwaRPLUhHh7QQEMjZUg0HevihoqCM5iSYHN61EyCoZvqC+bxg==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.26.10.tgz", + "integrity": "sha512-k8NuDrxr0WrPH5Aupqb2LCVURP/S0vBEn5mK6iH+GIYob66U5EtoZvcdudR2jQ4cmTwhEwW1DLB+Yyas9zjF6A==", "dev": true, "license": "MIT", "dependencies": { "@babel/code-frame": "^7.26.2", - "@babel/generator": "^7.26.9", - "@babel/parser": "^7.26.9", + "@babel/generator": "^7.26.10", + "@babel/parser": "^7.26.10", "@babel/template": "^7.26.9", - "@babel/types": "^7.26.9", + "@babel/types": "^7.26.10", "debug": "^4.3.1", "globals": "^11.1.0" }, @@ -2523,9 +2509,9 @@ } }, "node_modules/@babel/types": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.9.tgz", - "integrity": "sha512-Y3IR1cRnOxOCDvMmNiym7XpXQ93iGDDPHx+Zj+NM+rg0fBaShfQLkg+hKPaZCEvg5N/LeCo4+Rj/i3FuJsIQaw==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.10.tgz", + "integrity": "sha512-emqcG3vHrpxUKTrxcblR36dcrcoRDvKmnL/dCL6ZsHaShW80qxCAcNhzQZrpeM765VzEos+xOi4s+r4IXzTwdQ==", "dev": true, "license": "MIT", "dependencies": { @@ -2660,6 +2646,16 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@eslint/config-helpers": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.1.0.tgz", + "integrity": "sha512-kLrdPDJE1ckPo94kmPPf9Hfd0DU0Jw6oKYrhe+pwSC0iTUInmTa+w6fw8sGgcfkFJGNdWOUeOaDM4quW4a7OkA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, "node_modules/@eslint/core": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.12.0.tgz", @@ -2744,10 +2740,11 @@ } }, "node_modules/@eslint/js": { - "version": "9.18.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.18.0.tgz", - "integrity": "sha512-fK6L7rxcq6/z+AaQMtiFTkvbHkBLNlwyRxHpKawP0x3u9+NC6MQTnFW+AdpwC6gfHTW0051cokQgtTN2FqlxQA==", + "version": "9.22.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.22.0.tgz", + "integrity": "sha512-vLFajx9o8d1/oL2ZkpMYbkLv8nDB6yaIwFNt7nI4+I80U/z03SxmfOMsLbvWr3p7C+Wnoh//aOu2pQW8cS0HCQ==", "dev": true, + "license": "MIT", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } @@ -5143,9 +5140,9 @@ "dev": true }, "node_modules/@puppeteer/browsers": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.7.1.tgz", - "integrity": "sha512-MK7rtm8JjaxPN7Mf1JdZIZKPD2Z+W7osvrC1vjpvfOX1K0awDIHYbNi89f7eotp7eMUn2shWnt03HwVbriXtKQ==", + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.8.0.tgz", + "integrity": "sha512-yTwt2KWRmCQAfhvbCRjebaSX8pV1//I0Y3g+A7f/eS7gf0l4eRJoUCvcYdVtboeU4CTOZQuqYbZNS8aBYb8ROQ==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -5153,7 +5150,7 @@ "extract-zip": "^2.0.1", "progress": "^2.0.3", "proxy-agent": "^6.5.0", - "semver": "^7.7.0", + "semver": "^7.7.1", "tar-fs": "^3.0.8", "yargs": "^17.7.2" }, @@ -7477,17 +7474,17 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.25.0.tgz", - "integrity": "sha512-VM7bpzAe7JO/BFf40pIT1lJqS/z1F8OaSsUB3rpFJucQA4cOSuH2RVVVkFULN+En0Djgr29/jb4EQnedUo95KA==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.26.0.tgz", + "integrity": "sha512-cLr1J6pe56zjKYajK6SSSre6nl1Gj6xDp1TY0trpgPzjVbgDwd09v2Ws37LABxzkicmUjhEeg/fAUjPJJB1v5Q==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "8.25.0", - "@typescript-eslint/type-utils": "8.25.0", - "@typescript-eslint/utils": "8.25.0", - "@typescript-eslint/visitor-keys": "8.25.0", + "@typescript-eslint/scope-manager": "8.26.0", + "@typescript-eslint/type-utils": "8.26.0", + "@typescript-eslint/utils": "8.26.0", + "@typescript-eslint/visitor-keys": "8.26.0", "graphemer": "^1.4.0", "ignore": "^5.3.1", "natural-compare": "^1.4.0", @@ -7503,7 +7500,7 @@ "peerDependencies": { "@typescript-eslint/parser": "^8.0.0 || ^8.0.0-alpha.0", "eslint": "^8.57.0 || ^9.0.0", - "typescript": ">=4.8.4 <5.8.0" + "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/@typescript-eslint/eslint-plugin/node_modules/ts-api-utils": { @@ -7520,16 +7517,16 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.25.0.tgz", - "integrity": "sha512-4gbs64bnbSzu4FpgMiQ1A+D+urxkoJk/kqlDJ2W//5SygaEiAP2B4GoS7TEdxgwol2el03gckFV9lJ4QOMiiHg==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.26.0.tgz", + "integrity": "sha512-mNtXP9LTVBy14ZF3o7JG69gRPBK/2QWtQd0j0oH26HcY/foyJJau6pNUez7QrM5UHnSvwlQcJXKsk0I99B9pOA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.25.0", - "@typescript-eslint/types": "8.25.0", - "@typescript-eslint/typescript-estree": "8.25.0", - "@typescript-eslint/visitor-keys": "8.25.0", + "@typescript-eslint/scope-manager": "8.26.0", + "@typescript-eslint/types": "8.26.0", + "@typescript-eslint/typescript-estree": "8.26.0", + "@typescript-eslint/visitor-keys": "8.26.0", "debug": "^4.3.4" }, "engines": { @@ -7541,18 +7538,18 @@ }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", - "typescript": ">=4.8.4 <5.8.0" + "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.25.0.tgz", - "integrity": "sha512-6PPeiKIGbgStEyt4NNXa2ru5pMzQ8OYKO1hX1z53HMomrmiSB+R5FmChgQAP1ro8jMtNawz+TRQo/cSXrauTpg==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.26.0.tgz", + "integrity": "sha512-E0ntLvsfPqnPwng8b8y4OGuzh/iIOm2z8U3S9zic2TeMLW61u5IH2Q1wu0oSTkfrSzwbDJIB/Lm8O3//8BWMPA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.25.0", - "@typescript-eslint/visitor-keys": "8.25.0" + "@typescript-eslint/types": "8.26.0", + "@typescript-eslint/visitor-keys": "8.26.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -7563,14 +7560,14 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.25.0.tgz", - "integrity": "sha512-d77dHgHWnxmXOPJuDWO4FDWADmGQkN5+tt6SFRZz/RtCWl4pHgFl3+WdYCn16+3teG09DY6XtEpf3gGD0a186g==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.26.0.tgz", + "integrity": "sha512-ruk0RNChLKz3zKGn2LwXuVoeBcUMh+jaqzN461uMMdxy5H9epZqIBtYj7UiPXRuOpaALXGbmRuZQhmwHhaS04Q==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/typescript-estree": "8.25.0", - "@typescript-eslint/utils": "8.25.0", + "@typescript-eslint/typescript-estree": "8.26.0", + "@typescript-eslint/utils": "8.26.0", "debug": "^4.3.4", "ts-api-utils": "^2.0.1" }, @@ -7583,7 +7580,7 @@ }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", - "typescript": ">=4.8.4 <5.8.0" + "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/@typescript-eslint/type-utils/node_modules/ts-api-utils": { @@ -7600,9 +7597,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.25.0.tgz", - "integrity": "sha512-+vUe0Zb4tkNgznQwicsvLUJgZIRs6ITeWSCclX1q85pR1iOiaj+4uZJIUp//Z27QWu5Cseiw3O3AR8hVpax7Aw==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.26.0.tgz", + "integrity": "sha512-89B1eP3tnpr9A8L6PZlSjBvnJhWXtYfZhECqlBl1D9Lme9mHO6iWlsprBtVenQvY1HMhax1mWOjhtL3fh/u+pA==", "dev": true, "license": "MIT", "engines": { @@ -7614,14 +7611,14 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.25.0.tgz", - "integrity": "sha512-ZPaiAKEZ6Blt/TPAx5Ot0EIB/yGtLI2EsGoY6F7XKklfMxYQyvtL+gT/UCqkMzO0BVFHLDlzvFqQzurYahxv9Q==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.26.0.tgz", + "integrity": "sha512-tiJ1Hvy/V/oMVRTbEOIeemA2XoylimlDQ03CgPPNaHYZbpsc78Hmngnt+WXZfJX1pjQ711V7g0H7cSJThGYfPQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.25.0", - "@typescript-eslint/visitor-keys": "8.25.0", + "@typescript-eslint/types": "8.26.0", + "@typescript-eslint/visitor-keys": "8.26.0", "debug": "^4.3.4", "fast-glob": "^3.3.2", "is-glob": "^4.0.3", @@ -7637,7 +7634,7 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "typescript": ">=4.8.4 <5.8.0" + "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { @@ -7680,16 +7677,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.25.0.tgz", - "integrity": "sha512-syqRbrEv0J1wywiLsK60XzHnQe/kRViI3zwFALrNEgnntn1l24Ra2KvOAWwWbWZ1lBZxZljPDGOq967dsl6fkA==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.26.0.tgz", + "integrity": "sha512-2L2tU3FVwhvU14LndnQCA2frYC8JnPDVKyQtWFPf8IYFMt/ykEN1bPolNhNbCVgOmdzTlWdusCTKA/9nKrf8Ig==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", - "@typescript-eslint/scope-manager": "8.25.0", - "@typescript-eslint/types": "8.25.0", - "@typescript-eslint/typescript-estree": "8.25.0" + "@typescript-eslint/scope-manager": "8.26.0", + "@typescript-eslint/types": "8.26.0", + "@typescript-eslint/typescript-estree": "8.26.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -7700,17 +7697,17 @@ }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", - "typescript": ">=4.8.4 <5.8.0" + "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.25.0.tgz", - "integrity": "sha512-kCYXKAum9CecGVHGij7muybDfTS2sD3t0L4bJsEZLkyrXUImiCTq1M3LG2SRtOhiHFwMR9wAFplpT6XHYjTkwQ==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.26.0.tgz", + "integrity": "sha512-2z8JQJWAzPdDd51dRQ/oqIJxe99/hoLIqmf8RMCAJQtYDc535W/Jt2+RTP4bP0aKeBG1F65yjIZuczOXCmbWwg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.25.0", + "@typescript-eslint/types": "8.26.0", "eslint-visitor-keys": "^4.2.0" }, "engines": { @@ -8674,13 +8671,14 @@ } }, "node_modules/babel-plugin-polyfill-corejs3": { - "version": "0.10.6", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.10.6.tgz", - "integrity": "sha512-b37+KR2i/khY5sKmWNVQAnitvquQbNdWy6lJdsr0kmquCKEEUgMKK4SboVM3HtfnZilfjr4MMQ7vY58FVWDtIA==", + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.11.1.tgz", + "integrity": "sha512-yGCqvBT4rwMczo28xkH/noxJ6MZ4nJfkVYdoDaC/utLtWrXxv27HVrzAeSbqR8SxDsp46n0YF47EbHoixy6rXQ==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/helper-define-polyfill-provider": "^0.6.2", - "core-js-compat": "^3.38.0" + "@babel/helper-define-polyfill-provider": "^0.6.3", + "core-js-compat": "^3.40.0" }, "peerDependencies": { "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" @@ -8814,14 +8812,14 @@ } }, "node_modules/bare-os": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.4.0.tgz", - "integrity": "sha512-9Ous7UlnKbe3fMi7Y+qh0DwAup6A1JkYgPnjvMDNOlmnxNRQvQ/7Nst+OnUQKzk0iAT0m9BisbDVp9gCv8+ETA==", + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.5.1.tgz", + "integrity": "sha512-LvfVNDcWLw2AnIw5f2mWUgumW3I3N/WYGiWeimhQC1Ybt71n2FjlS9GJKeCnFeg1MKZHxzIFmpFnBXDI+sBeFg==", "dev": true, "license": "Apache-2.0", "optional": true, "engines": { - "bare": ">=1.6.0" + "bare": ">=1.14.0" } }, "node_modules/bare-path": { @@ -9811,9 +9809,9 @@ "dev": true }, "node_modules/chromium-bidi": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-1.3.0.tgz", - "integrity": "sha512-G3x1bkST13kmbL7+dT/oRkNH/7C4UqG+0YQpmySrzXspyOhYgDNc6lhSGpj3cuexvH25WTENhTYq2Tt9JRXtbw==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-2.1.2.tgz", + "integrity": "sha512-vtRWBK2uImo5/W2oG6/cDkkHSm+2t6VHgnj+Rcwhb0pP74OoUb4GipyRX/T/y39gYQPhioP0DPShn+A7P6CHNw==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -10614,11 +10612,12 @@ } }, "node_modules/core-js": { - "version": "3.40.0", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.40.0.tgz", - "integrity": "sha512-7vsMc/Lty6AGnn7uFpYT56QesI5D2Y/UkgKounk87OP9Z2H9Z8kj6jzcSGAxFmUtDOS0ntK6lbQz+Nsa0Jj6mQ==", + "version": "3.41.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.41.0.tgz", + "integrity": "sha512-SJ4/EHwS36QMJd6h/Rg+GyR4A5xE0FSI3eZ+iBVpfqf1x0eTSg1smWLHrA+2jQThZSh97fmSgFSU8B61nxosxA==", "dev": true, "hasInstallScript": true, + "license": "MIT", "funding": { "type": "opencollective", "url": "https://opencollective.com/core-js" @@ -12030,9 +12029,9 @@ } }, "node_modules/devtools-protocol": { - "version": "0.0.1402036", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1402036.tgz", - "integrity": "sha512-JwAYQgEvm3yD45CHB+RmF5kMbWtXBaOGwuxa87sZogHcLCv8c/IqnThaoQ1y60d7pXWjSKWQphPEc+1rAScVdg==", + "version": "0.0.1413902", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1413902.tgz", + "integrity": "sha512-yRtvFD8Oyk7C9Os3GmnFZLu53yAfsnyw1s+mLmHHUK0GQEc9zthHWvS1r67Zqzm5t7v56PILHIVZ7kmFMaL2yQ==", "dev": true, "license": "BSD-3-Clause" }, @@ -12688,18 +12687,19 @@ } }, "node_modules/eslint": { - "version": "9.21.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.21.0.tgz", - "integrity": "sha512-KjeihdFqTPhOMXTt7StsDxriV4n66ueuF/jfPNC3j/lduHwr/ijDwJMsF+wyMJethgiKi5wniIE243vi07d3pg==", + "version": "9.22.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.22.0.tgz", + "integrity": "sha512-9V/QURhsRN40xuHXWjV64yvrzMjcz7ZyNoF2jJFmy9j/SLk0u1OLSZgXi28MrXjymnjEGSR80WCdab3RGMDveQ==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", "@eslint/config-array": "^0.19.2", + "@eslint/config-helpers": "^0.1.0", "@eslint/core": "^0.12.0", "@eslint/eslintrc": "^3.3.0", - "@eslint/js": "9.21.0", + "@eslint/js": "9.22.0", "@eslint/plugin-kit": "^0.2.7", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", @@ -12711,7 +12711,7 @@ "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^8.2.0", + "eslint-scope": "^8.3.0", "eslint-visitor-keys": "^4.2.0", "espree": "^10.3.0", "esquery": "^1.5.0", @@ -12767,9 +12767,9 @@ } }, "node_modules/eslint-plugin-jsdoc": { - "version": "50.6.3", - "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-50.6.3.tgz", - "integrity": "sha512-NxbJyt1M5zffPcYZ8Nb53/8nnbIScmiLAMdoe0/FAszwb7lcSiX3iYBTsuF7RV84dZZJC8r3NghomrUXsmWvxQ==", + "version": "50.6.6", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-50.6.6.tgz", + "integrity": "sha512-4jLo9NZqHfyNtiBxAU293eX1xi6oUIBcAxJJL/hHeeNhh26l4l/Apmu0x9SarvSQ/gWNOrnFci4DSPupN4//WA==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -12839,16 +12839,6 @@ "url": "https://opencollective.com/eslint" } }, - "node_modules/eslint/node_modules/@eslint/js": { - "version": "9.21.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.21.0.tgz", - "integrity": "sha512-BqStZ3HX8Yz6LvsF5ByXYrtigrV5AXADWLAGc7PH/1SxOb7/FIYYMszZZWiUou/GB9P2lXWk2SV4d+Z8h0nknw==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, "node_modules/eslint/node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", @@ -12911,10 +12901,11 @@ } }, "node_modules/eslint/node_modules/eslint-scope": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.2.0.tgz", - "integrity": "sha512-PHlWUfG6lvPc3yvP5A4PNyBL1W8fkDUccmI21JUu/+GKZBoH/W5u6usENXUrWFRsyoW5ACUjFGgAFQp5gUlb/A==", + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.3.0.tgz", + "integrity": "sha512-pUNxi75F8MJ/GdeKtVLSbYg4ZI34J6C0C7sbL4YOp2exGwen7ZsuBqKzUhXd0qMQ362yET3z+uPwKeg/0C2XCQ==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" @@ -12943,6 +12934,7 @@ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true, + "license": "BSD-2-Clause", "engines": { "node": ">=4.0" } @@ -19713,9 +19705,9 @@ } }, "node_modules/lint-staged": { - "version": "15.4.3", - "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.4.3.tgz", - "integrity": "sha512-FoH1vOeouNh1pw+90S+cnuoFwRfUD9ijY2GKy5h7HS3OR7JVir2N2xrsa0+Twc1B7cW72L+88geG5cW4wIhn7g==", + "version": "15.5.0", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.5.0.tgz", + "integrity": "sha512-WyCzSbfYGhK7cU+UuDDkzUiytbfbi0ZdPy2orwtM75P3WTtQBzmG40cCxIa8Ii2+XjfxzLH6Be46tUfWS85Xfg==", "dev": true, "license": "MIT", "dependencies": { @@ -24839,9 +24831,9 @@ } }, "node_modules/pac-proxy-agent": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.1.0.tgz", - "integrity": "sha512-Z5FnLVVZSnX7WjBg0mhDtydeRZ1xMcATZThjySQUHqr+0ksP8kqaw23fNKkaaN/Z8gwLUs/W7xdl0I75eP2Xyw==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz", + "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==", "dev": true, "license": "MIT", "dependencies": { @@ -26307,18 +26299,18 @@ } }, "node_modules/puppeteer": { - "version": "24.2.1", - "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-24.2.1.tgz", - "integrity": "sha512-Euno62ou0cd0dTkOYTNioSOsFF4VpSnz4ldD38hi9ov9xCNtr8DbhmoJRUx+V9OuPgecueZbKOohRrnrhkbg3Q==", + "version": "24.4.0", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-24.4.0.tgz", + "integrity": "sha512-E4JhJzjS8AAI+6N/b+Utwarhz6zWl3+MR725fal+s3UlOlX2eWdsvYYU+Q5bXMjs9eZEGkNQroLkn7j11s2k1Q==", "dev": true, "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { - "@puppeteer/browsers": "2.7.1", - "chromium-bidi": "1.3.0", + "@puppeteer/browsers": "2.8.0", + "chromium-bidi": "2.1.2", "cosmiconfig": "^9.0.0", - "devtools-protocol": "0.0.1402036", - "puppeteer-core": "24.2.1", + "devtools-protocol": "0.0.1413902", + "puppeteer-core": "24.4.0", "typed-query-selector": "^2.12.0" }, "bin": { @@ -26329,18 +26321,18 @@ } }, "node_modules/puppeteer-core": { - "version": "24.2.1", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.2.1.tgz", - "integrity": "sha512-bCypUh3WXzETafv1TCFAjIUnI8BiQ/d+XvEfEXDLcIMm9CAvROqnBmbt79yBjwasoDZsgfXnUmIJU7Y27AalVQ==", + "version": "24.4.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.4.0.tgz", + "integrity": "sha512-eFw66gCnWo0X8Hyf9KxxJtms7a61NJVMiSaWfItsFPzFBsjsWdmcNlBdsA1WVwln6neoHhsG+uTVesKmTREn/g==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@puppeteer/browsers": "2.7.1", - "chromium-bidi": "1.3.0", + "@puppeteer/browsers": "2.8.0", + "chromium-bidi": "2.1.2", "debug": "^4.4.0", - "devtools-protocol": "0.0.1402036", + "devtools-protocol": "0.0.1413902", "typed-query-selector": "^2.12.0", - "ws": "^8.18.0" + "ws": "^8.18.1" }, "engines": { "node": ">=18" @@ -29784,15 +29776,15 @@ } }, "node_modules/typescript-eslint": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.25.0.tgz", - "integrity": "sha512-TxRdQQLH4g7JkoFlYG3caW5v1S6kEkz8rqt80iQJZUYPq1zD1Ra7HfQBJJ88ABRaMvHAXnwRvRB4V+6sQ9xN5Q==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.26.0.tgz", + "integrity": "sha512-PtVz9nAnuNJuAVeUFvwztjuUgSnJInODAUx47VDwWPXzd5vismPOtPtt83tzNXyOjVQbPRp786D6WFW/M2koIA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.25.0", - "@typescript-eslint/parser": "8.25.0", - "@typescript-eslint/utils": "8.25.0" + "@typescript-eslint/eslint-plugin": "8.26.0", + "@typescript-eslint/parser": "8.26.0", + "@typescript-eslint/utils": "8.26.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -29803,7 +29795,7 @@ }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", - "typescript": ">=4.8.4 <5.8.0" + "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/uc.micro": { @@ -31502,21 +31494,21 @@ "dev": true }, "@babel/core": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.9.tgz", - "integrity": "sha512-lWBYIrF7qK5+GjY5Uy+/hEgp8OJWOD/rpy74GplYRhEauvbHDeFB8t5hPOZxCZ0Oxf4Cc36tK51/l3ymJysrKw==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.10.tgz", + "integrity": "sha512-vMqyb7XCDMPvJFFOaT9kxtiRh42GwlZEg1/uIgtZshS5a/8OaduUfCi7kynKgc3Tw/6Uo2D+db9qBttghhmxwQ==", "dev": true, "requires": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.26.2", - "@babel/generator": "^7.26.9", + "@babel/generator": "^7.26.10", "@babel/helper-compilation-targets": "^7.26.5", "@babel/helper-module-transforms": "^7.26.0", - "@babel/helpers": "^7.26.9", - "@babel/parser": "^7.26.9", + "@babel/helpers": "^7.26.10", + "@babel/parser": "^7.26.10", "@babel/template": "^7.26.9", - "@babel/traverse": "^7.26.9", - "@babel/types": "^7.26.9", + "@babel/traverse": "^7.26.10", + "@babel/types": "^7.26.10", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", @@ -31558,13 +31550,13 @@ } }, "@babel/generator": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.26.9.tgz", - "integrity": "sha512-kEWdzjOAUMW4hAyrzJ0ZaTOu9OmpyDIQicIh0zg0EEcEkYXZb2TjtBhnHi2ViX7PKwZqF4xwqfAm299/QMP3lg==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.26.10.tgz", + "integrity": "sha512-rRHT8siFIXQrAYOYqZQVsAr8vJ+cBNqcVAY6m5V8/4QqzaPl+zDBe6cLEPRDuNOUf3ww8RfJVlOyQMoSI+5Ang==", "dev": true, "requires": { - "@babel/parser": "^7.26.9", - "@babel/types": "^7.26.9", + "@babel/parser": "^7.26.10", + "@babel/types": "^7.26.10", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^3.0.2" @@ -31787,22 +31779,22 @@ } }, "@babel/helpers": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.9.tgz", - "integrity": "sha512-Mz/4+y8udxBKdmzt/UjPACs4G3j5SshJJEFFKxlCGPydG4JAHXxjWjAwjd09tf6oINvl1VfMJo+nB7H2YKQ0dA==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.10.tgz", + "integrity": "sha512-UPYc3SauzZ3JGgj87GgZ89JVdC5dj0AoetR5Bw6wj4niittNyFh6+eOGonYvJ1ao6B8lEa3Q3klS7ADZ53bc5g==", "dev": true, "requires": { "@babel/template": "^7.26.9", - "@babel/types": "^7.26.9" + "@babel/types": "^7.26.10" } }, "@babel/parser": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.9.tgz", - "integrity": "sha512-81NWa1njQblgZbQHxWHpxxCzNsa3ZwvFqpUg7P+NNUU6f3UU2jBEg4OlF/J6rl8+PQGh1q6/zWScd001YwcA5A==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.10.tgz", + "integrity": "sha512-6aQR2zGE/QFi8JpDLjUZEPYOs7+mhKXm86VaKFiLP35JQwQb6bwUE+XbvkH0EptsYhbNBSUGaUBLKqxH1xSgsA==", "dev": true, "requires": { - "@babel/types": "^7.26.9" + "@babel/types": "^7.26.10" } }, "@babel/plugin-bugfix-firefox-class-in-computed-class-key": { @@ -32600,15 +32592,15 @@ } }, "@babel/plugin-transform-runtime": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.26.9.tgz", - "integrity": "sha512-Jf+8y9wXQbbxvVYTM8gO5oEF2POdNji0NMltEkG7FtmzD9PVz7/lxpqSdTvwsjTMU5HIHuDVNf2SOxLkWi+wPQ==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.26.10.tgz", + "integrity": "sha512-NWaL2qG6HRpONTnj4JvDU6th4jYeZOJgu3QhmFTCihib0ermtOJqktA5BduGm3suhhVe9EMP9c9+mfJ/I9slqw==", "dev": true, "requires": { "@babel/helper-module-imports": "^7.25.9", "@babel/helper-plugin-utils": "^7.26.5", "babel-plugin-polyfill-corejs2": "^0.4.10", - "babel-plugin-polyfill-corejs3": "^0.10.6", + "babel-plugin-polyfill-corejs3": "^0.11.0", "babel-plugin-polyfill-regenerator": "^0.6.1", "semver": "^6.3.1" }, @@ -32796,16 +32788,6 @@ "semver": "^6.3.1" }, "dependencies": { - "babel-plugin-polyfill-corejs3": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.11.1.tgz", - "integrity": "sha512-yGCqvBT4rwMczo28xkH/noxJ6MZ4nJfkVYdoDaC/utLtWrXxv27HVrzAeSbqR8SxDsp46n0YF47EbHoixy6rXQ==", - "dev": true, - "requires": { - "@babel/helper-define-polyfill-provider": "^0.6.3", - "core-js-compat": "^3.40.0" - } - }, "semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", @@ -32862,9 +32844,9 @@ } }, "@babel/runtime-corejs3": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.26.9.tgz", - "integrity": "sha512-5EVjbTegqN7RSJle6hMWYxO4voo4rI+9krITk+DWR+diJgGrjZjrIBnJhjrHYYQsFgI7j1w1QnrvV7YSKBfYGg==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.26.10.tgz", + "integrity": "sha512-uITFQYO68pMEYR46AHgQoyBg7KPPJDAbGn4jUTIRgCFJIp88MIBUianVOplhZDEec07bp9zIyr4Kp0FCyQzmWg==", "requires": { "core-js-pure": "^3.30.2", "regenerator-runtime": "^0.14.0" @@ -32882,24 +32864,24 @@ } }, "@babel/traverse": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.26.9.tgz", - "integrity": "sha512-ZYW7L+pL8ahU5fXmNbPF+iZFHCv5scFak7MZ9bwaRPLUhHh7QQEMjZUg0HevihoqCM5iSYHN61EyCoZvqC+bxg==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.26.10.tgz", + "integrity": "sha512-k8NuDrxr0WrPH5Aupqb2LCVURP/S0vBEn5mK6iH+GIYob66U5EtoZvcdudR2jQ4cmTwhEwW1DLB+Yyas9zjF6A==", "dev": true, "requires": { "@babel/code-frame": "^7.26.2", - "@babel/generator": "^7.26.9", - "@babel/parser": "^7.26.9", + "@babel/generator": "^7.26.10", + "@babel/parser": "^7.26.10", "@babel/template": "^7.26.9", - "@babel/types": "^7.26.9", + "@babel/types": "^7.26.10", "debug": "^4.3.1", "globals": "^11.1.0" } }, "@babel/types": { - "version": "7.26.9", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.9.tgz", - "integrity": "sha512-Y3IR1cRnOxOCDvMmNiym7XpXQ93iGDDPHx+Zj+NM+rg0fBaShfQLkg+hKPaZCEvg5N/LeCo4+Rj/i3FuJsIQaw==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.10.tgz", + "integrity": "sha512-emqcG3vHrpxUKTrxcblR36dcrcoRDvKmnL/dCL6ZsHaShW80qxCAcNhzQZrpeM765VzEos+xOi4s+r4IXzTwdQ==", "dev": true, "requires": { "@babel/helper-string-parser": "^7.25.9", @@ -33008,6 +32990,12 @@ "minimatch": "^3.1.2" } }, + "@eslint/config-helpers": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.1.0.tgz", + "integrity": "sha512-kLrdPDJE1ckPo94kmPPf9Hfd0DU0Jw6oKYrhe+pwSC0iTUInmTa+w6fw8sGgcfkFJGNdWOUeOaDM4quW4a7OkA==", + "dev": true + }, "@eslint/core": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.12.0.tgz", @@ -33064,9 +33052,9 @@ } }, "@eslint/js": { - "version": "9.18.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.18.0.tgz", - "integrity": "sha512-fK6L7rxcq6/z+AaQMtiFTkvbHkBLNlwyRxHpKawP0x3u9+NC6MQTnFW+AdpwC6gfHTW0051cokQgtTN2FqlxQA==", + "version": "9.22.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.22.0.tgz", + "integrity": "sha512-vLFajx9o8d1/oL2ZkpMYbkLv8nDB6yaIwFNt7nI4+I80U/z03SxmfOMsLbvWr3p7C+Wnoh//aOu2pQW8cS0HCQ==", "dev": true }, "@eslint/object-schema": { @@ -34854,16 +34842,16 @@ "dev": true }, "@puppeteer/browsers": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.7.1.tgz", - "integrity": "sha512-MK7rtm8JjaxPN7Mf1JdZIZKPD2Z+W7osvrC1vjpvfOX1K0awDIHYbNi89f7eotp7eMUn2shWnt03HwVbriXtKQ==", + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.8.0.tgz", + "integrity": "sha512-yTwt2KWRmCQAfhvbCRjebaSX8pV1//I0Y3g+A7f/eS7gf0l4eRJoUCvcYdVtboeU4CTOZQuqYbZNS8aBYb8ROQ==", "dev": true, "requires": { "debug": "^4.4.0", "extract-zip": "^2.0.1", "progress": "^2.0.3", "proxy-agent": "^6.5.0", - "semver": "^7.7.0", + "semver": "^7.7.1", "tar-fs": "^3.0.8", "yargs": "^17.7.2" }, @@ -36569,16 +36557,16 @@ } }, "@typescript-eslint/eslint-plugin": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.25.0.tgz", - "integrity": "sha512-VM7bpzAe7JO/BFf40pIT1lJqS/z1F8OaSsUB3rpFJucQA4cOSuH2RVVVkFULN+En0Djgr29/jb4EQnedUo95KA==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.26.0.tgz", + "integrity": "sha512-cLr1J6pe56zjKYajK6SSSre6nl1Gj6xDp1TY0trpgPzjVbgDwd09v2Ws37LABxzkicmUjhEeg/fAUjPJJB1v5Q==", "dev": true, "requires": { "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "8.25.0", - "@typescript-eslint/type-utils": "8.25.0", - "@typescript-eslint/utils": "8.25.0", - "@typescript-eslint/visitor-keys": "8.25.0", + "@typescript-eslint/scope-manager": "8.26.0", + "@typescript-eslint/type-utils": "8.26.0", + "@typescript-eslint/utils": "8.26.0", + "@typescript-eslint/visitor-keys": "8.26.0", "graphemer": "^1.4.0", "ignore": "^5.3.1", "natural-compare": "^1.4.0", @@ -36595,36 +36583,36 @@ } }, "@typescript-eslint/parser": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.25.0.tgz", - "integrity": "sha512-4gbs64bnbSzu4FpgMiQ1A+D+urxkoJk/kqlDJ2W//5SygaEiAP2B4GoS7TEdxgwol2el03gckFV9lJ4QOMiiHg==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.26.0.tgz", + "integrity": "sha512-mNtXP9LTVBy14ZF3o7JG69gRPBK/2QWtQd0j0oH26HcY/foyJJau6pNUez7QrM5UHnSvwlQcJXKsk0I99B9pOA==", "dev": true, "requires": { - "@typescript-eslint/scope-manager": "8.25.0", - "@typescript-eslint/types": "8.25.0", - "@typescript-eslint/typescript-estree": "8.25.0", - "@typescript-eslint/visitor-keys": "8.25.0", + "@typescript-eslint/scope-manager": "8.26.0", + "@typescript-eslint/types": "8.26.0", + "@typescript-eslint/typescript-estree": "8.26.0", + "@typescript-eslint/visitor-keys": "8.26.0", "debug": "^4.3.4" } }, "@typescript-eslint/scope-manager": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.25.0.tgz", - "integrity": "sha512-6PPeiKIGbgStEyt4NNXa2ru5pMzQ8OYKO1hX1z53HMomrmiSB+R5FmChgQAP1ro8jMtNawz+TRQo/cSXrauTpg==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.26.0.tgz", + "integrity": "sha512-E0ntLvsfPqnPwng8b8y4OGuzh/iIOm2z8U3S9zic2TeMLW61u5IH2Q1wu0oSTkfrSzwbDJIB/Lm8O3//8BWMPA==", "dev": true, "requires": { - "@typescript-eslint/types": "8.25.0", - "@typescript-eslint/visitor-keys": "8.25.0" + "@typescript-eslint/types": "8.26.0", + "@typescript-eslint/visitor-keys": "8.26.0" } }, "@typescript-eslint/type-utils": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.25.0.tgz", - "integrity": "sha512-d77dHgHWnxmXOPJuDWO4FDWADmGQkN5+tt6SFRZz/RtCWl4pHgFl3+WdYCn16+3teG09DY6XtEpf3gGD0a186g==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.26.0.tgz", + "integrity": "sha512-ruk0RNChLKz3zKGn2LwXuVoeBcUMh+jaqzN461uMMdxy5H9epZqIBtYj7UiPXRuOpaALXGbmRuZQhmwHhaS04Q==", "dev": true, "requires": { - "@typescript-eslint/typescript-estree": "8.25.0", - "@typescript-eslint/utils": "8.25.0", + "@typescript-eslint/typescript-estree": "8.26.0", + "@typescript-eslint/utils": "8.26.0", "debug": "^4.3.4", "ts-api-utils": "^2.0.1" }, @@ -36639,19 +36627,19 @@ } }, "@typescript-eslint/types": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.25.0.tgz", - "integrity": "sha512-+vUe0Zb4tkNgznQwicsvLUJgZIRs6ITeWSCclX1q85pR1iOiaj+4uZJIUp//Z27QWu5Cseiw3O3AR8hVpax7Aw==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.26.0.tgz", + "integrity": "sha512-89B1eP3tnpr9A8L6PZlSjBvnJhWXtYfZhECqlBl1D9Lme9mHO6iWlsprBtVenQvY1HMhax1mWOjhtL3fh/u+pA==", "dev": true }, "@typescript-eslint/typescript-estree": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.25.0.tgz", - "integrity": "sha512-ZPaiAKEZ6Blt/TPAx5Ot0EIB/yGtLI2EsGoY6F7XKklfMxYQyvtL+gT/UCqkMzO0BVFHLDlzvFqQzurYahxv9Q==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.26.0.tgz", + "integrity": "sha512-tiJ1Hvy/V/oMVRTbEOIeemA2XoylimlDQ03CgPPNaHYZbpsc78Hmngnt+WXZfJX1pjQ711V7g0H7cSJThGYfPQ==", "dev": true, "requires": { - "@typescript-eslint/types": "8.25.0", - "@typescript-eslint/visitor-keys": "8.25.0", + "@typescript-eslint/types": "8.26.0", + "@typescript-eslint/visitor-keys": "8.26.0", "debug": "^4.3.4", "fast-glob": "^3.3.2", "is-glob": "^4.0.3", @@ -36688,24 +36676,24 @@ } }, "@typescript-eslint/utils": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.25.0.tgz", - "integrity": "sha512-syqRbrEv0J1wywiLsK60XzHnQe/kRViI3zwFALrNEgnntn1l24Ra2KvOAWwWbWZ1lBZxZljPDGOq967dsl6fkA==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.26.0.tgz", + "integrity": "sha512-2L2tU3FVwhvU14LndnQCA2frYC8JnPDVKyQtWFPf8IYFMt/ykEN1bPolNhNbCVgOmdzTlWdusCTKA/9nKrf8Ig==", "dev": true, "requires": { "@eslint-community/eslint-utils": "^4.4.0", - "@typescript-eslint/scope-manager": "8.25.0", - "@typescript-eslint/types": "8.25.0", - "@typescript-eslint/typescript-estree": "8.25.0" + "@typescript-eslint/scope-manager": "8.26.0", + "@typescript-eslint/types": "8.26.0", + "@typescript-eslint/typescript-estree": "8.26.0" } }, "@typescript-eslint/visitor-keys": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.25.0.tgz", - "integrity": "sha512-kCYXKAum9CecGVHGij7muybDfTS2sD3t0L4bJsEZLkyrXUImiCTq1M3LG2SRtOhiHFwMR9wAFplpT6XHYjTkwQ==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.26.0.tgz", + "integrity": "sha512-2z8JQJWAzPdDd51dRQ/oqIJxe99/hoLIqmf8RMCAJQtYDc535W/Jt2+RTP4bP0aKeBG1F65yjIZuczOXCmbWwg==", "dev": true, "requires": { - "@typescript-eslint/types": "8.25.0", + "@typescript-eslint/types": "8.26.0", "eslint-visitor-keys": "^4.2.0" }, "dependencies": { @@ -37484,13 +37472,13 @@ } }, "babel-plugin-polyfill-corejs3": { - "version": "0.10.6", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.10.6.tgz", - "integrity": "sha512-b37+KR2i/khY5sKmWNVQAnitvquQbNdWy6lJdsr0kmquCKEEUgMKK4SboVM3HtfnZilfjr4MMQ7vY58FVWDtIA==", + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.11.1.tgz", + "integrity": "sha512-yGCqvBT4rwMczo28xkH/noxJ6MZ4nJfkVYdoDaC/utLtWrXxv27HVrzAeSbqR8SxDsp46n0YF47EbHoixy6rXQ==", "dev": true, "requires": { - "@babel/helper-define-polyfill-provider": "^0.6.2", - "core-js-compat": "^3.38.0" + "@babel/helper-define-polyfill-provider": "^0.6.3", + "core-js-compat": "^3.40.0" } }, "babel-plugin-polyfill-regenerator": { @@ -37599,9 +37587,9 @@ } }, "bare-os": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.4.0.tgz", - "integrity": "sha512-9Ous7UlnKbe3fMi7Y+qh0DwAup6A1JkYgPnjvMDNOlmnxNRQvQ/7Nst+OnUQKzk0iAT0m9BisbDVp9gCv8+ETA==", + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.5.1.tgz", + "integrity": "sha512-LvfVNDcWLw2AnIw5f2mWUgumW3I3N/WYGiWeimhQC1Ybt71n2FjlS9GJKeCnFeg1MKZHxzIFmpFnBXDI+sBeFg==", "dev": true, "optional": true }, @@ -38405,9 +38393,9 @@ "dev": true }, "chromium-bidi": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-1.3.0.tgz", - "integrity": "sha512-G3x1bkST13kmbL7+dT/oRkNH/7C4UqG+0YQpmySrzXspyOhYgDNc6lhSGpj3cuexvH25WTENhTYq2Tt9JRXtbw==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-2.1.2.tgz", + "integrity": "sha512-vtRWBK2uImo5/W2oG6/cDkkHSm+2t6VHgnj+Rcwhb0pP74OoUb4GipyRX/T/y39gYQPhioP0DPShn+A7P6CHNw==", "dev": true, "requires": { "mitt": "^3.0.1", @@ -39036,9 +39024,9 @@ } }, "core-js": { - "version": "3.40.0", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.40.0.tgz", - "integrity": "sha512-7vsMc/Lty6AGnn7uFpYT56QesI5D2Y/UkgKounk87OP9Z2H9Z8kj6jzcSGAxFmUtDOS0ntK6lbQz+Nsa0Jj6mQ==", + "version": "3.41.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.41.0.tgz", + "integrity": "sha512-SJ4/EHwS36QMJd6h/Rg+GyR4A5xE0FSI3eZ+iBVpfqf1x0eTSg1smWLHrA+2jQThZSh97fmSgFSU8B61nxosxA==", "dev": true }, "core-js-compat": { @@ -40133,9 +40121,9 @@ } }, "devtools-protocol": { - "version": "0.0.1402036", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1402036.tgz", - "integrity": "sha512-JwAYQgEvm3yD45CHB+RmF5kMbWtXBaOGwuxa87sZogHcLCv8c/IqnThaoQ1y60d7pXWjSKWQphPEc+1rAScVdg==", + "version": "0.0.1413902", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1413902.tgz", + "integrity": "sha512-yRtvFD8Oyk7C9Os3GmnFZLu53yAfsnyw1s+mLmHHUK0GQEc9zthHWvS1r67Zqzm5t7v56PILHIVZ7kmFMaL2yQ==", "dev": true }, "diff-sequences": { @@ -40651,17 +40639,18 @@ } }, "eslint": { - "version": "9.21.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.21.0.tgz", - "integrity": "sha512-KjeihdFqTPhOMXTt7StsDxriV4n66ueuF/jfPNC3j/lduHwr/ijDwJMsF+wyMJethgiKi5wniIE243vi07d3pg==", + "version": "9.22.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.22.0.tgz", + "integrity": "sha512-9V/QURhsRN40xuHXWjV64yvrzMjcz7ZyNoF2jJFmy9j/SLk0u1OLSZgXi28MrXjymnjEGSR80WCdab3RGMDveQ==", "dev": true, "requires": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", "@eslint/config-array": "^0.19.2", + "@eslint/config-helpers": "^0.1.0", "@eslint/core": "^0.12.0", "@eslint/eslintrc": "^3.3.0", - "@eslint/js": "9.21.0", + "@eslint/js": "9.22.0", "@eslint/plugin-kit": "^0.2.7", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", @@ -40673,7 +40662,7 @@ "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^8.2.0", + "eslint-scope": "^8.3.0", "eslint-visitor-keys": "^4.2.0", "espree": "^10.3.0", "esquery": "^1.5.0", @@ -40692,12 +40681,6 @@ "optionator": "^0.9.3" }, "dependencies": { - "@eslint/js": { - "version": "9.21.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.21.0.tgz", - "integrity": "sha512-BqStZ3HX8Yz6LvsF5ByXYrtigrV5AXADWLAGc7PH/1SxOb7/FIYYMszZZWiUou/GB9P2lXWk2SV4d+Z8h0nknw==", - "dev": true - }, "ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", @@ -40739,9 +40722,9 @@ "dev": true }, "eslint-scope": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.2.0.tgz", - "integrity": "sha512-PHlWUfG6lvPc3yvP5A4PNyBL1W8fkDUccmI21JUu/+GKZBoH/W5u6usENXUrWFRsyoW5ACUjFGgAFQp5gUlb/A==", + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.3.0.tgz", + "integrity": "sha512-pUNxi75F8MJ/GdeKtVLSbYg4ZI34J6C0C7sbL4YOp2exGwen7ZsuBqKzUhXd0qMQ362yET3z+uPwKeg/0C2XCQ==", "dev": true, "requires": { "esrecurse": "^4.3.0", @@ -40849,9 +40832,9 @@ } }, "eslint-plugin-jsdoc": { - "version": "50.6.3", - "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-50.6.3.tgz", - "integrity": "sha512-NxbJyt1M5zffPcYZ8Nb53/8nnbIScmiLAMdoe0/FAszwb7lcSiX3iYBTsuF7RV84dZZJC8r3NghomrUXsmWvxQ==", + "version": "50.6.6", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-50.6.6.tgz", + "integrity": "sha512-4jLo9NZqHfyNtiBxAU293eX1xi6oUIBcAxJJL/hHeeNhh26l4l/Apmu0x9SarvSQ/gWNOrnFci4DSPupN4//WA==", "dev": true, "requires": { "@es-joy/jsdoccomment": "~0.49.0", @@ -45988,9 +45971,9 @@ } }, "lint-staged": { - "version": "15.4.3", - "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.4.3.tgz", - "integrity": "sha512-FoH1vOeouNh1pw+90S+cnuoFwRfUD9ijY2GKy5h7HS3OR7JVir2N2xrsa0+Twc1B7cW72L+88geG5cW4wIhn7g==", + "version": "15.5.0", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.5.0.tgz", + "integrity": "sha512-WyCzSbfYGhK7cU+UuDDkzUiytbfbi0ZdPy2orwtM75P3WTtQBzmG40cCxIa8Ii2+XjfxzLH6Be46tUfWS85Xfg==", "dev": true, "requires": { "chalk": "^5.4.1", @@ -49571,9 +49554,9 @@ "dev": true }, "pac-proxy-agent": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.1.0.tgz", - "integrity": "sha512-Z5FnLVVZSnX7WjBg0mhDtydeRZ1xMcATZThjySQUHqr+0ksP8kqaw23fNKkaaN/Z8gwLUs/W7xdl0I75eP2Xyw==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz", + "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==", "dev": true, "requires": { "@tootallnate/quickjs-emscripten": "^0.23.0", @@ -50681,31 +50664,31 @@ "dev": true }, "puppeteer": { - "version": "24.2.1", - "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-24.2.1.tgz", - "integrity": "sha512-Euno62ou0cd0dTkOYTNioSOsFF4VpSnz4ldD38hi9ov9xCNtr8DbhmoJRUx+V9OuPgecueZbKOohRrnrhkbg3Q==", + "version": "24.4.0", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-24.4.0.tgz", + "integrity": "sha512-E4JhJzjS8AAI+6N/b+Utwarhz6zWl3+MR725fal+s3UlOlX2eWdsvYYU+Q5bXMjs9eZEGkNQroLkn7j11s2k1Q==", "dev": true, "requires": { - "@puppeteer/browsers": "2.7.1", - "chromium-bidi": "1.3.0", + "@puppeteer/browsers": "2.8.0", + "chromium-bidi": "2.1.2", "cosmiconfig": "^9.0.0", - "devtools-protocol": "0.0.1402036", - "puppeteer-core": "24.2.1", + "devtools-protocol": "0.0.1413902", + "puppeteer-core": "24.4.0", "typed-query-selector": "^2.12.0" } }, "puppeteer-core": { - "version": "24.2.1", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.2.1.tgz", - "integrity": "sha512-bCypUh3WXzETafv1TCFAjIUnI8BiQ/d+XvEfEXDLcIMm9CAvROqnBmbt79yBjwasoDZsgfXnUmIJU7Y27AalVQ==", + "version": "24.4.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.4.0.tgz", + "integrity": "sha512-eFw66gCnWo0X8Hyf9KxxJtms7a61NJVMiSaWfItsFPzFBsjsWdmcNlBdsA1WVwln6neoHhsG+uTVesKmTREn/g==", "dev": true, "requires": { - "@puppeteer/browsers": "2.7.1", - "chromium-bidi": "1.3.0", + "@puppeteer/browsers": "2.8.0", + "chromium-bidi": "2.1.2", "debug": "^4.4.0", - "devtools-protocol": "0.0.1402036", + "devtools-protocol": "0.0.1413902", "typed-query-selector": "^2.12.0", - "ws": "^8.18.0" + "ws": "^8.18.1" } }, "pure-rand": { @@ -53354,14 +53337,14 @@ "dev": true }, "typescript-eslint": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.25.0.tgz", - "integrity": "sha512-TxRdQQLH4g7JkoFlYG3caW5v1S6kEkz8rqt80iQJZUYPq1zD1Ra7HfQBJJ88ABRaMvHAXnwRvRB4V+6sQ9xN5Q==", + "version": "8.26.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.26.0.tgz", + "integrity": "sha512-PtVz9nAnuNJuAVeUFvwztjuUgSnJInODAUx47VDwWPXzd5vismPOtPtt83tzNXyOjVQbPRp786D6WFW/M2koIA==", "dev": true, "requires": { - "@typescript-eslint/eslint-plugin": "8.25.0", - "@typescript-eslint/parser": "8.25.0", - "@typescript-eslint/utils": "8.25.0" + "@typescript-eslint/eslint-plugin": "8.26.0", + "@typescript-eslint/parser": "8.26.0", + "@typescript-eslint/utils": "8.26.0" } }, "uc.micro": { diff --git a/package.json b/package.json index 63342724b..cee4bb8e2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "parse", - "version": "6.0.0", + "version": "6.1.0-alpha.3", "description": "Parse JavaScript SDK", "homepage": "https://parseplatform.org", "keywords": [ @@ -21,15 +21,17 @@ "weapp.js", "dist/", "lib/", + "types/", "LICENSE", "NOTICE", "README.md" ], + "types": "types/index.d.ts", "browser": { "react-native": false }, "dependencies": { - "@babel/runtime-corejs3": "7.26.9", + "@babel/runtime-corejs3": "7.26.10", "idb-keyval": "6.2.1", "react-native-crypto-js": "1.0.0", "uuid": "10.0.0", @@ -37,13 +39,13 @@ "xmlhttprequest": "1.8.0" }, "devDependencies": { - "@babel/core": "7.26.9", + "@babel/core": "7.26.10", "@babel/plugin-proposal-class-properties": "7.18.6", - "@babel/plugin-transform-runtime": "7.26.9", + "@babel/plugin-transform-runtime": "7.26.10", "@babel/preset-env": "7.26.9", "@babel/preset-react": "7.26.3", "@babel/preset-typescript": "7.26.0", - "@eslint/js": "9.18.0", + "@eslint/js": "9.22.0", "@parse/minami": "git+https://github.com/parse-community/minami#main", "@saithodev/semantic-release-backmerge": "4.0.1", "@semantic-release/changelog": "6.0.3", @@ -59,11 +61,11 @@ "babel-plugin-transform-inline-environment-variables": "0.4.4", "browserify": "17.0.0", "codecov": "3.8.3", - "core-js": "3.40.0", + "core-js": "3.41.0", "cross-env": "7.0.2", - "eslint": "9.21.0", + "eslint": "9.22.0", "eslint-plugin-expect-type": "0.6.2", - "eslint-plugin-jsdoc": "50.6.3", + "eslint-plugin-jsdoc": "50.6.6", "express": "4.21.2", "gulp": "5.0.0", "gulp-babel": "8.0.0", @@ -80,16 +82,16 @@ "jest-environment-jsdom": "29.7.0", "jsdoc": "4.0.4", "jsdoc-babel": "0.5.0", - "lint-staged": "15.4.3", + "lint-staged": "15.5.0", "madge": "8.0.0", "metro-react-native-babel-preset": "0.77.0", "mongodb-runner": "5.8.0", "parse-server": "7.3.0", "prettier": "3.5.2", - "puppeteer": "24.2.1", + "puppeteer": "24.4.0", "regenerator-runtime": "0.14.1", "semantic-release": "24.2.3", - "typescript-eslint": "8.25.0", + "typescript-eslint": "8.26.0", "vinyl-source-stream": "2.0.0" }, "optionalDependencies": { @@ -97,7 +99,8 @@ }, "scripts": { "build": "node build_releases.js", - "build:types": "tsc && prettier --write 'types/{**/*,*}.ts' && npm run lint:fix", + "build:types": "tsc", + "ci:typecheck": "node ./ci/typecheck.js", "release": "node build_releases.js && npm publish", "test": "cross-env PARSE_BUILD=node jest", "test:mongodb": "npm run test:mongodb:runnerstart && npm run integration", @@ -105,11 +108,12 @@ "posttest:mongodb": "mongodb-runner stop --all", "lint": "eslint --cache src/ integration/", "lint:fix": "eslint --fix --cache src/ integration/", - "test:types": "eslint --cache types/tests.ts -c eslint.config.test.mjs", + "test:types": "eslint types/tests.ts -c eslint.config.test.mjs", "watch": "cross-env PARSE_BUILD=${PARSE_BUILD} gulp watch", "watch:browser": "cross-env PARSE_BUILD=browser npm run watch", "watch:node": "cross-env PARSE_BUILD=node npm run watch", "watch:react-native": "cross-env PARSE_BUILD=react-native npm run watch", + "watch:ts": "tsc --watch", "integration": "cross-env TESTING=1 jasmine --config=jasmine.json", "docs": "jsdoc -c ./jsdoc-conf.json ./src", "madge:circular": "madge ./src --extensions js,ts --circular", diff --git a/src/AnonymousUtils.ts b/src/AnonymousUtils.ts index 99584c43f..db5041e72 100644 --- a/src/AnonymousUtils.ts +++ b/src/AnonymousUtils.ts @@ -44,7 +44,7 @@ const AnonymousUtils = { * linked to an anonymous user. * @static */ - isLinked(user: ParseUser) { + isLinked(user: ParseUser): boolean { const provider = this._getAuthProvider(); return user._isLinked(provider.getAuthType()); }, diff --git a/src/Cloud.ts b/src/Cloud.ts index 32678ddd0..c8fd781ad 100644 --- a/src/Cloud.ts +++ b/src/Cloud.ts @@ -37,7 +37,15 @@ import type { RequestOptions } from './RESTController'; * @returns {Promise} A promise that will be resolved with the result * of the function. */ -export function run(name: string, data: any, options: RequestOptions): Promise { +export function run any>( + name: string, + data?: null, + options?: RequestOptions +): 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 { if (typeof name !== 'string' || name.length === 0) { throw new TypeError('Cloud function name must be a string.'); } @@ -88,7 +96,7 @@ export function getJobStatus(jobStatusId: string): Promise { } const DefaultController = { - run(name: string, data: any, options: RequestOptions) { + run(name: string, data: any, options?: RequestOptions): Promise { const RESTController = CoreManager.getRESTController(); const payload = encode(data, true); @@ -105,12 +113,12 @@ const DefaultController = { }); }, - getJobsData(options: RequestOptions) { + getJobsData(options?: RequestOptions): Promise { const RESTController = CoreManager.getRESTController(); return RESTController.request('GET', 'cloud_code/jobs/data', null, options); }, - async startJob(name: string, data: any, options: RequestOptions) { + async startJob(name: string, data: any, options?: RequestOptions): Promise { const RESTController = CoreManager.getRESTController(); const payload = encode(data, true); diff --git a/src/CoreManager.ts b/src/CoreManager.ts index 4f9ccea13..f6889174a 100644 --- a/src/CoreManager.ts +++ b/src/CoreManager.ts @@ -13,17 +13,16 @@ import type ParseSession from './ParseSession'; import type { HookDeclaration, HookDeleteArg } from './ParseHooks'; import type ParseConfig from './ParseConfig'; import type LiveQueryClient from './LiveQueryClient'; -import type ParseSchema from './ParseSchema'; import type ParseInstallation from './ParseInstallation'; type AnalyticsController = { track: (name: string, dimensions: { [key: string]: string }) => Promise; }; type CloudController = { - run: (name: string, data: any, options: RequestOptions) => Promise; - getJobsData: (options: RequestOptions) => Promise; + run: (name: string, data: any, options?: RequestOptions) => Promise; + getJobsData: (options?: RequestOptions) => Promise; /** Returns promise which resolves with JobStatusId of the job */ - startJob: (name: string, data: any, options: RequestOptions) => Promise; + startJob: (name: string, data: any, options?: RequestOptions) => Promise; }; type ConfigController = { current: () => Promise | ParseConfig; @@ -56,15 +55,15 @@ type ObjectController = { fetch: ( object: ParseObject | Array, forceFetch: boolean, - options: RequestOptions + options?: RequestOptions ) => Promise | ParseObject | undefined>; save: ( object: ParseObject | Array | null, - options: RequestOptions + options?: RequestOptions ) => Promise | ParseFile | undefined>; destroy: ( object: ParseObject | Array, - options: RequestOptions + options?: RequestOptions ) => Promise>; }; type ObjectStateController = { @@ -93,18 +92,52 @@ type QueryController = { find( className: string, params: QueryJSON, - options: RequestOptions + options?: RequestOptions ): Promise<{ results?: Array; className?: string; count?: number }>; aggregate( className: string, params: any, - options: RequestOptions + options?: RequestOptions ): Promise<{ results?: Array }>; }; -type EventuallyQueue = { - save: (object: ParseObject, serverOptions: SaveOptions) => Promise; - destroy: (object: ParseObject, serverOptions: RequestOptions) => Promise; - poll: (ms?: number) => void; +export type QueueObject = { + queueId: string; + action: string; + object: ParseObject; + serverOptions: SaveOptions | RequestOptions; + id: string; + className: string; + hash: string; + createdAt: Date; +}; +export type Queue = Array; +export type EventuallyQueue = { + save: (object: ParseObject, serverOptions?: SaveOptions) => Promise; + destroy: (object: ParseObject, serverOptions?: RequestOptions) => Promise; + generateQueueId: (action: string, object: ParseObject) => string; + enqueue( + action: string, + object: ParseObject, + serverOptions?: SaveOptions | RequestOptions + ): Promise; + store(data: Queue): Promise; + load(): Promise; + getQueue(): Promise; + setQueue(queue: Queue): Promise; + remove(queueId: string): Promise; + clear(): Promise; + queueItemExists(queue: Queue, queueId: string): number; + length(): Promise; + sendQueue(): Promise; + sendQueueCallback(object: ParseObject, queueObject: QueueObject): Promise; + poll(ms?: number): void; + stopPoll(): void; + isPolling(): boolean; + process: { + create(ObjectType: any, queueObject: any): Promise; + byId(ObjectType: any, queueObject: any): Promise; + byHash(ObjectType: any, queueObject: any): Promise; + }; }; type RESTController = { request: (method: string, path: string, data?: any, options?: RequestOptions) => Promise; @@ -119,14 +152,14 @@ type RESTController = { }; type SchemaController = { purge: (className: string) => Promise; - get: (className: string, options?: RequestOptions) => Promise<{ results: ParseSchema[] }>; + get: (className: string, options?: RequestOptions) => Promise; delete: (className: string, options?: RequestOptions) => Promise; create: (className: string, params: any, options?: RequestOptions) => Promise; update: (className: string, params: any, options?: RequestOptions) => Promise; - send(className: string, method: string, params: any, options: RequestOptions): Promise; + send(className: string, method: string, params: any, options?: RequestOptions): Promise; }; type SessionController = { - getSession: (token: RequestOptions) => Promise; + getSession: (options?: RequestOptions) => Promise; }; type StorageController = | { @@ -166,24 +199,24 @@ type UserController = { setCurrentUser: (user: ParseUser) => Promise; currentUser: () => ParseUser | null; currentUserAsync: () => Promise; - signUp: (user: ParseUser, attrs: AttributeMap, options: RequestOptions) => Promise; - logIn: (user: ParseUser, options: RequestOptions) => Promise; + signUp: (user: ParseUser, attrs: AttributeMap, options?: RequestOptions) => Promise; + logIn: (user: ParseUser, options?: RequestOptions) => Promise; loginAs: (user: ParseUser, userId: string) => Promise; - become: (user: ParseUser, options: RequestOptions) => Promise; + become: (user: ParseUser, options?: RequestOptions) => Promise; hydrate: (user: ParseUser, userJSON: AttributeMap) => Promise; - logOut: (options: RequestOptions) => Promise; - me: (user: ParseUser, options: RequestOptions) => Promise; - requestPasswordReset: (email: string, options: RequestOptions) => Promise; + logOut: (options?: RequestOptions) => Promise; + me: (user: ParseUser, options?: RequestOptions) => Promise; + requestPasswordReset: (email: string, options?: RequestOptions) => Promise; updateUserOnDisk: (user: ParseUser) => Promise; - upgradeToRevocableSession: (user: ParseUser, options: RequestOptions) => Promise; + upgradeToRevocableSession: (user: ParseUser, options?: RequestOptions) => Promise; linkWith: (user: ParseUser, authData: AuthData, options?: FullOptions) => Promise; removeUserFromDisk: () => Promise; verifyPassword: ( username: string, password: string, - options: RequestOptions + options?: RequestOptions ) => Promise; - requestEmailVerification: (email: string, options: RequestOptions) => Promise; + requestEmailVerification: (email: string, options?: RequestOptions) => Promise; }; type HooksController = { get: (type: string, functionName?: string, triggerName?: string) => Promise; @@ -320,6 +353,7 @@ const config: Config & { [key: string]: any } = { VERSION: 'js' + require('../package.json').version, APPLICATION_ID: null, JAVASCRIPT_KEY: null, + MAINTENANCE_KEY: null, MASTER_KEY: null, USE_MASTER_KEY: false, PERFORM_USER_REWRITE: true, @@ -687,5 +721,4 @@ const CoreManager = { }, }; -module.exports = CoreManager; export default CoreManager; diff --git a/src/CryptoController.ts b/src/CryptoController.ts index 211c5d283..14c1ea2b3 100644 --- a/src/CryptoController.ts +++ b/src/CryptoController.ts @@ -22,5 +22,4 @@ const CryptoController = { }, }; -module.exports = CryptoController; export default CryptoController; diff --git a/src/EventEmitter.ts b/src/EventEmitter.ts index 4f965641f..d0adf68d0 100644 --- a/src/EventEmitter.ts +++ b/src/EventEmitter.ts @@ -17,5 +17,5 @@ try { } catch (_) { // EventEmitter unavailable } -module.exports = EventEmitter; + export default EventEmitter; diff --git a/src/EventuallyQueue.ts b/src/EventuallyQueue.ts index a4cdb0ed8..972d297c0 100644 --- a/src/EventuallyQueue.ts +++ b/src/EventuallyQueue.ts @@ -4,24 +4,12 @@ import ParseObject from './ParseObject'; import ParseQuery from './ParseQuery'; import Storage from './Storage'; +import type { Queue, QueueObject } from './CoreManager'; import type { SaveOptions } from './ParseObject'; import type { RequestOptions } from './RESTController'; -type QueueObject = { - queueId: string; - action: string; - object: ParseObject; - serverOptions: SaveOptions | RequestOptions; - id: string; - className: string; - hash: string; - createdAt: Date; -}; - -type Queue = Array; - const QUEUE_KEY = 'Parse/Eventually/Queue'; -let queueCache: QueueObject[] = []; +let queueCache: Queue = []; let dirtyCache = true; let polling: ReturnType | undefined = undefined; @@ -44,7 +32,7 @@ const EventuallyQueue = { * @static * @see Parse.Object#saveEventually */ - save(object: ParseObject, serverOptions: SaveOptions = {}): Promise { + save(object: ParseObject, serverOptions?: SaveOptions): Promise { return this.enqueue('save', object, serverOptions); }, @@ -59,7 +47,7 @@ const EventuallyQueue = { * @static * @see Parse.Object#destroyEventually */ - destroy(object: ParseObject, serverOptions: RequestOptions = {}): Promise { + destroy(object: ParseObject, serverOptions?: RequestOptions): Promise { return this.enqueue('destroy', object, serverOptions); }, @@ -92,7 +80,7 @@ const EventuallyQueue = { async enqueue( action: string, object: ParseObject, - serverOptions: SaveOptions | RequestOptions + serverOptions?: SaveOptions | RequestOptions ): Promise { const queueData = await this.getQueue(); const queueId = this.generateQueueId(action, object); @@ -112,7 +100,7 @@ const EventuallyQueue = { queueId, action, object: object.toJSON(), - serverOptions, + serverOptions: serverOptions || {}, id: object.id, className: object.className, hash: object.get('hash'), @@ -121,11 +109,11 @@ const EventuallyQueue = { return this.setQueue(queueData); }, - store(data: QueueObject[]) { + store(data: Queue): Promise { return Storage.setItemAsync(QUEUE_KEY, JSON.stringify(data)); }, - load() { + load(): Promise { return Storage.getItemAsync(QUEUE_KEY); }, @@ -134,10 +122,10 @@ const EventuallyQueue = { * * @function getQueue * @name Parse.EventuallyQueue.getQueue - * @returns {Promise} + * @returns {Promise} * @static */ - async getQueue(): Promise { + async getQueue(): Promise { if (dirtyCache) { queueCache = JSON.parse((await this.load()) || '[]'); dirtyCache = false; @@ -297,7 +285,7 @@ const EventuallyQueue = { * @param [ms] Milliseconds to ping the server. Default 2000ms * @static */ - poll(ms = 2000) { + poll(ms?: number): void { if (polling) { return; } @@ -311,7 +299,7 @@ const EventuallyQueue = { } }) .catch(e => e); - }, ms); + }, ms || 2000); }, /** @@ -321,7 +309,7 @@ const EventuallyQueue = { * @name Parse.EventuallyQueue.stopPoll * @static */ - stopPoll() { + stopPoll(): void { clearInterval(polling); polling = undefined; }, @@ -367,5 +355,4 @@ const EventuallyQueue = { }, }; -module.exports = EventuallyQueue; export default EventuallyQueue; diff --git a/src/FacebookUtils.ts b/src/FacebookUtils.ts index f789bd17d..b90c65b94 100644 --- a/src/FacebookUtils.ts +++ b/src/FacebookUtils.ts @@ -1,11 +1,11 @@ /* global FB */ import ParseUser from './ParseUser'; -import type { AuthProviderType } from './ParseUser'; +import type { AuthProvider } from './ParseUser'; let initialized = false; let requestedPermissions; let initOptions; -const provider: AuthProviderType = { +const provider: AuthProvider = { authenticate(options) { if (typeof FB === 'undefined') { options.error(this, 'Facebook SDK not found.'); @@ -227,7 +227,7 @@ const FacebookUtils = { }, // Used for testing purposes - _getAuthProvider() { + _getAuthProvider(): AuthProvider { return provider; }, }; diff --git a/src/IndexedDBStorageController.ts b/src/IndexedDBStorageController.ts index 30a6726f6..ff1e80d7a 100644 --- a/src/IndexedDBStorageController.ts +++ b/src/IndexedDBStorageController.ts @@ -34,5 +34,5 @@ if (typeof window !== 'undefined' && window.indexedDB) { // IndexedDB not supported IndexedDBStorageController = undefined; } -module.exports = IndexedDBStorageController; + export default IndexedDBStorageController; diff --git a/src/InstallationController.ts b/src/InstallationController.ts index 782e5f659..ebf25db80 100644 --- a/src/InstallationController.ts +++ b/src/InstallationController.ts @@ -77,5 +77,4 @@ const InstallationController = { }, }; -module.exports = InstallationController; export default InstallationController; diff --git a/src/LiveQuerySubscription.ts b/src/LiveQuerySubscription.ts index 6b4c8a0c1..79a59d822 100644 --- a/src/LiveQuerySubscription.ts +++ b/src/LiveQuerySubscription.ts @@ -1,6 +1,7 @@ import CoreManager from './CoreManager'; import { resolvingPromise } from './promiseUtils'; import type ParseQuery from './ParseQuery'; +import type { EventEmitter } from 'events'; /** * Creates a new LiveQuery Subscription. @@ -84,16 +85,16 @@ import type ParseQuery from './ParseQuery'; * * });

*/ -class Subscription { +class LiveQuerySubscription { id: string | number; query: ParseQuery; sessionToken?: string; subscribePromise: any; unsubscribePromise: any; subscribed: boolean; - emitter: any; - on: any; - emit: any; + emitter: EventEmitter; + on: EventEmitter['on']; + emit: EventEmitter['emit']; /* * @param {string | number} id - subscription id * @param {string} query - query to subscribe to @@ -106,8 +107,8 @@ class Subscription { this.subscribePromise = resolvingPromise(); this.unsubscribePromise = resolvingPromise(); this.subscribed = false; - const EventEmitter = CoreManager.getEventEmitter(); - this.emitter = new EventEmitter(); + const Emitter = CoreManager.getEventEmitter(); + this.emitter = new Emitter(); this.on = (eventName, listener) => this.emitter.on(eventName, listener); this.emit = (eventName, ...args) => this.emitter.emit(eventName, ...args); @@ -131,4 +132,4 @@ class Subscription { } } -export default Subscription; +export default LiveQuerySubscription; diff --git a/src/LocalDatastore.ts b/src/LocalDatastore.ts index 4720d7f02..069a44c48 100644 --- a/src/LocalDatastore.ts +++ b/src/LocalDatastore.ts @@ -387,7 +387,6 @@ const LocalDatastore = { }, }; -module.exports = LocalDatastore; export default LocalDatastore; CoreManager.setLocalDatastoreController(LocalDatastoreController); diff --git a/src/LocalDatastoreController.default.ts b/src/LocalDatastoreController.default.ts index 29a1c36c8..80bbba421 100644 --- a/src/LocalDatastoreController.default.ts +++ b/src/LocalDatastoreController.default.ts @@ -61,5 +61,4 @@ const LocalDatastoreController = { }, }; -module.exports = LocalDatastoreController; export default LocalDatastoreController; diff --git a/src/LocalDatastoreController.react-native.ts b/src/LocalDatastoreController.react-native.ts index e877d30e6..c555bffb2 100644 --- a/src/LocalDatastoreController.react-native.ts +++ b/src/LocalDatastoreController.react-native.ts @@ -80,5 +80,4 @@ const LocalDatastoreController = { }, }; -module.exports = LocalDatastoreController; export default LocalDatastoreController; diff --git a/src/LocalDatastoreController.ts b/src/LocalDatastoreController.ts index f0acfea5b..7f4e969ba 100644 --- a/src/LocalDatastoreController.ts +++ b/src/LocalDatastoreController.ts @@ -6,5 +6,5 @@ let LocalDatastoreController: any = DefaultLocalDatastoreController; if (process.env.PARSE_BUILD === 'react-native') { LocalDatastoreController = RNLocalDatastoreController; } -module.exports = LocalDatastoreController; + export default LocalDatastoreController; diff --git a/src/OfflineQuery.ts b/src/OfflineQuery.ts index 17e80aeb5..7ffe18a1c 100644 --- a/src/OfflineQuery.ts +++ b/src/OfflineQuery.ts @@ -591,5 +591,4 @@ const OfflineQuery = { validateQuery: validateQuery, }; -module.exports = OfflineQuery; export default OfflineQuery; diff --git a/src/Parse.ts b/src/Parse.ts index 0041b3d1e..32e096c97 100644 --- a/src/Parse.ts +++ b/src/Parse.ts @@ -1,7 +1,7 @@ import decode from './decode'; import encode from './encode'; import CryptoController from './CryptoController'; -import EventuallyQueue from './EventuallyQueue'; +import EQ from './EventuallyQueue'; import IndexedDBStorageController from './IndexedDBStorageController'; import InstallationController from './InstallationController'; import * as ParseOp from './ParseOp'; @@ -36,6 +36,7 @@ import LiveQueryClient from './LiveQueryClient'; import LocalDatastoreController from './LocalDatastoreController'; import StorageController from './StorageController'; import WebSocketController from './WebSocketController'; +import type { EventuallyQueue } from './CoreManager'; const Parse = { ACL, @@ -79,11 +80,11 @@ const Parse = { * @member {EventuallyQueue} Parse.EventuallyQueue * @static */ - set EventuallyQueue(queue: typeof EventuallyQueue) { + set EventuallyQueue(queue: EventuallyQueue) { CoreManager.setEventuallyQueue(queue); }, - get EventuallyQueue(): any { + get EventuallyQueue(): EventuallyQueue { return CoreManager.getEventuallyQueue(); }, @@ -109,15 +110,21 @@ const Parse = { Parse._initialize(applicationId, javaScriptKey); }, - _initialize(applicationId: string, javaScriptKey: string, masterKey?: string) { + _initialize( + applicationId: string, + javaScriptKey: string, + masterKey?: string, + maintenanceKey?: string + ) { CoreManager.set('APPLICATION_ID', applicationId); CoreManager.set('JAVASCRIPT_KEY', javaScriptKey); + CoreManager.set('MAINTENANCE_KEY', maintenanceKey); CoreManager.set('MASTER_KEY', masterKey); CoreManager.set('USE_MASTER_KEY', false); CoreManager.setIfNeeded('EventEmitter', EventEmitter); CoreManager.setIfNeeded('LiveQuery', new ParseLiveQuery()); CoreManager.setIfNeeded('CryptoController', CryptoController); - CoreManager.setIfNeeded('EventuallyQueue', EventuallyQueue); + CoreManager.setIfNeeded('EventuallyQueue', EQ); CoreManager.setIfNeeded('InstallationController', InstallationController); CoreManager.setIfNeeded('LocalDatastoreController', LocalDatastoreController); CoreManager.setIfNeeded('StorageController', StorageController); @@ -197,6 +204,17 @@ const Parse = { return CoreManager.get('MASTER_KEY'); }, + /** + * @member {string} Parse.maintenanceKey + * @static + */ + set maintenanceKey(value) { + CoreManager.set('MAINTENANCE_KEY', value); + }, + get maintenanceKey() { + return CoreManager.get('MAINTENANCE_KEY'); + }, + /** * @member {string} Parse.serverURL * @static @@ -342,7 +360,7 @@ const Parse = { * @static * @returns {boolean} */ - isLocalDatastoreEnabled() { + isLocalDatastoreEnabled(): boolean { return this.LocalDatastore.isEnabled; }, /** diff --git a/src/ParseACL.ts b/src/ParseACL.ts index aab488941..5e07772fa 100644 --- a/src/ParseACL.ts +++ b/src/ParseACL.ts @@ -25,9 +25,9 @@ class ParseACL { permissionsById: ByIdMap; /** - * @param {(Parse.User | object)} arg1 The user to initialize the ACL for + * @param {(Parse.User | object | null)} arg1 The user to initialize the ACL for */ - constructor(arg1: ParseUser | ByIdMap) { + constructor(arg1?: ParseUser | ByIdMap | null) { this.permissionsById = {}; if (arg1 && typeof arg1 === 'object') { const ParseUser = CoreManager.getParseUser(); diff --git a/src/ParseConfig.ts b/src/ParseConfig.ts index 1689ead30..6bdd38807 100644 --- a/src/ParseConfig.ts +++ b/src/ParseConfig.ts @@ -77,7 +77,7 @@ class ParseConfig { * @returns {Promise} A promise that is resolved with a newly-created * configuration object when the get completes. */ - static get(options: RequestOptions = {}) { + static get(options?: RequestOptions) { const controller = CoreManager.getConfigController(); return controller.get(options); } @@ -166,7 +166,7 @@ const DefaultController = { }); }, - get(options: RequestOptions = {}) { + get(options?: RequestOptions) { const RESTController = CoreManager.getRESTController(); return RESTController.request('GET', 'config', {}, options).then(response => { diff --git a/src/ParseFile.ts b/src/ParseFile.ts index 681039d28..d53c8f947 100644 --- a/src/ParseFile.ts +++ b/src/ParseFile.ts @@ -68,8 +68,8 @@ class ParseFile { _previousSave?: Promise; _data?: string; _requestTask?: any; - _metadata?: object; - _tags?: object; + _metadata?: Record; + _tags?: Record; /** * @param name {String} The file's name. This will be prefixed by a unique @@ -205,7 +205,7 @@ class ParseFile { * * @returns {object} */ - metadata() { + metadata(): Record { return this._metadata; } @@ -214,7 +214,7 @@ class ParseFile { * * @returns {object} */ - tags() { + tags(): Record { return this._tags; } @@ -357,7 +357,7 @@ class ParseFile { * * @param {object} metadata Key value pairs to be stored with file object */ - setMetadata(metadata: any) { + setMetadata(metadata: Record) { if (metadata && typeof metadata === 'object') { Object.keys(metadata).forEach(key => { this.addMetadata(key, metadata[key]); @@ -382,7 +382,7 @@ class ParseFile { * * @param {object} tags Key value pairs to be stored with file object */ - setTags(tags: any) { + setTags(tags: Record) { if (tags && typeof tags === 'object') { Object.keys(tags).forEach(key => { this.addTag(key, tags[key]); diff --git a/src/ParseGeoPoint.ts b/src/ParseGeoPoint.ts index 979abb693..230384473 100644 --- a/src/ParseGeoPoint.ts +++ b/src/ParseGeoPoint.ts @@ -31,7 +31,7 @@ class ParseGeoPoint { * @param {number} arg2 The longitude of the GeoPoint */ constructor( - arg1: Array | { latitude: number; longitude: number } | number, + arg1?: [number, number] | { latitude: number; longitude: number } | number, arg2?: number ) { if (Array.isArray(arg1)) { diff --git a/src/ParseInstallation.ts b/src/ParseInstallation.ts index 465d59175..8110e4a78 100644 --- a/src/ParseInstallation.ts +++ b/src/ParseInstallation.ts @@ -1,8 +1,7 @@ import CoreManager from './CoreManager'; import ParseError from './ParseError'; -import ParseObject from './ParseObject'; - -import type { AttributeMap } from './ObjectStateMutations'; +import ParseObject, { Attributes } from './ParseObject'; +import type { AttributeKey } from './ParseObject'; type DeviceInterface = { IOS: string; @@ -33,15 +32,15 @@ const DEVICE_TYPES: DeviceInterface = { * * @alias Parse.Installation */ -class ParseInstallation extends ParseObject { +class ParseInstallation extends ParseObject { /** * @param {object} attributes The initial set of data to store in the object. */ - constructor(attributes?: AttributeMap) { + constructor(attributes?: T) { super('_Installation'); if (attributes && typeof attributes === 'object') { try { - this.set(attributes || {}); + this.set((attributes || {}) as any); } catch (_) { throw new Error("Can't create an invalid Installation"); } @@ -56,7 +55,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get appIdentifier() { - return this.get('appIdentifier'); + return this.get('appIdentifier' as AttributeKey); } /** @@ -67,7 +66,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get appVersion() { - return this.get('appVersion'); + return this.get('appVersion' as AttributeKey); } /** @@ -78,7 +77,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get appName() { - return this.get('appName'); + return this.get('appName' as AttributeKey); } /** @@ -91,7 +90,7 @@ class ParseInstallation extends ParseObject { * @returns {number} */ get badge() { - return this.get('badge'); + return this.get('badge' as AttributeKey); } /** @@ -102,7 +101,7 @@ class ParseInstallation extends ParseObject { * @returns {string[]} */ get channels() { - return this.get('channels'); + return this.get('channels' as AttributeKey); } /** @@ -113,7 +112,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get deviceToken() { - return this.get('deviceToken'); + return this.get('deviceToken' as AttributeKey); } /** @@ -124,7 +123,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get deviceType() { - return this.get('deviceType'); + return this.get('deviceType' as AttributeKey); } /** @@ -135,7 +134,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get GCMSenderId() { - return this.get('GCMSenderId'); + return this.get('GCMSenderId' as AttributeKey); } /** @@ -146,7 +145,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get installationId() { - return this.get('installationId'); + return this.get('installationId' as AttributeKey); } /** @@ -157,7 +156,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get localeIdentifier() { - return this.get('localeIdentifier'); + return this.get('localeIdentifier' as AttributeKey); } /** @@ -168,7 +167,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get parseVersion() { - return this.get('parseVersion'); + return this.get('parseVersion' as AttributeKey); } /** @@ -179,7 +178,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get pushType() { - return this.get('pushType'); + return this.get('pushType' as AttributeKey); } /** @@ -190,7 +189,7 @@ class ParseInstallation extends ParseObject { * @returns {string} */ get timeZone() { - return this.get('timeZone'); + return this.get('timeZone' as AttributeKey); } /** @@ -220,7 +219,7 @@ class ParseInstallation extends ParseObject { * @param {...any} args * @returns {Promise} */ - async fetch(...args: Array): Promise { + async fetch(...args: Array): Promise { try { await super.fetch.apply(this, args); } catch (e) { @@ -234,7 +233,7 @@ class ParseInstallation extends ParseObject { this._markAllFieldsDirty(); await super.save.apply(this, args); } - await CoreManager.getInstallationController().updateInstallationOnDisk(this); + await CoreManager.getInstallationController().updateInstallationOnDisk(this as any); return this; } @@ -259,13 +258,13 @@ class ParseInstallation extends ParseObject { this._markAllFieldsDirty(); await super.save.apply(this, args); } - await CoreManager.getInstallationController().updateInstallationOnDisk(this); + await CoreManager.getInstallationController().updateInstallationOnDisk(this as any); return this; } _markAllFieldsDirty() { for (const [key, value] of Object.entries(this.attributes)) { - this.set(key, value); + this.set(key as AttributeKey, value); } } @@ -287,5 +286,4 @@ class ParseInstallation extends ParseObject { ParseObject.registerSubclass('_Installation', ParseInstallation); -module.exports = ParseInstallation; export default ParseInstallation; diff --git a/src/ParseLiveQuery.ts b/src/ParseLiveQuery.ts index 8c7e8188f..769e2cf1d 100644 --- a/src/ParseLiveQuery.ts +++ b/src/ParseLiveQuery.ts @@ -1,5 +1,6 @@ import LiveQueryClient from './LiveQueryClient'; import CoreManager from './CoreManager'; +import type { EventEmitter } from 'events'; function getLiveQueryClient(): Promise { return CoreManager.getLiveQueryController().getDefaultLiveQueryClient(); @@ -33,13 +34,13 @@ function getLiveQueryClient(): Promise { * @static */ class LiveQuery { - emitter: any; - on: any; - emit: any; + emitter: EventEmitter; + on: EventEmitter['on']; + emit: EventEmitter['emit']; constructor() { - const EventEmitter = CoreManager.getEventEmitter(); - this.emitter = new EventEmitter(); + const Emitter = CoreManager.getEventEmitter(); + this.emitter = new Emitter(); this.on = (eventName: string, listener: any) => this.emitter.on(eventName, listener); this.emit = (eventName: string, ...args: any) => this.emitter.emit(eventName, ...args); // adding listener so process does not crash diff --git a/src/ParseObject.ts b/src/ParseObject.ts index c53930757..059021384 100644 --- a/src/ParseObject.ts +++ b/src/ParseObject.ts @@ -29,6 +29,8 @@ import unsavedChildren from './unsavedChildren'; import type { AttributeMap, OpsMap } from './ObjectStateMutations'; import type { RequestOptions, FullOptions } from './RESTController'; +import type ParseGeoPoint from './ParseGeoPoint'; +import type ParsePolygon from './ParsePolygon'; export type Pointer = { __type: string; @@ -57,6 +59,49 @@ type FetchOptions = { context?: AttributeMap; }; +export type SetOptions = { + ignoreValidation?: boolean; + unset?: boolean; +}; + +export type AttributeKey = Extract; + +export interface Attributes { + [key: string]: any; +} + +interface JSONBaseAttributes { + objectId: string; + createdAt: string; + updatedAt: string; +} + +interface CommonAttributes { + ACL: ParseACL; +} + +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 + ? { __type: 'Date'; iso: string } + : T extends RegExp + ? string + : T extends Array + ? Array> + : T extends object + ? ToJSON + : T; + +type ToJSON = { + [K in keyof T]: Encode; +}; + // Mapping of class names to constructors, so we can populate objects from the // server with appropriate subclasses of ParseObject const classMap: AttributeMap = {}; @@ -100,7 +145,7 @@ function getServerUrlPath() { * * @alias Parse.Object */ -class ParseObject { +class ParseObject { /** * @param {string} className The class name for the object * @param {object} attributes The initial set of data to store in the object. @@ -109,8 +154,8 @@ class ParseObject { */ constructor( className?: string | { className: string; [attr: string]: any }, - attributes?: { [attr: string]: any }, - options?: { ignoreValidation: boolean } + attributes?: T, + options?: SetOptions ) { // Enable legacy initializers if (typeof this.initialize === 'function') { @@ -157,9 +202,9 @@ class ParseObject { /* Prototype getters / setters */ - get attributes(): AttributeMap { + get attributes(): T { const stateController = CoreManager.getObjectStateController(); - return Object.freeze(stateController.estimateAttributes(this._getStateIdentifier())); + return Object.freeze(stateController.estimateAttributes(this._getStateIdentifier())) as T; } /** @@ -213,7 +258,7 @@ class ParseObject { id = this._getId(); } return { - id: id, + id, className: this.className, }; } else { @@ -221,7 +266,7 @@ class ParseObject { } } - _getServerData(): AttributeMap { + _getServerData(): Attributes { const stateController = CoreManager.getObjectStateController(); return stateController.getServerData(this._getStateIdentifier()); } @@ -254,13 +299,13 @@ class ParseObject { }); } - _getDirtyObjectAttributes(): AttributeMap { + _getDirtyObjectAttributes(): Attributes { const attributes = this.attributes; const stateController = CoreManager.getObjectStateController(); const objectCache = stateController.getObjectCache(this._getStateIdentifier()); - const dirty = {}; + const dirty: Attributes = {}; for (const attr in attributes) { - const val = attributes[attr]; + const val: any = attributes[attr]; if ( val && typeof val === 'object' && @@ -286,14 +331,14 @@ class ParseObject { return dirty; } - _toFullJSON(seen?: Array, offline?: boolean): AttributeMap { - const json: { [key: string]: any } = this.toJSON(seen, offline); + _toFullJSON(seen?: Array, offline?: boolean): Attributes { + const json: Attributes = this.toJSON(seen, offline); json.__type = 'Object'; json.className = this.className; return json; } - _getSaveJSON(): AttributeMap { + _getSaveJSON(): Attributes { const pending = this._getPendingOps(); const dirtyObjects = this._getDirtyObjectAttributes(); const json = {}; @@ -347,7 +392,7 @@ class ParseObject { }; } - _finishFetch(serverData: AttributeMap) { + _finishFetch(serverData: Attributes) { if (!this.id && serverData.objectId) { this.id = serverData.objectId; } @@ -406,7 +451,7 @@ class ParseObject { } } - _handleSaveResponse(response: AttributeMap, status: number) { + _handleSaveResponse(response: Attributes, status: number) { const changes: Partial<{ createdAt: string; updatedAt: string; @@ -468,6 +513,9 @@ class ParseObject { if (hasOwn(options, 'useMasterKey')) { requestOptions.useMasterKey = !!options.useMasterKey; } + if (hasOwn(options, 'useMaintenanceKey')) { + requestOptions.useMaintenanceKey = !!options.useMaintenanceKey; + } if (hasOwn(options, 'sessionToken') && typeof options.sessionToken === 'string') { requestOptions.sessionToken = options.sessionToken; } @@ -508,10 +556,10 @@ class ParseObject { * @param offline * @returns {object} */ - toJSON(seen: Array | void, offline?: boolean): AttributeMap { + toJSON(seen: Array | void, offline?: boolean): ToJSON & JSONBaseAttributes { const seenEntry = this.id ? this.className + ':' + this.id : this; seen = seen || [seenEntry]; - const json: AttributeMap = {}; + const json: any = {}; const attrs = this.attributes; for (const attr in attrs) { if ((attr === 'createdAt' || attr === 'updatedAt') && attrs[attr].toJSON) { @@ -538,8 +586,8 @@ class ParseObject { * @param {object} other - An other object ot compare * @returns {boolean} */ - equals(other: any): boolean { - if (this === other) { + equals(other: T): boolean { + if ((this as any) === (other as any)) { return true; } return ( @@ -558,7 +606,7 @@ class ParseObject { * @param {string} attr An attribute name (optional). * @returns {boolean} */ - dirty(attr?: string): boolean { + dirty>(attr?: K): boolean { if (!this.id) { return true; } @@ -589,7 +637,7 @@ class ParseObject { * * @returns {string[]} */ - dirtyKeys(): Array { + dirtyKeys(): string[] { const pendingOps = this._getPendingOps(); const keys = {}; for (let i = 0; i < pendingOps.length; i++) { @@ -652,7 +700,7 @@ class ParseObject { * @param {string} attr The string name of an attribute. * @returns {*} */ - get(attr: string): any { + get>(attr: K): T[K] { return this.attributes[attr]; } @@ -662,8 +710,10 @@ class ParseObject { * @param {string} attr The attribute to get the relation for. * @returns {Parse.Relation} */ - relation(attr: string): ParseRelation { - const value = this.get(attr); + relation = AttributeKey>( + attr: T[K] extends ParseRelation ? K : never + ): ParseRelation { + const value = this.get(attr) as any; if (value) { if (!(value instanceof ParseRelation)) { throw new Error('Called relation() on non-relation field ' + attr); @@ -680,7 +730,7 @@ class ParseObject { * @param {string} attr The string name of an attribute. * @returns {string} */ - escape(attr: string): string { + escape>(attr: K): string { let val = this.attributes[attr]; if (val == null) { return ''; @@ -701,7 +751,7 @@ class ParseObject { * @param {string} attr The string name of the attribute. * @returns {boolean} */ - has(attr: string): boolean { + has>(attr: K): boolean { const attributes = this.attributes; if (Object.hasOwn(attributes, attr)) { return attributes[attr] != null; @@ -739,8 +789,12 @@ class ParseObject { * The only supported option is error. * @returns {Parse.Object} Returns the object, so you can chain this call. */ - set(key: any, value?: any, options?: any): this { - let changes = {}; + set>( + key: K | (Pick | T), + value?: SetOptions | (T[K] extends undefined ? never : T[K]), + options?: SetOptions + ): this { + let changes: any = {}; const newOps = {}; if (key && typeof key === 'object') { changes = key; @@ -750,7 +804,6 @@ class ParseObject { } else { return this; } - options = options || {}; let readonly = []; if (typeof (this.constructor as any).readOnlyAttributes === 'function') { @@ -834,7 +887,7 @@ class ParseObject { * @param options * @returns {Parse.Object} Returns the object, so you can chain this call. */ - unset(attr: string, options?: { [opt: string]: any }): this { + unset>(attr: K, options?: SetOptions): this { options = options || {}; options.unset = true; return this.set(attr, null, options); @@ -848,14 +901,14 @@ class ParseObject { * @param amount {Number} The amount to increment by (optional). * @returns {Parse.Object} Returns the object, so you can chain this call. */ - increment(attr: string, amount?: number): this { + increment>(attr: K, amount?: number): this { if (typeof amount === 'undefined') { amount = 1; } if (typeof amount !== 'number') { throw new Error('Cannot increment by a non-numeric amount.'); } - return this.set(attr, new IncrementOp(amount)); + return this.set(attr, new IncrementOp(amount) as any); } /** @@ -866,14 +919,14 @@ class ParseObject { * @param amount {Number} The amount to decrement by (optional). * @returns {Parse.Object} Returns the object, so you can chain this call. */ - decrement(attr: string, amount?: number): this { + decrement>(attr: K, amount?: number): this { if (typeof amount === 'undefined') { amount = 1; } if (typeof amount !== 'number') { throw new Error('Cannot decrement by a non-numeric amount.'); } - return this.set(attr, new IncrementOp(amount * -1)); + return this.set(attr, new IncrementOp(amount * -1) as any); } /** @@ -884,8 +937,8 @@ class ParseObject { * @param item {} The item to add. * @returns {Parse.Object} Returns the object, so you can chain this call. */ - add(attr: string, item: any): this { - return this.set(attr, new AddOp([item])); + add[keyof T]>(attr: K, item: NonNullable[number]): this { + return this.set(attr as any, new AddOp([item]) as any); } /** @@ -896,8 +949,8 @@ class ParseObject { * @param items {Object[]} The items to add. * @returns {Parse.Object} Returns the object, so you can chain this call. */ - addAll(attr: string, items: Array): this { - return this.set(attr, new AddOp(items)); + addAll[keyof T]>(attr: K, items: NonNullable): this { + return this.set(attr as any, new AddOp(items) as any); } /** @@ -909,8 +962,8 @@ class ParseObject { * @param item {} The object to add. * @returns {Parse.Object} Returns the object, so you can chain this call. */ - addUnique(attr: string, item: any): this { - return this.set(attr, new AddUniqueOp([item])); + addUnique[keyof T]>(attr: K, item: NonNullable[number]): this { + return this.set(attr as any, new AddUniqueOp([item]) as any); } /** @@ -922,8 +975,8 @@ class ParseObject { * @param items {Object[]} The objects to add. * @returns {Parse.Object} Returns the object, so you can chain this call. */ - addAllUnique(attr: string, items: Array): this { - return this.set(attr, new AddUniqueOp(items)); + addAllUnique[keyof T]>(attr: K, items: NonNullable): this { + return this.set(attr as any, new AddUniqueOp(items) as any); } /** @@ -934,8 +987,8 @@ class ParseObject { * @param item {} The object to remove. * @returns {Parse.Object} Returns the object, so you can chain this call. */ - remove(attr: string, item: any): this { - return this.set(attr, new RemoveOp([item])); + remove[keyof T]>(attr: K, item: NonNullable[number]): this { + return this.set(attr as any, new RemoveOp([item]) as any); } /** @@ -946,8 +999,8 @@ class ParseObject { * @param items {Object[]} The object to remove. * @returns {Parse.Object} Returns the object, so you can chain this call. */ - removeAll(attr: string, items: Array): this { - return this.set(attr, new RemoveOp(items)); + removeAll[keyof T]>(attr: K, items: NonNullable): this { + return this.set(attr as any, new RemoveOp(items) as any); } /** @@ -959,7 +1012,7 @@ class ParseObject { * @param attr {String} The key. * @returns {Parse.Op | undefined} The operation, or undefined if none. */ - op(attr: string): Op | undefined { + op>(attr: K): Op | undefined { const pending = this._getPendingOps(); for (let i = pending.length; i--;) { if (pending[i][attr]) { @@ -982,7 +1035,7 @@ class ParseObject { const readonly = (this.constructor as any).readOnlyAttributes() || []; // Attributes are frozen, so we have to rebuild an object, // rather than delete readonly keys - const copy = {}; + const copy: T = {} as T; for (const a in attributes) { if (readonly.indexOf(a) < 0) { copy[a] = attributes[a]; @@ -991,7 +1044,7 @@ class ParseObject { attributes = copy; } if (clone.set) { - clone.set(attributes); + clone.set(attributes as any); } return clone; } @@ -1001,7 +1054,7 @@ class ParseObject { * * @returns {Parse.Object} */ - newInstance(): any { + newInstance(): this { const clone = new (this.constructor as new ( ...args: ConstructorParameters ) => this)(this.className); @@ -1094,13 +1147,13 @@ class ParseObject { * @returns {Parse.Error|boolean} False if the data is valid. An error object otherwise. * @see Parse.Object#set */ - validate(attrs: AttributeMap): ParseError | boolean { + validate(attrs: Attributes): ParseError | boolean { if (Object.hasOwn(attrs, 'ACL') && !(attrs.ACL instanceof ParseACL)) { return new ParseError(ParseError.OTHER_CAUSE, 'ACL must be a Parse ACL.'); } for (const key in attrs) { - if (!/^[A-Za-z][0-9A-Za-z_.]*$/.test(key)) { - return new ParseError(ParseError.INVALID_KEY_NAME, `Invalid key name: "${key}"`); + if (!/^[A-Za-z_][0-9A-Za-z_.]*$/.test(key)) { + return new ParseError(ParseError.INVALID_KEY_NAME, `Invalid key name: ${key}`); } } return false; @@ -1113,7 +1166,7 @@ class ParseObject { * @see Parse.Object#get */ getACL(): ParseACL | null { - const acl = this.get('ACL'); + const acl: any = this.get('ACL' as AttributeKey); if (acl instanceof ParseACL) { return acl; } @@ -1129,7 +1182,7 @@ class ParseObject { * @see Parse.Object#set */ setACL(acl: ParseACL, options?: any): this { - return this.set('ACL', acl, options); + return this.set('ACL' as AttributeKey, acl as any, options); } /** @@ -1137,7 +1190,7 @@ class ParseObject { * * @param {string} [keys] - specify which fields to revert */ - revert(...keys: Array): void { + revert(...keys: Array>): void { let keysToRevert; if (keys.length) { keysToRevert = []; @@ -1159,7 +1212,7 @@ class ParseObject { */ clear(): this { const attributes = this.attributes; - const erasable = {}; + const erasable: Attributes = {}; let readonly = ['createdAt', 'updatedAt']; if (typeof (this.constructor as any).readOnlyAttributes === 'function') { readonly = readonly.concat((this.constructor as any).readOnlyAttributes()); @@ -1169,7 +1222,7 @@ class ParseObject { erasable[attr] = true; } } - return this.set(erasable, { unset: true }); + return this.set(erasable as any, { unset: true }); } /** @@ -1189,10 +1242,10 @@ class ParseObject { * @returns {Promise} A promise that is fulfilled when the fetch * completes. */ - fetch(options: FetchOptions): Promise { + fetch(options: FetchOptions): Promise { const fetchOptions = ParseObject._getRequestOptions(options); const controller = CoreManager.getObjectController(); - return controller.fetch(this, true, fetchOptions); + return controller.fetch(this, true, fetchOptions) as Promise; } /** @@ -1215,8 +1268,8 @@ class ParseObject { */ fetchWithInclude( keys: string | Array>, - options: RequestOptions - ): Promise { + options?: RequestOptions + ): Promise { options = options || {}; options.include = keys; return this.fetch(options); @@ -1246,7 +1299,7 @@ class ParseObject { * @returns {Promise} A promise that is fulfilled when the save * completes. */ - async saveEventually(options: SaveOptions): Promise { + async saveEventually(options?: SaveOptions): Promise { try { await this.save(null, options); } catch (e) { @@ -1321,9 +1374,13 @@ class ParseObject { * @returns {Promise} A promise that is fulfilled when the save * completes. */ - async save( - arg1: undefined | string | { [attr: string]: any } | null, - arg2: SaveOptions | any, + async save>( + arg1?: Pick | T | null, + arg2?: SaveOptions + ): Promise; + async save>( + arg1: K, + arg2: T[K] extends undefined ? never : T[K], arg3?: SaveOptions ): Promise { let attrs; @@ -1367,9 +1424,8 @@ class ParseObject { .then(() => controller.save(unsavedObjects, saveOptions)) .then((savedOjbects: this[]) => savedOjbects.pop()); } - return controller.save(unsaved, saveOptions).then(() => { - return controller.save(this, saveOptions); - }) as Promise as Promise; + await controller.save(unsaved, saveOptions); + return controller.save(this, saveOptions) as Promise as Promise; } /** @@ -1394,7 +1450,7 @@ class ParseObject { * @returns {Promise} A promise that is fulfilled when the destroy * completes. */ - async destroyEventually(options: RequestOptions): Promise { + async destroyEventually(options?: RequestOptions): Promise { try { await this.destroy(options); } catch (e) { @@ -1420,7 +1476,7 @@ class ParseObject { * @returns {Promise} A promise that is fulfilled when the destroy * completes. */ - destroy(options: RequestOptions): Promise { + destroy(options?: RequestOptions): Promise { if (!this.id) { return Promise.resolve(); } @@ -1576,9 +1632,9 @@ class ParseObject { * @static * @returns {Parse.Object[]} */ - static fetchAll(list: Array, options: RequestOptions = {}) { + static fetchAll(list: T[], options?: RequestOptions): Promise { const fetchOptions = ParseObject._getRequestOptions(options); - return CoreManager.getObjectController().fetch(list, true, fetchOptions); + return CoreManager.getObjectController().fetch(list, true, fetchOptions) as Promise; } /** @@ -1610,11 +1666,11 @@ class ParseObject { * @static * @returns {Parse.Object[]} */ - static fetchAllWithInclude( - list: Array, - keys: string | Array>, - options: RequestOptions - ) { + static fetchAllWithInclude( + list: T[], + keys: keyof T['attributes'] | Array, + options?: RequestOptions + ): Promise { options = options || {}; options.include = keys; return ParseObject.fetchAll(list, options); @@ -1650,11 +1706,11 @@ class ParseObject { * @static * @returns {Parse.Object[]} */ - static fetchAllIfNeededWithInclude( - list: Array, - keys: string | Array>, - options: RequestOptions - ) { + static fetchAllIfNeededWithInclude( + list: T[], + keys: keyof T['attributes'] | Array, + options?: RequestOptions + ): Promise { options = options || {}; options.include = keys; return ParseObject.fetchAllIfNeeded(list, options); @@ -1687,9 +1743,9 @@ class ParseObject { * @static * @returns {Parse.Object[]} */ - static fetchAllIfNeeded(list: Array, options: FetchOptions) { + static fetchAllIfNeeded(list: T[], options?: FetchOptions): Promise { const fetchOptions = ParseObject._getRequestOptions(options); - return CoreManager.getObjectController().fetch(list, false, fetchOptions); + return CoreManager.getObjectController().fetch(list, false, fetchOptions) as Promise; } static handleIncludeOptions(options: { include?: string | string[] }) { @@ -1763,7 +1819,7 @@ class ParseObject { * @returns {Promise} A promise that is fulfilled when the destroyAll * completes. */ - static destroyAll(list: Array, options: SaveOptions = {}) { + static destroyAll(list: Array, options?: SaveOptions) { const destroyOptions = ParseObject._getRequestOptions(options); return CoreManager.getObjectController().destroy(list, destroyOptions); } @@ -1797,9 +1853,9 @@ class ParseObject { * @static * @returns {Parse.Object[]} */ - static saveAll(list: Array, options: SaveOptions = {}) { + static saveAll(list: T, options?: SaveOptions): Promise { const saveOptions = ParseObject._getRequestOptions(options); - return CoreManager.getObjectController().save(list, saveOptions); + return CoreManager.getObjectController().save(list, saveOptions) as any; } /** @@ -1832,13 +1888,13 @@ class ParseObject { * @static * @returns {Parse.Object} A Parse.Object reference */ - static fromJSON(json: any, override?: boolean, dirty?: boolean): ParseObject { + static fromJSON(json: any, override?: boolean, dirty?: boolean): T { if (!json.className) { throw new Error('Cannot create an object without a className'); } const constructor = classMap[json.className]; const o = constructor ? new constructor(json.className) : new ParseObject(json.className); - const otherAttributes: AttributeMap = {}; + const otherAttributes: Attributes = {}; for (const attr in json) { if (attr !== 'className' && attr !== '__type') { otherAttributes[attr] = json[attr]; @@ -2206,7 +2262,7 @@ const DefaultController = { fetch( target: ParseObject | Array, forceFetch: boolean, - options: RequestOptions + options?: RequestOptions ): Promise | ParseObject | undefined> { const localDatastore = CoreManager.getLocalDatastore(); if (Array.isArray(target)) { @@ -2310,7 +2366,7 @@ const DefaultController = { async destroy( target: ParseObject | Array, - options: RequestOptions + options?: RequestOptions ): Promise> { if (options && options.batchSize && options.transaction) throw new ParseError( @@ -2397,7 +2453,7 @@ const DefaultController = { save( target: ParseObject | null | Array, - options: RequestOptions + options?: RequestOptions ): Promise | ParseFile | undefined> { if (options && options.batchSize && options.transaction) return Promise.reject( diff --git a/src/ParseQuery.ts b/src/ParseQuery.ts index 648060b9b..77a2e3601 100644 --- a/src/ParseQuery.ts +++ b/src/ParseQuery.ts @@ -9,10 +9,12 @@ import { DEFAULT_PIN } from './LocalDatastoreUtils'; import type LiveQuerySubscription from './LiveQuerySubscription'; import type { RequestOptions, FullOptions } from './RESTController'; +import type { Pointer } from './ParseObject'; type BatchOptions = FullOptions & { batchSize?: number; useMasterKey?: boolean; + useMaintenanceKey?: boolean; sessionToken?: string; context?: { [key: string]: any }; json?: boolean; @@ -54,6 +56,12 @@ export type QueryJSON = { comment?: string; }; +interface BaseAttributes { + createdAt: Date; + objectId: string; + updatedAt: Date; +} + /** * Converts a string into a regex that matches it. * Surrounding with \Q .. \E does this, we just need to escape any \E's in @@ -235,7 +243,7 @@ function handleOfflineSort(a, b, sorts) { * * @alias Parse.Query */ -class ParseQuery { +class ParseQuery { /** * @property {string} className */ @@ -263,7 +271,7 @@ class ParseQuery { /** * @param {(string | Parse.Object)} objectClass An instance of a subclass of Parse.Object, or a Parse className string. */ - constructor(objectClass: string | ParseObject) { + constructor(objectClass: string | (new (...args: any[]) => T | ParseObject)) { if (typeof objectClass === 'string') { if (objectClass === 'User' && CoreManager.get('PERFORM_USER_REWRITE')) { this.className = '_User'; @@ -310,7 +318,7 @@ class ParseQuery { * @param {Array} queries * @returns {Parse.Query} Returns the query, so you can chain this call. */ - _orQuery(queries: Array): ParseQuery { + _orQuery(queries: Array): this { const queryJSON = queries.map(q => { return q.toJSON().where; }); @@ -325,7 +333,7 @@ class ParseQuery { * @param {Array} queries * @returns {Parse.Query} Returns the query, so you can chain this call. */ - _andQuery(queries: Array): ParseQuery { + _andQuery(queries: Array): this { const queryJSON = queries.map(q => { return q.toJSON().where; }); @@ -340,7 +348,7 @@ class ParseQuery { * @param {Array} queries * @returns {Parse.Query} Returns the query, so you can chain this call. */ - _norQuery(queries: Array): ParseQuery { + _norQuery(queries: Array): this { const queryJSON = queries.map(q => { return q.toJSON().where; }); @@ -357,7 +365,11 @@ class ParseQuery { * @param value * @returns {Parse.Query} */ - _addCondition(key: string, condition: string, value: any): ParseQuery { + _addCondition( + key: K, + condition: string, + value: any + ): this { if (!this._where[key] || typeof this._where[key] === 'string') { this._where[key] = {}; } @@ -518,7 +530,7 @@ class ParseQuery { * @param {QueryJSON} json from Parse.Query.toJSON() method * @returns {Parse.Query} Returns the query, so you can chain this call. */ - withJSON(json: QueryJSON): ParseQuery { + withJSON(json: QueryJSON): this { if (json.where) { this._where = json.where; } @@ -636,8 +648,8 @@ class ParseQuery { * @returns {Promise} A promise that is resolved with the result when * the query completes. */ - get(objectId: string, options?: QueryOptions): Promise { - this.equalTo('objectId', objectId); + get(objectId: string, options?: QueryOptions): Promise { + this.equalTo('objectId', objectId as any); const firstOptions = ParseObject._getRequestOptions(options); return this.first(firstOptions).then(response => { @@ -665,7 +677,7 @@ class ParseQuery { * @returns {Promise} A promise that is resolved with the results when * the query completes. */ - find(options?: QueryOptions): Promise> { + find(options?: QueryOptions): Promise { const findOptions = ParseObject._getRequestOptions(options); this._setRequestTask(findOptions); @@ -726,9 +738,9 @@ class ParseQuery { * @returns {Promise} A promise that is resolved with the results when * the query completes. */ - async findAll(options?: BatchOptions): Promise> { - let result: ParseObject[] = []; - await this.eachBatch((objects: ParseObject[]) => { + async findAll(options?: BatchOptions): Promise { + let result: T[] = []; + await this.eachBatch((objects: T[]) => { result = [...result, ...objects]; }, options); return result; @@ -774,7 +786,10 @@ class ParseQuery { * @param {string} [options.sessionToken] A valid session token, used for making a request on behalf of a specific user. * @returns {Promise} A promise that is resolved with the query completes. */ - distinct(key: string, options?: { sessionToken?: string }): Promise> { + distinct( + key: K, + options?: { sessionToken?: string } + ): Promise { options = options || {}; const distinctOptions: { sessionToken?: string; useMasterKey: boolean } = { useMasterKey: true, @@ -853,7 +868,7 @@ class ParseQuery { * @returns {Promise} A promise that is resolved with the object when * the query completes. */ - first(options: QueryOptions = {}): Promise { + first(options: QueryOptions = {}): Promise { const findOptions = ParseObject._getRequestOptions(options); this._setRequestTask(findOptions); @@ -889,9 +904,9 @@ class ParseQuery { handleSelectResult(objects[0], select); } if (findOptions.json) { - return objects[0]; + return objects[0] as T; } else { - return ParseObject.fromJSON(objects[0], !select); + return ParseObject.fromJSON(objects[0], !select) as T; } }); } @@ -917,7 +932,10 @@ class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - eachBatch(callback: (objs: Array) => void, options?: BatchOptions): Promise { + eachBatch( + callback: (objs: T[]) => PromiseLike | void, + options?: BatchOptions + ): Promise { options = options || {}; if (this._order || this._skip || this._limit >= 0) { @@ -931,7 +949,7 @@ class ParseQuery { const findOptions = ParseObject._getRequestOptions(options); let finished = false; - let previousResults: ParseObject[] = []; + let previousResults: T[] = []; return continueWhile( () => { return !finished; @@ -947,9 +965,9 @@ class ParseQuery { } else { query.greaterThan('objectId', results[results.length - 1].id); } - previousResults = results; + previousResults = results as T[]; } else if (results.length > 0) { - await Promise.resolve(callback(results)); + await Promise.resolve(callback(results as T[])); finished = true; } else { finished = true; @@ -978,10 +996,10 @@ class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - each(callback: (obj: ParseObject) => any, options?: BatchOptions): Promise { + each(callback: (obj: T) => PromiseLike | void, options?: BatchOptions): Promise { return this.eachBatch(results => { let callbacksDone = Promise.resolve(); - results.forEach(result => { + results.forEach((result: T) => { callbacksDone = callbacksDone.then(() => { return callback(result); }); @@ -996,7 +1014,7 @@ class ParseQuery { * @param {(string|object)} value String or Object of index that should be used when executing query * @returns {Parse.Query} Returns the query, so you can chain this call. */ - hint(value: any): ParseQuery { + hint(value: any): this { if (typeof value === 'undefined') { delete this._hint; } @@ -1010,7 +1028,7 @@ class ParseQuery { * @param {boolean} explain Used to toggle the information on the query plan. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - explain(explain = true): ParseQuery { + explain(explain = true): this { if (typeof explain !== 'boolean') { throw new Error('You can only set explain to a boolean value'); } @@ -1155,15 +1173,23 @@ class ParseQuery { * @param value The value that the Parse.Object must contain. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - equalTo(key: string | { [key: string]: any }, value?: any): ParseQuery { + equalTo( + key: K, + value: + | T['attributes'][K] + | (T['attributes'][K] extends ParseObject + ? Pointer + : T['attributes'][K] extends Array + ? E + : never) + ): this { if (key && typeof key === 'object') { - Object.entries(key).forEach(([k, val]) => this.equalTo(k, val)); + Object.entries(key).forEach(([k, val]) => this.equalTo(k, val as any)); return this; } if (typeof value === 'undefined') { return this.doesNotExist(key as string); } - this._where[key as string] = encode(value, false, true); return this; } @@ -1176,12 +1202,21 @@ class ParseQuery { * @param value The value that must not be equalled. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - notEqualTo(key: string | { [key: string]: any }, value?: any): ParseQuery { + notEqualTo( + key: K, + value: + | T['attributes'][K] + | (T['attributes'][K] extends ParseObject + ? Pointer + : T['attributes'][K] extends Array + ? E + : never) + ): this { if (key && typeof key === 'object') { - Object.entries(key).forEach(([k, val]) => this.notEqualTo(k, val)); + Object.entries(key).forEach(([k, val]) => this.notEqualTo(k, val as any)); return this; } - return this._addCondition(key as string, '$ne', value); + return this._addCondition(key, '$ne', value); } /** @@ -1192,7 +1227,10 @@ class ParseQuery { * @param value The value that provides an upper bound. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - lessThan(key: string, value: any): ParseQuery { + lessThan( + key: K, + value: T['attributes'][K] + ): this { return this._addCondition(key, '$lt', value); } @@ -1204,7 +1242,10 @@ class ParseQuery { * @param value The value that provides an lower bound. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - greaterThan(key: string, value: any): ParseQuery { + greaterThan( + key: K, + value: T['attributes'][K] + ): this { return this._addCondition(key, '$gt', value); } @@ -1216,7 +1257,10 @@ class ParseQuery { * @param value The value that provides an upper bound. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - lessThanOrEqualTo(key: string, value: any): ParseQuery { + lessThanOrEqualTo( + key: K, + value: T['attributes'][K] + ): this { return this._addCondition(key, '$lte', value); } @@ -1228,7 +1272,10 @@ class ParseQuery { * @param {*} value The value that provides an lower bound. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - greaterThanOrEqualTo(key: string, value: any): ParseQuery { + greaterThanOrEqualTo( + key: K, + value: T['attributes'][K] + ): this { return this._addCondition(key, '$gte', value); } @@ -1237,11 +1284,14 @@ class ParseQuery { * be contained in the provided list of values. * * @param {string} key The key to check. - * @param {Array<*>} value The values that will match. + * @param {Array<*>} values The values that will match. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - containedIn(key: string, value: Array): ParseQuery { - return this._addCondition(key, '$in', value); + containedIn( + key: K, + values: Array + ): this { + return this._addCondition(key, '$in', values); } /** @@ -1249,11 +1299,14 @@ class ParseQuery { * not be contained in the provided list of values. * * @param {string} key The key to check. - * @param {Array<*>} value The values that will not match. + * @param {Array<*>} values The values that will not match. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - notContainedIn(key: string, value: Array): ParseQuery { - return this._addCondition(key, '$nin', value); + notContainedIn( + key: K, + values: Array + ): this { + return this._addCondition(key, '$nin', values); } /** @@ -1264,7 +1317,10 @@ class ParseQuery { * @param {Array} values The values that will match. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - containedBy(key: string, values: Array): ParseQuery { + containedBy( + key: K, + values: Array + ): this { return this._addCondition(key, '$containedBy', values); } @@ -1276,7 +1332,7 @@ class ParseQuery { * @param {Array} values The values that will match. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - containsAll(key: string, values: Array): ParseQuery { + containsAll(key: K, values: any[]): this { return this._addCondition(key, '$all', values); } @@ -1288,7 +1344,10 @@ class ParseQuery { * @param {Array} values The string values that will match as starting string. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - containsAllStartingWith(key: string, values: Array): ParseQuery { + containsAllStartingWith( + key: K, + values: any[] + ): this { if (!Array.isArray(values)) { values = [values]; } @@ -1306,7 +1365,7 @@ class ParseQuery { * @param {string} key The key that should exist. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - exists(key: string): ParseQuery { + exists(key: K): this { return this._addCondition(key, '$exists', true); } @@ -1316,7 +1375,7 @@ class ParseQuery { * @param {string} key The key that should not exist * @returns {Parse.Query} Returns the query, so you can chain this call. */ - doesNotExist(key: string): ParseQuery { + doesNotExist(key: K): this { return this._addCondition(key, '$exists', false); } @@ -1330,7 +1389,11 @@ class ParseQuery { * @param {string} modifiers The regular expression mode. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - matches(key: string, regex: RegExp | string, modifiers: string): ParseQuery { + matches( + key: K, + regex: RegExp | string, + modifiers?: string + ): this { this._addCondition(key, '$regex', regex); if (!modifiers) { modifiers = ''; @@ -1358,7 +1421,10 @@ class ParseQuery { * @param {Parse.Query} query The query that should match. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - matchesQuery(key: string, query: ParseQuery): ParseQuery { + matchesQuery( + key: K, + query: ParseQuery + ): this { const queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$inQuery', queryJSON); @@ -1373,7 +1439,10 @@ class ParseQuery { * @param {Parse.Query} query The query that should not match. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - doesNotMatchQuery(key: string, query: ParseQuery): ParseQuery { + doesNotMatchQuery( + key: K, + query: ParseQuery + ): this { const queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$notInQuery', queryJSON); @@ -1390,7 +1459,11 @@ class ParseQuery { * @param {Parse.Query} query The query to run. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - matchesKeyInQuery(key: string, queryKey: string, query: ParseQuery): ParseQuery { + matchesKeyInQuery< + U extends ParseObject, + K extends keyof T['attributes'], + X extends Extract, + >(key: K, queryKey: X, query: ParseQuery): this { const queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$select', { @@ -1410,7 +1483,11 @@ class ParseQuery { * @param {Parse.Query} query The query to run. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - doesNotMatchKeyInQuery(key: string, queryKey: string, query: ParseQuery): ParseQuery { + doesNotMatchKeyInQuery< + U extends ParseObject, + K extends keyof T['attributes'] | keyof BaseAttributes, + X extends Extract, + >(key: K, queryKey: X, query: ParseQuery): this { const queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$dontSelect', { @@ -1427,7 +1504,10 @@ class ParseQuery { * @param {string} substring The substring that the value must contain. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - contains(key: string, substring: string): ParseQuery { + contains( + key: K, + substring: string + ): this { if (typeof substring !== 'string') { throw new Error('The value being searched for must be a string.'); } @@ -1463,7 +1543,11 @@ 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: string, value: string, options: FullTextQueryOptions = {}): ParseQuery { + fullText( + key: K, + value: string, + options?: FullTextQueryOptions + ): this { options = options || {}; if (!key) { @@ -1510,7 +1594,7 @@ class ParseQuery { */ sortByTextScore() { this.ascending('$score'); - this.select(['$score']); + this.select(['$score'] as any); return this; } @@ -1524,7 +1608,11 @@ class ParseQuery { * @param {string} modifiers The regular expression mode. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - startsWith(key: string, prefix: string, modifiers: string): ParseQuery { + startsWith( + key: K, + prefix: string, + modifiers?: string + ): this { if (typeof prefix !== 'string') { throw new Error('The value being searched for must be a string.'); } @@ -1540,7 +1628,11 @@ class ParseQuery { * @param {string} modifiers The regular expression mode. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - endsWith(key: string, suffix: string, modifiers: string): ParseQuery { + endsWith( + key: K, + suffix: string, + modifiers?: string + ): this { if (typeof suffix !== 'string') { throw new Error('The value being searched for must be a string.'); } @@ -1555,7 +1647,7 @@ class ParseQuery { * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - near(key: string, point: ParseGeoPoint): ParseQuery { + near(key: K, point: ParseGeoPoint): this { if (!(point instanceof ParseGeoPoint)) { // Try to cast it as a GeoPoint point = new ParseGeoPoint(point); @@ -1575,12 +1667,12 @@ class ParseQuery { * defaults to true. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - withinRadians( - key: string, + withinRadians( + key: K, point: ParseGeoPoint, maxDistance: number, - sorted: boolean - ): ParseQuery { + sorted?: boolean + ): this { if (sorted || sorted === undefined) { this.near(key, point); return this._addCondition(key, '$maxDistance', maxDistance); @@ -1604,7 +1696,12 @@ class ParseQuery { * defaults to true. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - withinMiles(key: string, point: ParseGeoPoint, maxDistance: number, sorted: boolean): ParseQuery { + withinMiles( + key: K, + point: ParseGeoPoint, + maxDistance: number, + sorted?: boolean + ): this { return this.withinRadians(key, point, maxDistance / 3958.8, sorted); } @@ -1621,12 +1718,12 @@ class ParseQuery { * defaults to true. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - withinKilometers( - key: string, + withinKilometers( + key: K, point: ParseGeoPoint, maxDistance: number, - sorted: boolean - ): ParseQuery { + sorted?: boolean + ): this { return this.withinRadians(key, point, maxDistance / 6371.0, sorted); } @@ -1642,7 +1739,11 @@ class ParseQuery { * The upper-right inclusive corner of the box. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - withinGeoBox(key: string, southwest: ParseGeoPoint, northeast: ParseGeoPoint): ParseQuery { + withinGeoBox( + key: K, + southwest: ParseGeoPoint, + northeast: ParseGeoPoint + ): this { if (!(southwest instanceof ParseGeoPoint)) { southwest = new ParseGeoPoint(southwest); } @@ -1664,7 +1765,10 @@ class ParseQuery { * @param {Array} points Array of Coordinates / GeoPoints * @returns {Parse.Query} Returns the query, so you can chain this call. */ - withinPolygon(key: string, points: Array>): ParseQuery { + withinPolygon( + key: K, + points: number[][] + ): this { return this._addCondition(key, '$geoWithin', { $polygon: points }); } @@ -1676,7 +1780,10 @@ class ParseQuery { * @param {Parse.GeoPoint} point * @returns {Parse.Query} Returns the query, so you can chain this call. */ - polygonContains(key: string, point: ParseGeoPoint): ParseQuery { + polygonContains( + key: K, + point: ParseGeoPoint + ): this { return this._addCondition(key, '$geoIntersects', { $point: point }); } @@ -1689,7 +1796,7 @@ class ParseQuery { * string of comma separated values, or an Array of keys, or multiple keys. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - ascending(...keys: Array): ParseQuery { + ascending(...keys: Array): this { this._order = []; return this.addAscending.apply(this, keys); } @@ -1702,11 +1809,11 @@ class ParseQuery { * string of comma separated values, or an Array of keys, or multiple keys. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - addAscending(...keys: Array): ParseQuery { + addAscending(...keys: Array): this { if (!this._order) { this._order = []; } - keys.forEach(key => { + keys.forEach((key: any) => { if (Array.isArray(key)) { key = key.join(); } @@ -1723,7 +1830,7 @@ class ParseQuery { * string of comma separated values, or an Array of keys, or multiple keys. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - descending(...keys: Array): ParseQuery { + descending(...keys: Array): this { this._order = []; return this.addDescending.apply(this, keys); } @@ -1736,11 +1843,11 @@ class ParseQuery { * string of comma separated values, or an Array of keys, or multiple keys. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - addDescending(...keys: Array): ParseQuery { + addDescending(...keys: Array): this { if (!this._order) { this._order = []; } - keys.forEach(key => { + keys.forEach((key: any) => { if (Array.isArray(key)) { key = key.join(); } @@ -1748,7 +1855,7 @@ class ParseQuery { key .replace(/\s/g, '') .split(',') - .map(k => { + .map((k: string) => { return '-' + k; }) ); @@ -1767,7 +1874,7 @@ class ParseQuery { * @param {number} n the number of results to skip. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - skip(n: number): ParseQuery { + skip(n: number): this { if (typeof n !== 'number' || n < 0) { throw new Error('You can only skip by a positive number'); } @@ -1781,7 +1888,7 @@ class ParseQuery { * @param {number} n the number of results to limit to. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - limit(n: number): ParseQuery { + limit(n: number): this { if (typeof n !== 'number') { throw new Error('You can only set the limit to a numeric value'); } @@ -1798,7 +1905,7 @@ class ParseQuery { * @param {boolean} includeCount false - disable, true - enable. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - withCount(includeCount = true): ParseQuery { + withCount(includeCount = true): this { if (typeof includeCount !== 'boolean') { throw new Error('You can only set withCount to a boolean value'); } @@ -1816,12 +1923,14 @@ class ParseQuery { * @param {...string|Array} keys The name(s) of the key(s) to include. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - include(...keys: Array>): ParseQuery { + include( + ...keys: Array> + ): this { keys.forEach(key => { if (Array.isArray(key)) { - this._include = this._include.concat(key); + this._include = this._include.concat(key as string[]); } else { - this._include.push(key); + this._include.push(key as string); } }); return this; @@ -1834,7 +1943,7 @@ class ParseQuery { * * @returns {Parse.Query} Returns the query, so you can chain this call. */ - includeAll(): ParseQuery { + includeAll(): this { return this.include('*'); } @@ -1846,15 +1955,17 @@ class ParseQuery { * @param {...string|Array} keys The name(s) of the key(s) to include. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - select(...keys: Array>): ParseQuery { + select( + ...keys: Array> + ): this { if (!this._select) { this._select = []; } keys.forEach(key => { if (Array.isArray(key)) { - this._select = this._select.concat(key); + this._select = this._select.concat(key as string[]); } else { - this._select.push(key); + this._select.push(key as string); } }); return this; @@ -1869,12 +1980,14 @@ class ParseQuery { * @param {...string|Array} keys The name(s) of the key(s) to exclude. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - exclude(...keys: Array>): ParseQuery { + exclude( + ...keys: Array> + ): this { keys.forEach(key => { if (Array.isArray(key)) { - this._exclude = this._exclude.concat(key); + this._exclude = this._exclude.concat(key as string[]); } else { - this._exclude.push(key); + this._exclude.push(key as string); } }); return this; @@ -1888,12 +2001,14 @@ class ParseQuery { * @param {...string|Array} keys The name(s) of the key(s) to watch. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - watch(...keys: Array>): ParseQuery { + watch( + ...keys: Array> + ): this { keys.forEach(key => { if (Array.isArray(key)) { - this._watch = this._watch.concat(key); + this._watch = this._watch.concat(key as string[]); } else { - this._watch.push(key); + this._watch.push(key as string); } }); return this; @@ -1911,7 +2026,7 @@ class ParseQuery { readPreference: string, includeReadPreference?: string, subqueryReadPreference?: string - ): ParseQuery { + ): this { this._readPreference = readPreference; this._includeReadPreference = includeReadPreference || null; this._subqueryReadPreference = subqueryReadPreference || null; @@ -1925,7 +2040,7 @@ class ParseQuery { * @returns {Promise} Returns the liveQuerySubscription, it's an event emitter * which can be used to get liveQuery updates. */ - async subscribe(sessionToken?: string): Promise { + async subscribe(sessionToken?: string | null): Promise { const currentUser = await CoreManager.getUserController().currentUserAsync(); if (!sessionToken) { sessionToken = currentUser ? currentUser.getSessionToken() || undefined : undefined; @@ -2002,7 +2117,7 @@ class ParseQuery { * * @returns {Parse.Query} Returns the query, so you can chain this call. */ - fromNetwork(): ParseQuery { + fromNetwork(): this { this._queriesLocalDatastore = false; this._localDatastorePinName = null; return this; @@ -2013,7 +2128,7 @@ class ParseQuery { * * @returns {Parse.Query} Returns the query, so you can chain this call. */ - fromLocalDatastore(): ParseQuery { + fromLocalDatastore(): this { return this.fromPinWithName(null); } @@ -2022,7 +2137,7 @@ class ParseQuery { * * @returns {Parse.Query} Returns the query, so you can chain this call. */ - fromPin(): ParseQuery { + fromPin(): this { return this.fromPinWithName(DEFAULT_PIN); } @@ -2032,7 +2147,7 @@ class ParseQuery { * @param {string} name The name of query source. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - fromPinWithName(name?: string | null): ParseQuery { + fromPinWithName(name?: string | null): this { const localDatastore = CoreManager.getLocalDatastore(); if (localDatastore.checkIfEnabled()) { this._queriesLocalDatastore = true; @@ -2046,7 +2161,7 @@ class ParseQuery { * * @returns {Parse.Query} Returns the query, so you can chain this call. */ - cancel(): ParseQuery { + cancel(): this { if (this._xhrRequest.task && typeof this._xhrRequest.task.abort === 'function') { this._xhrRequest.task._aborted = true; this._xhrRequest.task.abort(); @@ -2072,7 +2187,7 @@ class ParseQuery { * @param {string} value a comment can make your profile data easier to interpret and trace. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - comment(value: string): ParseQuery { + comment(value: string): this { if (value == null) { delete this._comment; return this; @@ -2089,7 +2204,7 @@ const DefaultController = { find( className: string, params: QueryJSON, - options: RequestOptions + options?: RequestOptions ): Promise<{ results: Array }> { const RESTController = CoreManager.getRESTController(); return RESTController.request('GET', 'classes/' + className, params, options); @@ -2098,7 +2213,7 @@ const DefaultController = { aggregate( className: string, params: any, - options: RequestOptions + options?: RequestOptions ): Promise<{ results: Array }> { const RESTController = CoreManager.getRESTController(); diff --git a/src/ParseRelation.ts b/src/ParseRelation.ts index d53126d98..ea5844e35 100644 --- a/src/ParseRelation.ts +++ b/src/ParseRelation.ts @@ -15,8 +15,8 @@ import CoreManager from './CoreManager'; * * @alias Parse.Relation */ -class ParseRelation { - parent?: ParseObject; +class ParseRelation { + parent?: S; key?: string; targetClassName?: string | null; @@ -24,7 +24,7 @@ class ParseRelation { * @param {Parse.Object} parent The parent of this relation. * @param {string} key The key for this relation on the parent. */ - constructor(parent?: ParseObject, key?: string) { + constructor(parent?: S, key?: string) { this.parent = parent; this.key = key; this.targetClassName = null; @@ -33,7 +33,7 @@ class ParseRelation { /* * Makes sure that this relation has the right parent and key. */ - _ensureParentAndKey(parent: ParseObject, key: string) { + _ensureParentAndKey(parent: S, key: string) { this.key = this.key || key; if (this.key !== key) { throw new Error('Internal Error. Relation retrieved from two different keys.'); @@ -60,7 +60,7 @@ class ParseRelation { * @param {(Parse.Object|Array)} objects The item or items to add. * @returns {Parse.Object} The parent of the relation. */ - add(objects: ParseObject | Array): ParseObject { + add(objects: T | T[]): S { if (!Array.isArray(objects)) { objects = [objects]; } @@ -83,7 +83,7 @@ class ParseRelation { * * @param {(Parse.Object|Array)} objects The item or items to remove. */ - remove(objects: ParseObject | Array) { + remove(objects: T | T[]): void { if (!Array.isArray(objects)) { objects = [objects]; } @@ -117,7 +117,7 @@ class ParseRelation { * * @returns {Parse.Query} Relation Query */ - query(): ParseQuery { + query(): ParseQuery { let query; const parent = this.parent; if (!parent) { diff --git a/src/ParseRole.ts b/src/ParseRole.ts index 6ce7ca754..7bcee4525 100644 --- a/src/ParseRole.ts +++ b/src/ParseRole.ts @@ -1,10 +1,12 @@ import CoreManager from './CoreManager'; import ParseACL from './ParseACL'; import ParseError from './ParseError'; -import ParseObject from './ParseObject'; +import ParseObject, { Attributes, SetOptions } from './ParseObject'; +import type { AttributeKey } from './ParseObject'; import type { AttributeMap } from './ObjectStateMutations'; import type ParseRelation from './ParseRelation'; +import type ParseUser from './ParseUser'; /** * Represents a Role on the Parse server. Roles represent groupings of @@ -19,7 +21,7 @@ import type ParseRelation from './ParseRelation'; * @alias Parse.Role * @augments Parse.Object */ -class ParseRole extends ParseObject { +class ParseRole extends ParseObject { /** * @param {string} name The name of the Role to create. * @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL. @@ -40,7 +42,7 @@ class ParseRole extends ParseObject { * @returns {string} the name of the role. */ getName(): string | null { - const name = this.get('name'); + const name = this.get('name' as AttributeKey); if (name == null || typeof name === 'string') { return name; } @@ -62,11 +64,11 @@ class ParseRole extends ParseObject { * @param {string} name The name of the role. * @param {object} options Standard options object with success and error * callbacks. - * @returns {(ParseObject|boolean)} true if the set succeeded. + * @returns {Parse.Object} Returns the object, so you can chain this call. */ - setName(name: string, options?: any): ParseObject | boolean { + setName(name: string, options?: SetOptions): this { this._validateName(name); - return this.set('name', name, options); + return this.set('name' as AttributeKey, name as any, options); } /** @@ -80,8 +82,8 @@ class ParseRole extends ParseObject { * @returns {Parse.Relation} the relation for the users belonging to this * role. */ - getUsers(): ParseRelation { - return this.relation('users'); + getUsers(): ParseRelation { + return this.relation('users' as any); } /** @@ -95,8 +97,8 @@ class ParseRole extends ParseObject { * @returns {Parse.Relation} the relation for the roles belonging to this * role. */ - getRoles(): ParseRelation { - return this.relation('roles'); + getRoles(): ParseRelation { + return this.relation('roles' as any); } _validateName(newName) { diff --git a/src/ParseSchema.ts b/src/ParseSchema.ts index 4decdcf4f..8e849463d 100644 --- a/src/ParseSchema.ts +++ b/src/ParseSchema.ts @@ -1,8 +1,98 @@ import CoreManager from './CoreManager'; import ParseObject from './ParseObject'; import ParseCLP from './ParseCLP'; - +import type ParseGeoPoint from './ParseGeoPoint'; +import type ParseFile from './ParseFile'; +import type ParsePolygon from './ParsePolygon'; +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'; + +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 + | Bytes + | Date + | ParseFile + | ParseGeoPoint + | ParsePolygon + | any[] + | object + | Pointer + | ParseRelation = any, +> { + required?: boolean | undefined; + defaultValue?: T | undefined; + targetClass?: string | undefined; +} + +interface Index { + [fieldName: string]: number | string; +} + +interface CLPField { + '*'?: boolean | undefined; + requiresAuthentication?: boolean | undefined; + [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; + readUserFields?: string[] | undefined; + writeUserFields?: string[] | undefined; + protectedFields?: { + [userIdOrRoleName: string]: string[]; + }; +} + +interface RestSchema { + className: string; + fields: { + [key: string]: { + type: string; + targetClass?: string; + required?: boolean; + defaultValue?: string; + }; + }; + classLevelPermissions: CLP; + indexes?: { + [key: string]: { + [key: string]: any; + }; + }; +} const FIELD_TYPES = [ 'String', @@ -19,12 +109,6 @@ const FIELD_TYPES = [ 'Relation', ]; -type FieldOptions = { - required?: boolean; - defaultValue?: any; - targetClass?: string; -}; - /** * A Parse.Schema object is for handling schema data from Parse. *

All the schemas methods require MasterKey. @@ -42,7 +126,7 @@ type FieldOptions = { * * @alias Parse.Schema */ -class ParseSchema { +class ParseSchema { className: string; _fields: { [key: string]: any }; _indexes: { [key: string]: any }; @@ -70,7 +154,7 @@ class ParseSchema { * @returns {Promise} A promise that is resolved with the result when * the query completes. */ - static all() { + static all(): Promise { const controller = CoreManager.getSchemaController(); return controller.get('').then(response => { if (response.results.length === 0) { @@ -86,7 +170,7 @@ class ParseSchema { * @returns {Promise} A promise that is resolved with the result when * the query completes. */ - get() { + get(): Promise { this.assertClassName(); const controller = CoreManager.getSchemaController(); @@ -104,7 +188,7 @@ class ParseSchema { * @returns {Promise} A promise that is resolved with the result when * the query completes. */ - save() { + save(): Promise { this.assertClassName(); const controller = CoreManager.getSchemaController(); @@ -115,7 +199,7 @@ class ParseSchema { classLevelPermissions: this._clp, }; - return controller.create(this.className, params); + return controller.create(this.className, params) as Promise; } /** @@ -124,7 +208,7 @@ class ParseSchema { * @returns {Promise} A promise that is resolved with the result when * the query completes. */ - update() { + update(): Promise { this.assertClassName(); const controller = CoreManager.getSchemaController(); @@ -138,7 +222,7 @@ class ParseSchema { this._fields = {}; this._indexes = {}; - return controller.update(this.className, params); + return controller.update(this.className, params) as Promise; } /** @@ -148,7 +232,7 @@ class ParseSchema { * @returns {Promise} A promise that is resolved with the result when * the query completes. */ - delete() { + delete(): Promise { this.assertClassName(); const controller = CoreManager.getSchemaController(); @@ -162,7 +246,7 @@ class ParseSchema { * @returns {Promise} A promise that is resolved with the result when * the query completes. */ - purge() { + purge(): Promise { this.assertClassName(); const controller = CoreManager.getSchemaController(); @@ -187,7 +271,7 @@ class ParseSchema { * @param {object | Parse.CLP} clp Class Level Permissions * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - setCLP(clp: PermissionsMap | ParseCLP) { + setCLP(clp: PermissionsMap | ParseCLP): this { if (clp instanceof ParseCLP) { this._clp = clp.toJSON(); } else { @@ -209,9 +293,9 @@ class ParseSchema { * * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addField(name: string, type: string, options: FieldOptions = {}) { - type = type || 'String'; - + addField(name: string, type?: T, options?: FieldOptions): this { + type = (type || 'String') as T; + options = options || {}; if (!name) { throw new Error('field name may not be null.'); } @@ -219,10 +303,10 @@ class ParseSchema { throw new Error(`${type} is not a valid type.`); } if (type === 'Pointer') { - return this.addPointer(name, options.targetClass!, options); + return this.addPointer(name as any, options.targetClass!, options); } if (type === 'Relation') { - return this.addRelation(name, options.targetClass!); + return this.addRelation(name as any, options.targetClass!); } const fieldOptions: Partial & { type: string; @@ -242,7 +326,7 @@ class ParseSchema { }; } } - if (type === 'Bytes') { + if (type === ('Bytes' as T)) { if (options && options.defaultValue) { fieldOptions.defaultValue = { __type: 'Bytes', @@ -265,16 +349,14 @@ class ParseSchema { * schema.addIndex('index_name', { 'field': 1 }); * */ - addIndex(name: string, index: any) { + addIndex(name: string, index: Index): this { if (!name) { throw new Error('index name may not be null.'); } if (!index) { throw new Error('index may not be null.'); } - this._indexes[name] = index; - return this; } @@ -285,7 +367,7 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addString(name: string, options: FieldOptions) { + addString(name: AttrType, options?: FieldOptions): this { return this.addField(name, 'String', options); } @@ -296,7 +378,7 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addNumber(name: string, options: FieldOptions) { + addNumber(name: AttrType, options?: FieldOptions): this { return this.addField(name, 'Number', options); } @@ -307,7 +389,7 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addBoolean(name: string, options: FieldOptions) { + addBoolean(name: AttrType, options?: FieldOptions): this { return this.addField(name, 'Boolean', options); } @@ -318,7 +400,7 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addBytes(name: string, options: FieldOptions) { + addBytes(name: AttrType, options?: FieldOptions): this { return this.addField(name, 'Bytes', options); } @@ -329,7 +411,7 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addDate(name: string, options: FieldOptions) { + addDate(name: AttrType, options?: FieldOptions): this { return this.addField(name, 'Date', options); } @@ -340,7 +422,7 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addFile(name: string, options: FieldOptions) { + addFile(name: AttrType, options?: FieldOptions) { return this.addField(name, 'File', options); } @@ -351,7 +433,7 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addGeoPoint(name: string, options: FieldOptions) { + addGeoPoint(name: AttrType, options?: FieldOptions): this { return this.addField(name, 'GeoPoint', options); } @@ -362,7 +444,7 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addPolygon(name: string, options: FieldOptions) { + addPolygon(name: AttrType, options?: FieldOptions): this { return this.addField(name, 'Polygon', options); } @@ -373,7 +455,7 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addArray(name: string, options: FieldOptions) { + addArray(name: AttrType, options?: FieldOptions): this { return this.addField(name, 'Array', options); } @@ -384,7 +466,7 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addObject(name: string, options: FieldOptions) { + addObject(name: AttrType, options?: FieldOptions): this { return this.addField(name, 'Object', options); } @@ -396,7 +478,11 @@ class ParseSchema { * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addPointer(name: string, targetClass: string, options: FieldOptions = {}) { + addPointer( + name: AttrType, + targetClass: string, + options?: FieldOptions + ): this { if (!name) { throw new Error('field name may not be null.'); } @@ -407,10 +493,10 @@ class ParseSchema { type: string; } = { type: 'Pointer', targetClass }; - if (typeof options.required === 'boolean') { + if (typeof options?.required === 'boolean') { fieldOptions.required = options.required; } - if (options.defaultValue !== undefined) { + if (options?.defaultValue !== undefined) { fieldOptions.defaultValue = options.defaultValue; if (options.defaultValue instanceof ParseObject) { fieldOptions.defaultValue = options.defaultValue.toPointer(); @@ -427,19 +513,17 @@ class ParseSchema { * @param {string} targetClass Name of the target Pointer Class * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - addRelation(name: string, targetClass: string) { + addRelation(name: AttrType, targetClass: string) { if (!name) { throw new Error('field name may not be null.'); } if (!targetClass) { throw new Error('You need to set the targetClass of the Relation.'); } - this._fields[name] = { type: 'Relation', targetClass, }; - return this; } @@ -449,7 +533,7 @@ class ParseSchema { * @param {string} name Name of the field * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - deleteField(name: string) { + deleteField(name: string): this { this._fields[name] = { __op: 'Delete' }; return this; } @@ -460,7 +544,7 @@ class ParseSchema { * @param {string} name Name of the field * @returns {Parse.Schema} Returns the schema, so you can chain this call. */ - deleteIndex(name: string) { + deleteIndex(name: string): this { this._indexes[name] = { __op: 'Delete' }; return this; } diff --git a/src/ParseSession.ts b/src/ParseSession.ts index e783a305b..ab84f23b9 100644 --- a/src/ParseSession.ts +++ b/src/ParseSession.ts @@ -1,8 +1,9 @@ import CoreManager from './CoreManager'; import isRevocableSession from './isRevocableSession'; -import ParseObject from './ParseObject'; +import ParseObject, { Attributes } from './ParseObject'; import ParseUser from './ParseUser'; +import type { AttributeKey } from './ParseObject'; import type { RequestOptions, FullOptions } from './RESTController'; /** @@ -13,15 +14,15 @@ import type { RequestOptions, FullOptions } from './RESTController'; * @alias Parse.Session * @augments Parse.Object */ -class ParseSession extends ParseObject { +class ParseSession extends ParseObject { /** * @param {object} attributes The initial set of data to store in the user. */ - constructor(attributes?: any) { + constructor(attributes?: T) { super('_Session'); if (attributes && typeof attributes === 'object') { try { - this.set(attributes || {}); + this.set((attributes || {}) as any); } catch (_) { throw new Error("Can't create an invalid Session"); } @@ -34,14 +35,14 @@ class ParseSession extends ParseObject { * @returns {string} */ getSessionToken(): string { - const token = this.get('sessionToken'); + const token = this.get('sessionToken' as AttributeKey); if (typeof token === 'string') { return token; } return ''; } - static readOnlyAttributes() { + static readOnlyAttributes(): string[] { return ['createdWith', 'expiresAt', 'installationId', 'restricted', 'sessionToken', 'user']; } @@ -54,7 +55,7 @@ class ParseSession extends ParseObject { * object after it has been fetched. If there is no current user, the * promise will be rejected. */ - static current(options: FullOptions) { + static current(options?: FullOptions): Promise { const controller = CoreManager.getSessionController(); const sessionOptions = ParseObject._getRequestOptions(options); @@ -63,7 +64,7 @@ class ParseSession extends ParseObject { return Promise.reject('There is no current user.'); } sessionOptions.sessionToken = user.getSessionToken(); - return controller.getSession(sessionOptions); + return controller.getSession(sessionOptions) as Promise; }); } @@ -89,7 +90,7 @@ class ParseSession extends ParseObject { ParseObject.registerSubclass('_Session', ParseSession); const DefaultController = { - getSession(options: RequestOptions): Promise { + getSession(options?: RequestOptions): Promise { const RESTController = CoreManager.getRESTController(); const session = new ParseSession(); diff --git a/src/ParseUser.ts b/src/ParseUser.ts index 47be73de2..730790f4c 100644 --- a/src/ParseUser.ts +++ b/src/ParseUser.ts @@ -1,17 +1,17 @@ import CoreManager from './CoreManager'; import isRevocableSession from './isRevocableSession'; import ParseError from './ParseError'; -import ParseObject from './ParseObject'; +import ParseObject, { Attributes } from './ParseObject'; import Storage from './Storage'; -import type { AttributeMap } from './ObjectStateMutations'; +import type { AttributeKey } from './ParseObject'; import type { RequestOptions, FullOptions } from './RESTController'; export type AuthData = { [key: string]: any }; -export type AuthProviderType = { +export type AuthProvider = { authenticate?(options: { - error?: (provider: AuthProviderType, error: string | any) => void; - success?: (provider: AuthProviderType, result: AuthData) => void; + error?: (provider: AuthProvider, error: string | any) => void; + success?: (provider: AuthProvider, result: AuthData) => void; }): void; restoreAuthentication(authData: any): boolean; getAuthType(): string; @@ -22,7 +22,7 @@ let canUseCurrentUser = !CoreManager.get('IS_NODE'); let currentUserCacheMatchesDisk = false; let currentUserCache: ParseUser | null = null; -const authProviders: { [key: string]: AuthProviderType } = {}; +const authProviders: { [key: string]: AuthProvider } = {}; /** *

A Parse.User object is a local representation of a user persisted to the @@ -34,15 +34,15 @@ const authProviders: { [key: string]: AuthProviderType } = {}; * @alias Parse.User * @augments Parse.Object */ -class ParseUser extends ParseObject { +class ParseUser extends ParseObject { /** * @param {object} attributes The initial set of data to store in the user. */ - constructor(attributes?: AttributeMap) { + constructor(attributes?: T) { super('_User'); if (attributes && typeof attributes === 'object') { try { - this.set(attributes || {}); + this.set((attributes || {}) as any); } catch (_) { throw new Error("Can't create an invalid Parse User"); } @@ -60,7 +60,7 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is resolved when the replacement * token has been fetched. */ - _upgradeToRevocableSession(options: RequestOptions): Promise { + _upgradeToRevocableSession(options?: RequestOptions): Promise { const upgradeOptions = ParseObject._getRequestOptions(options); const controller = CoreManager.getUserController(); return controller.upgradeToRevocableSession(this, upgradeOptions); @@ -83,7 +83,7 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled with the user is linked */ linkWith( - provider: AuthProviderType, + provider: string | AuthProvider, options: { authData?: AuthData }, saveOpts: FullOptions = {} ): Promise { @@ -109,12 +109,12 @@ class ParseUser extends ParseObject { authType = provider.getAuthType(); } if (options && Object.hasOwn(options, 'authData')) { - const authData = this.get('authData') || {}; + const authData = this.get('authData' as AttributeKey) || {}; if (typeof authData !== 'object') { throw new Error('Invalid type: authData field should be an object'); } authData[authType] = options.authData; - const oldAnonymousData = authData.anonymous; + const oldAnonymousData = (authData as any).anonymous; this.stripAnonymity(); const controller = CoreManager.getUserController(); @@ -168,7 +168,7 @@ class ParseUser extends ParseObject { * * @param provider */ - _synchronizeAuthData(provider: string | AuthProviderType) { + _synchronizeAuthData(provider: string | AuthProvider) { if (!this.isCurrent() || !provider) { return; } @@ -179,7 +179,7 @@ class ParseUser extends ParseObject { } else { authType = provider.getAuthType(); } - const authData = this.get('authData'); + const authData = this.get('authData' as AttributeKey); if (!provider || !authData || typeof authData !== 'object') { return; } @@ -193,7 +193,7 @@ class ParseUser extends ParseObject { * Synchronizes authData for all providers. */ _synchronizeAllAuthData() { - const authData = this.get('authData'); + const authData = this.get('authData' as AttributeKey); if (typeof authData !== 'object') { return; } @@ -210,7 +210,7 @@ class ParseUser extends ParseObject { if (!this.isCurrent()) { return; } - const authData = this.get('authData'); + const authData = this.get('authData' as AttributeKey); if (typeof authData !== 'object') { return; } @@ -250,7 +250,7 @@ class ParseUser extends ParseObject { } else { authType = provider.getAuthType(); } - const authData = this.get('authData') || {}; + const authData = this.get('authData' as AttributeKey) || {}; if (typeof authData !== 'object') { return false; } @@ -261,7 +261,7 @@ class ParseUser extends ParseObject { * Deauthenticates all providers. */ _logOutWithAll() { - const authData = this.get('authData'); + const authData = this.get('authData' as AttributeKey); if (typeof authData !== 'object') { return; } @@ -295,9 +295,9 @@ class ParseUser extends ParseObject { * * @returns {object} sessionToken */ - _preserveFieldsOnFetch(): AttributeMap { + _preserveFieldsOnFetch(): Attributes { return { - sessionToken: this.get('sessionToken'), + sessionToken: this.get('sessionToken' as AttributeKey), }; } @@ -322,7 +322,7 @@ class ParseUser extends ParseObject { } stripAnonymity() { - const authData = this.get('authData'); + const authData = this.get('authData' as AttributeKey); if (authData && typeof authData === 'object' && Object.hasOwn(authData, 'anonymous')) { // We need to set anonymous to null instead of deleting it in order to remove it from Parse. authData.anonymous = null; @@ -331,7 +331,7 @@ class ParseUser extends ParseObject { restoreAnonimity(anonymousData: any) { if (anonymousData) { - const authData = this.get('authData'); + const authData = this.get('authData' as AttributeKey); authData.anonymous = anonymousData; } } @@ -342,7 +342,7 @@ class ParseUser extends ParseObject { * @returns {string} */ getUsername(): string | null { - const username = this.get('username'); + const username = this.get('username' as AttributeKey); if (username == null || typeof username === 'string') { return username; } @@ -356,7 +356,7 @@ class ParseUser extends ParseObject { */ setUsername(username: string) { this.stripAnonymity(); - this.set('username', username); + this.set('username' as AttributeKey, username as any); } /** @@ -365,7 +365,7 @@ class ParseUser extends ParseObject { * @param {string} password User's Password */ setPassword(password: string) { - this.set('password', password); + this.set('password' as AttributeKey, password as any); } /** @@ -374,7 +374,7 @@ class ParseUser extends ParseObject { * @returns {string} User's Email */ getEmail(): string | null { - const email = this.get('email'); + const email = this.get('email' as AttributeKey); if (email == null || typeof email === 'string') { return email; } @@ -388,7 +388,7 @@ class ParseUser extends ParseObject { * @returns {boolean} */ setEmail(email: string) { - return this.set('email', email); + return this.set('email' as AttributeKey, email as any); } /** @@ -399,7 +399,7 @@ class ParseUser extends ParseObject { * @returns {string} the session token, or undefined */ getSessionToken(): string | null { - const token = this.get('sessionToken'); + const token = this.get('sessionToken' as AttributeKey); if (token == null || typeof token === 'string') { return token; } @@ -413,7 +413,7 @@ class ParseUser extends ParseObject { */ authenticated(): boolean { const current = ParseUser.current(); - return !!this.get('sessionToken') && !!current && current.id === this.id; + return !!this.get('sessionToken' as AttributeKey) && !!current && current.id === this.id; } /** @@ -436,8 +436,8 @@ class ParseUser extends ParseObject { * finishes. */ signUp( - attrs: AttributeMap, - options?: FullOptions & { context?: AttributeMap } + attrs?: Attributes | null, + options?: FullOptions & { context?: Attributes } ): Promise { const signupOptions = ParseObject._getRequestOptions(options); const controller = CoreManager.getUserController(); @@ -462,7 +462,7 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled with the user when * the login is complete. */ - logIn(options: FullOptions & { context?: AttributeMap } = {}): Promise { + logIn(options: FullOptions & { context?: Attributes } = {}): Promise { const loginOptions = ParseObject._getRequestOptions(options); if (!Object.hasOwn(loginOptions, 'usePost')) { loginOptions.usePost = true; @@ -510,11 +510,11 @@ class ParseUser extends ParseObject { * @param {...any} args * @returns {Parse.User} */ - async fetch(...args: Array): Promise { + async fetch(...args: Array): Promise { await super.fetch.apply(this, args); const current = await this.isCurrentAsync(); if (current) { - return CoreManager.getUserController().updateUserOnDisk(this); + return CoreManager.getUserController().updateUserOnDisk(this) as Promise; } return this; } @@ -526,11 +526,11 @@ class ParseUser extends ParseObject { * @param {...any} args * @returns {Parse.User} */ - async fetchWithInclude(...args: Array): Promise { + async fetchWithInclude(...args: Array): Promise { await super.fetchWithInclude.apply(this, args); const current = await this.isCurrentAsync(); if (current) { - return CoreManager.getUserController().updateUserOnDisk(this); + return CoreManager.getUserController().updateUserOnDisk(this) as Promise; } return this; } @@ -597,14 +597,14 @@ class ParseUser extends ParseObject { * either from memory or localStorage, if necessary. * * @static - * @returns {Parse.Object} The currently logged in Parse.User. + * @returns {Parse.User} The currently logged in Parse.User. */ - static current(): ParseUser | null { + static current(): T | null { if (!canUseCurrentUser) { return null; } const controller = CoreManager.getUserController(); - return controller.currentUser(); + return controller.currentUser() as T; } /** @@ -614,12 +614,12 @@ class ParseUser extends ParseObject { * @returns {Promise} A Promise that is resolved with the currently * logged in Parse User */ - static currentAsync(): Promise { + static currentAsync(): Promise { if (!canUseCurrentUser) { return Promise.resolve(null); } const controller = CoreManager.getUserController(); - return controller.currentUserAsync(); + return controller.currentUserAsync() as Promise; } /** @@ -636,12 +636,17 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled with the user when * the signup completes. */ - static signUp(username: string, password: string, attrs: AttributeMap, options?: FullOptions) { + static signUp( + username: string, + password: string, + attrs: Attributes, + options?: FullOptions + ): Promise { attrs = attrs || {}; attrs.username = username; attrs.password = password; const user = new this(attrs); - return user.signUp({}, options); + return user.signUp({}, options) as Promise; } /** @@ -656,15 +661,19 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled with the user when * the login completes. */ - static logIn(username: string, password: string, options?: FullOptions) { + static logIn( + username: string, + password: string, + options?: FullOptions + ): Promise { if (typeof username !== 'string') { return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Username must be a string.')); } else if (typeof password !== 'string') { return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Password must be a string.')); } const user = new this(); - user._finishFetch({ username: username, password: password }); - return user.logIn(options); + user._finishFetch({ username, password }); + return user.logIn(options) as Promise; } /** @@ -680,12 +689,12 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled with the user when * the login completes. */ - static logInWithAdditionalAuth( + static logInWithAdditionalAuth( username: string, password: string, authData: AuthData, options?: FullOptions - ) { + ): Promise { if (typeof username !== 'string') { return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Username must be a string.')); } @@ -696,8 +705,8 @@ class ParseUser extends ParseObject { return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Auth must be an object.')); } const user = new this(); - user._finishFetch({ username: username, password: password, authData }); - return user.logIn(options); + user._finishFetch({ username, password, authData }); + return user.logIn(options) as Promise; } /** @@ -710,7 +719,7 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled with the user when * the login completes. */ - static loginAs(userId: string) { + static loginAs(userId: string): Promise { if (!userId) { throw new ParseError( ParseError.USERNAME_MISSING, @@ -719,7 +728,7 @@ class ParseUser extends ParseObject { } const controller = CoreManager.getUserController(); const user = new this(); - return controller.loginAs(user, userId); + return controller.loginAs(user, userId) as Promise; } /** @@ -734,7 +743,7 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled with the user when * the login completes. */ - static become(sessionToken: string, options?: RequestOptions) { + static become(sessionToken: string, options?: RequestOptions): Promise { if (!canUseCurrentUser) { throw new Error('It is not memory-safe to become a user in a server environment'); } @@ -742,7 +751,7 @@ class ParseUser extends ParseObject { becomeOptions.sessionToken = sessionToken; const controller = CoreManager.getUserController(); const user = new this(); - return controller.become(user, becomeOptions); + return controller.become(user, becomeOptions) as Promise; } /** @@ -754,12 +763,12 @@ class ParseUser extends ParseObject { * @static * @returns {Promise} A promise that is fulfilled with the user is fetched. */ - static me(sessionToken: string, options: RequestOptions = {}) { + static me(sessionToken: string, options?: RequestOptions): Promise { const controller = CoreManager.getUserController(); const meOptions = ParseObject._getRequestOptions(options); meOptions.sessionToken = sessionToken; const user = new this(); - return controller.me(user, meOptions); + return controller.me(user, meOptions) as Promise; } /** @@ -772,10 +781,10 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled with the user when * the login completes. */ - static hydrate(userJSON: AttributeMap) { + static hydrate(userJSON: Attributes): Promise { const controller = CoreManager.getUserController(); const user = new this(); - return controller.hydrate(user, userJSON); + return controller.hydrate(user, userJSON) as Promise; } /** @@ -788,13 +797,13 @@ class ParseUser extends ParseObject { * @static * @returns {Promise} */ - static logInWith( - provider: any, + static logInWith( + provider: string | AuthProvider, options: { authData?: AuthData }, saveOpts?: FullOptions - ): Promise { + ): Promise { const user = new this(); - return user.linkWith(provider, options, saveOpts); + return user.linkWith(provider, options, saveOpts) as Promise; } /** @@ -807,7 +816,7 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is resolved when the session is * destroyed on the server. */ - static logOut(options: RequestOptions = {}) { + static logOut(options?: RequestOptions): Promise { const controller = CoreManager.getUserController(); return controller.logOut(options); } @@ -827,7 +836,7 @@ class ParseUser extends ParseObject { * @static * @returns {Promise} */ - static requestPasswordReset(email: string, options?: RequestOptions) { + static requestPasswordReset(email: string, options?: RequestOptions): Promise { const requestOptions = ParseObject._getRequestOptions(options); const controller = CoreManager.getUserController(); return controller.requestPasswordReset(email, requestOptions); @@ -846,7 +855,7 @@ class ParseUser extends ParseObject { * @static * @returns {Promise} */ - static requestEmailVerification(email: string, options?: RequestOptions) { + static requestEmailVerification(email: string, options?: RequestOptions): Promise { const requestOptions = ParseObject._getRequestOptions(options); const controller = CoreManager.getUserController(); return controller.requestEmailVerification(email, requestOptions); @@ -863,7 +872,11 @@ class ParseUser extends ParseObject { * the password regardless of whether the email has been verified. This requires the master key. * @returns {Promise} A promise that is fulfilled with a user when the password is correct. */ - static verifyPassword(username: string, password: string, options?: RequestOptions) { + static verifyPassword( + username: string, + password: string, + options?: RequestOptions + ): Promise { if (typeof username !== 'string') { return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Username must be a string.')); } @@ -873,7 +886,7 @@ class ParseUser extends ParseObject { } const controller = CoreManager.getUserController(); - return controller.verifyPassword(username, password, options || {}); + return controller.verifyPassword(username, password, options || {}) as Promise; } /** @@ -1099,7 +1112,7 @@ const DefaultController = { }); }, - signUp(user: ParseUser, attrs: AttributeMap, options: RequestOptions): Promise { + signUp(user: ParseUser, attrs: Attributes, options?: RequestOptions): Promise { const username = (attrs && attrs.username) || user.get('username'); const password = (attrs && attrs.password) || user.get('password'); @@ -1125,7 +1138,7 @@ const DefaultController = { }); }, - logIn(user: ParseUser, options: RequestOptions): Promise { + logIn(user: ParseUser, options?: RequestOptions): Promise { const RESTController = CoreManager.getRESTController(); const stateController = CoreManager.getObjectStateController(); const auth = { @@ -1164,7 +1177,7 @@ const DefaultController = { ); }, - become(user: ParseUser, options: RequestOptions): Promise { + become(user: ParseUser, options?: RequestOptions): Promise { const RESTController = CoreManager.getRESTController(); return RESTController.request('GET', 'users/me', {}, options).then(response => { user._finishFetch(response); @@ -1173,7 +1186,7 @@ const DefaultController = { }); }, - hydrate(user: ParseUser, userJSON: AttributeMap): Promise { + hydrate(user: ParseUser, userJSON: Attributes): Promise { user._finishFetch(userJSON); user._setExisted(true); if (userJSON.sessionToken && canUseCurrentUser) { @@ -1183,7 +1196,7 @@ const DefaultController = { } }, - me(user: ParseUser, options: RequestOptions): Promise { + me(user: ParseUser, options?: RequestOptions): Promise { const RESTController = CoreManager.getRESTController(); return RESTController.request('GET', 'users/me', {}, options).then(response => { user._finishFetch(response); @@ -1192,9 +1205,9 @@ const DefaultController = { }); }, - logOut(options: RequestOptions): Promise { + logOut(options?: RequestOptions): Promise { const RESTController = CoreManager.getRESTController(); - if (options.sessionToken) { + if (options?.sessionToken) { return RESTController.request('POST', 'logout', {}, options); } return DefaultController.currentUserAsync().then(currentUser => { @@ -1217,12 +1230,12 @@ const DefaultController = { }); }, - requestPasswordReset(email: string, options: RequestOptions) { + requestPasswordReset(email: string, options?: RequestOptions) { const RESTController = CoreManager.getRESTController(); - return RESTController.request('POST', 'requestPasswordReset', { email: email }, options); + return RESTController.request('POST', 'requestPasswordReset', { email }, options); }, - async upgradeToRevocableSession(user: ParseUser, options: RequestOptions) { + async upgradeToRevocableSession(user: ParseUser, options?: RequestOptions) { const token = user.getSessionToken(); if (!token) { return Promise.reject( @@ -1251,7 +1264,7 @@ const DefaultController = { }); }, - verifyPassword(username: string, password: string, options: RequestOptions) { + verifyPassword(username: string, password: string, options?: RequestOptions) { const RESTController = CoreManager.getRESTController(); const data = { username, @@ -1263,9 +1276,9 @@ const DefaultController = { return RESTController.request('GET', 'verifyPassword', data, options); }, - requestEmailVerification(email: string, options: RequestOptions) { + requestEmailVerification(email: string, options?: RequestOptions) { const RESTController = CoreManager.getRESTController(); - return RESTController.request('POST', 'verificationEmailRequest', { email: email }, options); + return RESTController.request('POST', 'verificationEmailRequest', { email }, options); }, }; diff --git a/src/Push.ts b/src/Push.ts index 2d69980da..18059b626 100644 --- a/src/Push.ts +++ b/src/Push.ts @@ -10,6 +10,8 @@ export type PushData = { push_time?: Date | string; expiration_time?: Date | string; expiration_interval?: number; + data?: any; + channels?: string[]; }; /** diff --git a/src/RESTController.ts b/src/RESTController.ts index c85d58e65..c0ea0b272 100644 --- a/src/RESTController.ts +++ b/src/RESTController.ts @@ -7,6 +7,7 @@ import XhrWeapp from './Xhr.weapp'; export type RequestOptions = { useMasterKey?: boolean; + useMaintenanceKey?: boolean; sessionToken?: string; installationId?: string; returnStatus?: boolean; @@ -23,6 +24,7 @@ export type FullOptions = { success?: any; error?: any; useMasterKey?: boolean; + useMaintenanceKey?: boolean; sessionToken?: string; installationId?: string; progress?: any; @@ -36,6 +38,7 @@ type PayloadType = { _JavaScriptKey?: string; _ClientVersion: string; _MasterKey?: string; + _MaintenanceKey?: string; _RevocableSession?: string; _InstallationId?: string; _SessionToken?: string; @@ -273,7 +276,9 @@ const RESTController = { throw new Error('Cannot use the Master Key, it has not been provided.'); } } - + if (options.useMaintenanceKey) { + payload._MaintenanceKey = CoreManager.get('MAINTENANCE_KEY'); + } if (CoreManager.get('FORCE_REVOCABLE_SESSION')) { payload._RevocableSession = '1'; } @@ -356,5 +361,4 @@ const RESTController = { }, }; -module.exports = RESTController; export default RESTController; diff --git a/src/Socket.weapp.ts b/src/Socket.weapp.ts index 768a48060..63575d49d 100644 --- a/src/Socket.weapp.ts +++ b/src/Socket.weapp.ts @@ -49,5 +49,5 @@ class SocketWeapp { wx.closeSocket(); } } -module.exports = SocketWeapp; + export default SocketWeapp; diff --git a/src/Storage.ts b/src/Storage.ts index 65143619f..45b6ffe43 100644 --- a/src/Storage.ts +++ b/src/Storage.ts @@ -91,5 +91,4 @@ const Storage = { }, }; -module.exports = Storage; export default Storage; diff --git a/src/StorageController.browser.ts b/src/StorageController.browser.ts index 924b5a167..e7962bcf3 100644 --- a/src/StorageController.browser.ts +++ b/src/StorageController.browser.ts @@ -33,5 +33,4 @@ const StorageController = { }, }; -module.exports = StorageController; export default StorageController; diff --git a/src/StorageController.default.ts b/src/StorageController.default.ts index 08ee16e44..53cec60b0 100644 --- a/src/StorageController.default.ts +++ b/src/StorageController.default.ts @@ -31,5 +31,4 @@ const StorageController = { }, }; -module.exports = StorageController; export default StorageController; diff --git a/src/StorageController.react-native.ts b/src/StorageController.react-native.ts index 23658a11c..375b04799 100644 --- a/src/StorageController.react-native.ts +++ b/src/StorageController.react-native.ts @@ -80,5 +80,4 @@ const StorageController = { }, }; -module.exports = StorageController; export default StorageController; diff --git a/src/StorageController.ts b/src/StorageController.ts index 1c26076a0..0f52b1af3 100644 --- a/src/StorageController.ts +++ b/src/StorageController.ts @@ -12,5 +12,5 @@ if (process.env.PARSE_BUILD === 'react-native') { } else if (process.env.PARSE_BUILD === 'weapp') { StorageController = WeappStorageController; } -module.exports = StorageController; + export default StorageController; diff --git a/src/StorageController.weapp.ts b/src/StorageController.weapp.ts index 9cead45e6..80f903e9a 100644 --- a/src/StorageController.weapp.ts +++ b/src/StorageController.weapp.ts @@ -32,5 +32,4 @@ const StorageController = { }, }; -module.exports = StorageController; export default StorageController; diff --git a/src/TaskQueue.ts b/src/TaskQueue.ts index 093481024..92ed530d6 100644 --- a/src/TaskQueue.ts +++ b/src/TaskQueue.ts @@ -51,5 +51,4 @@ class TaskQueue { } } -module.exports = TaskQueue; export default TaskQueue; diff --git a/src/WebSocketController.ts b/src/WebSocketController.ts index e5daa477a..f1e01759f 100644 --- a/src/WebSocketController.ts +++ b/src/WebSocketController.ts @@ -18,5 +18,5 @@ try { } catch (_) { // WebSocket unavailable } -module.exports = WebSocketController; + export default WebSocketController; diff --git a/src/Xhr.weapp.ts b/src/Xhr.weapp.ts index b001c9e9b..ffaa193ad 100644 --- a/src/Xhr.weapp.ts +++ b/src/Xhr.weapp.ts @@ -107,5 +107,5 @@ class XhrWeapp { }); } } -module.exports = XhrWeapp; + export default XhrWeapp; diff --git a/src/__tests__/Analytics-test.js b/src/__tests__/Analytics-test.js index c53933776..13bc7031b 100644 --- a/src/__tests__/Analytics-test.js +++ b/src/__tests__/Analytics-test.js @@ -2,7 +2,7 @@ jest.dontMock('../Analytics'); jest.dontMock('../CoreManager'); const Analytics = require('../Analytics'); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; const defaultController = CoreManager.getAnalyticsController(); diff --git a/src/__tests__/Cloud-test.js b/src/__tests__/Cloud-test.js index 67045f151..6ed1e84e1 100644 --- a/src/__tests__/Cloud-test.js +++ b/src/__tests__/Cloud-test.js @@ -9,7 +9,7 @@ jest.dontMock('../Push'); jest.dontMock('../ParseOp'); const Cloud = require('../Cloud'); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; const Push = require('../Push'); require('../ParseOp'); diff --git a/src/__tests__/CoreManager-test.js b/src/__tests__/CoreManager-test.js index 0dd3aafd1..3cfd8a6f0 100644 --- a/src/__tests__/CoreManager-test.js +++ b/src/__tests__/CoreManager-test.js @@ -1,6 +1,6 @@ jest.dontMock('../CoreManager'); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; describe('CoreManager', () => { it('is initialized with default values', () => { diff --git a/src/__tests__/EventuallyQueue-test.js b/src/__tests__/EventuallyQueue-test.js index da4486c42..10d622684 100644 --- a/src/__tests__/EventuallyQueue-test.js +++ b/src/__tests__/EventuallyQueue-test.js @@ -34,22 +34,26 @@ class MockObject { return MockSubclass; } } -jest.setMock('../ParseObject', MockObject); +jest.setMock('../ParseObject', { + __esModule: true, + default: MockObject, +}); const mockQueryFind = jest.fn(); -jest.mock('../ParseQuery', () => { - return jest.fn().mockImplementation(function () { +jest.mock('../ParseQuery', () => ({ + __esModule: true, + default: jest.fn().mockImplementation(function () { this.equalTo = jest.fn(); this.find = mockQueryFind; - }); -}); + }), +})); const mockRNStorageInterface = require('./test_helpers/mockRNStorage'); -const CoreManager = require('../CoreManager'); -const EventuallyQueue = require('../EventuallyQueue'); +const CoreManager = require('../CoreManager').default; +const EventuallyQueue = require('../EventuallyQueue').default; const ParseError = require('../ParseError').default; -const ParseObject = require('../ParseObject'); -const RESTController = require('../RESTController'); -const Storage = require('../Storage'); +const ParseObject = require('../ParseObject').default; +const RESTController = require('../RESTController').default; +const Storage = require('../Storage').default; const mockXHR = require('./test_helpers/mockXHR'); const flushPromises = require('./test_helpers/flushPromises'); @@ -65,7 +69,7 @@ describe('EventuallyQueue', () => { beforeEach(async () => { jest.clearAllMocks(); CoreManager.setAsyncStorage(mockRNStorageInterface); - CoreManager.setStorageController(require('../StorageController.react-native')); + CoreManager.setStorageController(require('../StorageController.react-native').default); CoreManager.setRESTController(RESTController); EventuallyQueue.stopPoll(); await EventuallyQueue.clear(); diff --git a/src/__tests__/Hooks-test.js b/src/__tests__/Hooks-test.js index 2bac07f71..41d8ac9ce 100644 --- a/src/__tests__/Hooks-test.js +++ b/src/__tests__/Hooks-test.js @@ -7,8 +7,8 @@ jest.dontMock('../ParseObject'); jest.dontMock('../RESTController'); const Hooks = require('../ParseHooks'); -const CoreManager = require('../CoreManager'); -const RESTController = require('../RESTController'); +const CoreManager = require('../CoreManager').default; +const RESTController = require('../RESTController').default; const defaultController = CoreManager.getHooksController(); const { sendRequest } = defaultController; diff --git a/src/__tests__/InstallationController-test.js b/src/__tests__/InstallationController-test.js index efcb97be9..c76696a6f 100644 --- a/src/__tests__/InstallationController-test.js +++ b/src/__tests__/InstallationController-test.js @@ -15,12 +15,12 @@ jest.mock('../uuid', () => { return () => value++ + ''; }); -const CoreManager = require('../CoreManager'); -const ParseInstallation = require('../ParseInstallation'); -const InstallationController = require('../InstallationController'); -const Storage = require('../Storage'); +const CoreManager = require('../CoreManager').default; +const ParseInstallation = require('../ParseInstallation').default; +const InstallationController = require('../InstallationController').default; +const Storage = require('../Storage').default; -CoreManager.setStorageController(require('../StorageController.default')); +CoreManager.setStorageController(require('../StorageController.default').default); describe('InstallationController', () => { beforeEach(() => { diff --git a/src/__tests__/LiveQueryClient-test.js b/src/__tests__/LiveQueryClient-test.js index be9c90fae..c8fa0ba0c 100644 --- a/src/__tests__/LiveQueryClient-test.js +++ b/src/__tests__/LiveQueryClient-test.js @@ -35,12 +35,12 @@ const mockLocalDatastore = { }; jest.setMock('../LocalDatastore', mockLocalDatastore); -const CoreManager = require('../CoreManager'); -const EventEmitter = require('../EventEmitter'); +const CoreManager = require('../CoreManager').default; +const EventEmitter = require('../EventEmitter').default; const LiveQueryClient = require('../LiveQueryClient').default; const ParseObject = require('../ParseObject').default; const ParseQuery = require('../ParseQuery').default; -const WebSocketController = require('../WebSocketController'); +const WebSocketController = require('../WebSocketController').default; const { resolvingPromise } = require('../promiseUtils'); const events = require('events'); diff --git a/src/__tests__/LocalDatastore-test.js b/src/__tests__/LocalDatastore-test.js index 5c9676836..e6ec14bab 100644 --- a/src/__tests__/LocalDatastore-test.js +++ b/src/__tests__/LocalDatastore-test.js @@ -78,30 +78,36 @@ const mockLocalStorageController = { getAllContents: jest.fn(), clear: jest.fn(), }; -jest.setMock('../ParseObject', MockObject); +jest.setMock('../ParseObject', { + __esModule: true, + default: MockObject, +}); const mockQueryFind = jest.fn(); -jest.mock('../ParseQuery', () => { - return jest.fn().mockImplementation(function () { +jest.mock('../ParseQuery', () => ({ + __esModule: true, + default: jest.fn().mockImplementation(function () { this.equalTo = jest.fn(); this.containedIn = jest.fn(); this.limit = jest.fn(); this.find = mockQueryFind; - }); -}); + }), +})); -const CoreManager = require('../CoreManager'); -const LocalDatastore = require('../LocalDatastore'); -const ParseObject = require('../ParseObject'); -const ParseQuery = require('../ParseQuery'); +const CoreManager = require('../CoreManager').default; +const LocalDatastore = require('../LocalDatastore').default; +const ParseObject = require('../ParseObject').default; +const ParseQuery = require('../ParseQuery').default; const ParseUser = require('../ParseUser').default; -const LocalDatastoreController = require('../LocalDatastoreController'); -const RNDatastoreController = require('../LocalDatastoreController.react-native'); -const BrowserStorageController = require('../StorageController.browser'); -const DefaultStorageController = require('../StorageController.default'); +const LocalDatastoreController = require('../LocalDatastoreController').default; +const RNDatastoreController = require('../LocalDatastoreController.react-native').default; +const BrowserStorageController = require('../StorageController.browser').default; +const DefaultStorageController = require('../StorageController.default').default; // Register our mocks -jest.spyOn(CoreManager, 'getParseObject').mockImplementation(() => require('../ParseObject')); -jest.spyOn(CoreManager, 'getParseQuery').mockImplementation(() => require('../ParseQuery')); +jest + .spyOn(CoreManager, 'getParseObject') + .mockImplementation(() => require('../ParseObject').default); +jest.spyOn(CoreManager, 'getParseQuery').mockImplementation(() => require('../ParseQuery').default); const item1 = new ParseObject('Item'); const item2 = new ParseObject('Item'); diff --git a/src/__tests__/ObjectStateMutations-test.js b/src/__tests__/ObjectStateMutations-test.js index 99dbe5134..e6b118948 100644 --- a/src/__tests__/ObjectStateMutations-test.js +++ b/src/__tests__/ObjectStateMutations-test.js @@ -13,12 +13,12 @@ const mockObject = function (className) { }; mockObject.registerSubclass = function () {}; jest.setMock('../ParseObject', mockObject); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; CoreManager.setParseObject(mockObject); const ObjectStateMutations = require('../ObjectStateMutations'); const ParseOps = require('../ParseOp'); -const TaskQueue = require('../TaskQueue'); +const TaskQueue = require('../TaskQueue').default; describe('ObjectStateMutations', () => { it('can apply server data', () => { diff --git a/src/__tests__/OfflineQuery-test.js b/src/__tests__/OfflineQuery-test.js index 5d1e645a5..a80f5e6e7 100644 --- a/src/__tests__/OfflineQuery-test.js +++ b/src/__tests__/OfflineQuery-test.js @@ -1,7 +1,6 @@ jest.autoMockOff(); -const matchesQuery = require('../OfflineQuery').matchesQuery; -const validateQuery = require('../OfflineQuery').validateQuery; +const { matchesQuery, validateQuery } = require('../OfflineQuery').default; const ParseError = require('../ParseError').default; const ParseObject = require('../ParseObject').default; const ParseQuery = require('../ParseQuery').default; diff --git a/src/__tests__/Parse-test.js b/src/__tests__/Parse-test.js index e68ea8253..a968de268 100644 --- a/src/__tests__/Parse-test.js +++ b/src/__tests__/Parse-test.js @@ -11,7 +11,7 @@ jest.dontMock('crypto-js/aes'); jest.setMock('../EventuallyQueue', { poll: jest.fn() }); global.indexedDB = require('./test_helpers/mockIndexedDB'); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; const ParseLiveQuery = require('../ParseLiveQuery').default; const EventuallyQueue = require('../EventuallyQueue'); const Parse = require('../Parse'); @@ -24,10 +24,11 @@ describe('Parse module', () => { expect(CoreManager.get('APPLICATION_ID')).toBe('A'); expect(CoreManager.get('JAVASCRIPT_KEY')).toBe('B'); - Parse._initialize('A', 'B', 'C'); + Parse._initialize('A', 'B', 'C', 'D'); expect(CoreManager.get('APPLICATION_ID')).toBe('A'); expect(CoreManager.get('JAVASCRIPT_KEY')).toBe('B'); expect(CoreManager.get('MASTER_KEY')).toBe('C'); + expect(CoreManager.get('MAINTENANCE_KEY')).toBe('D'); }); it('enables master key use in the node build', () => { @@ -55,6 +56,10 @@ describe('Parse module', () => { expect(CoreManager.get('MASTER_KEY')).toBe('789'); expect(Parse.masterKey).toBe('789'); + Parse.maintenanceKey = '000'; + expect(CoreManager.get('MAINTENANCE_KEY')).toBe('000'); + expect(Parse.maintenanceKey).toBe('000'); + Parse.serverURL = 'http://example.com'; expect(CoreManager.get('SERVER_URL')).toBe('http://example.com'); expect(Parse.serverURL).toBe('http://example.com'); diff --git a/src/__tests__/ParseACL-test.js b/src/__tests__/ParseACL-test.js index 4b4ee0dc4..2ed1921a7 100644 --- a/src/__tests__/ParseACL-test.js +++ b/src/__tests__/ParseACL-test.js @@ -13,7 +13,7 @@ jest.setMock('../ParseRole', mockRole); const ParseACL = require('../ParseACL').default; const ParseUser = require('../ParseUser').default; const ParseRole = require('../ParseRole'); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; CoreManager.setParseRole(require('../ParseRole')); describe('ParseACL', () => { diff --git a/src/__tests__/ParseConfig-test.js b/src/__tests__/ParseConfig-test.js index 135ee91a4..f37779a79 100644 --- a/src/__tests__/ParseConfig-test.js +++ b/src/__tests__/ParseConfig-test.js @@ -16,11 +16,11 @@ jest.dontMock('./test_helpers/mockAsyncStorage'); require('../ParseObject'); require('../ParseOp'); const mockAsyncStorage = require('./test_helpers/mockAsyncStorage'); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; const ParseConfig = require('../ParseConfig').default; const ParseGeoPoint = require('../ParseGeoPoint').default; -const Storage = require('../Storage'); -const StorageController = require('../StorageController.default'); +const Storage = require('../Storage').default; +const StorageController = require('../StorageController.default').default; CoreManager.set('APPLICATION_ID', 'A'); CoreManager.set('JAVASCRIPT_KEY', 'B'); diff --git a/src/__tests__/ParseError-test.js b/src/__tests__/ParseError-test.js index 5bbb5f81c..4cdc81303 100644 --- a/src/__tests__/ParseError-test.js +++ b/src/__tests__/ParseError-test.js @@ -2,7 +2,7 @@ jest.dontMock('../ParseError'); jest.dontMock('../CoreManager'); const ParseError = require('../ParseError').default; -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; describe('ParseError', () => { it('have sensible string representation', () => { diff --git a/src/__tests__/ParseFile-test.js b/src/__tests__/ParseFile-test.js index 09a2669d2..56251b040 100644 --- a/src/__tests__/ParseFile-test.js +++ b/src/__tests__/ParseFile-test.js @@ -8,8 +8,8 @@ const ParseFile = require('../ParseFile').default; const b64Digit = require('../ParseFile').b64Digit; const ParseObject = require('../ParseObject').default; -const CoreManager = require('../CoreManager'); -const EventEmitter = require('../EventEmitter'); +const CoreManager = require('../CoreManager').default; +const EventEmitter = require('../EventEmitter').default; const mockHttp = require('http'); const mockHttps = require('https'); diff --git a/src/__tests__/ParseInstallation-test.js b/src/__tests__/ParseInstallation-test.js index 8ed3993b4..0439e8a40 100644 --- a/src/__tests__/ParseInstallation-test.js +++ b/src/__tests__/ParseInstallation-test.js @@ -13,9 +13,9 @@ jest.dontMock('../SingleInstanceStateController'); jest.dontMock('../UniqueInstanceStateController'); const ParseError = require('../ParseError').default; -const LocalDatastore = require('../LocalDatastore'); -const ParseInstallation = require('../ParseInstallation'); -const CoreManager = require('../CoreManager'); +const LocalDatastore = require('../LocalDatastore').default; +const ParseInstallation = require('../ParseInstallation').default; +const CoreManager = require('../CoreManager').default; describe('ParseInstallation', () => { it('can create ParseInstallation', () => { diff --git a/src/__tests__/ParseLiveQuery-test.js b/src/__tests__/ParseLiveQuery-test.js index 7d00a5943..ba1e74ab7 100644 --- a/src/__tests__/ParseLiveQuery-test.js +++ b/src/__tests__/ParseLiveQuery-test.js @@ -10,8 +10,8 @@ jest.dontMock('../promiseUtils'); // Forces the loading const ParseLiveQuery = require('../ParseLiveQuery').default; -const CoreManager = require('../CoreManager'); -const EventEmitter = require('../EventEmitter'); +const CoreManager = require('../CoreManager').default; +const EventEmitter = require('../EventEmitter').default; const ParseQuery = require('../ParseQuery').default; const LiveQuerySubscription = require('../LiveQuerySubscription').default; const mockLiveQueryClient = { diff --git a/src/__tests__/ParseObject-test.js b/src/__tests__/ParseObject-test.js index 565b57c96..176f6a609 100644 --- a/src/__tests__/ParseObject-test.js +++ b/src/__tests__/ParseObject-test.js @@ -143,8 +143,8 @@ const mockLocalDatastore = { }; jest.setMock('../LocalDatastore', mockLocalDatastore); -const CoreManager = require('../CoreManager'); -const EventuallyQueue = require('../EventuallyQueue'); +const CoreManager = require('../CoreManager').default; +const EventuallyQueue = require('../EventuallyQueue').default; const ParseACL = require('../ParseACL').default; const ParseError = require('../ParseError').default; const ParseFile = require('../ParseFile').default; @@ -152,7 +152,7 @@ const ParseGeoPoint = require('../ParseGeoPoint').default; const ParsePolygon = require('../ParsePolygon').default; const ParseObject = require('../ParseObject').default; const ParseOp = require('../ParseOp'); -const RESTController = require('../RESTController'); +const RESTController = require('../RESTController').default; const SingleInstanceStateController = require('../SingleInstanceStateController'); const unsavedChildren = require('../unsavedChildren').default; @@ -965,7 +965,7 @@ describe('ParseObject', () => { o.validate({ 'invalid!key': 12, }) - ).toEqual(new ParseError(ParseError.INVALID_KEY_NAME, `Invalid key name: "invalid!key"`)); + ).toEqual(new ParseError(ParseError.INVALID_KEY_NAME, 'Invalid key name: invalid!key')); expect( o.validate({ @@ -988,7 +988,7 @@ describe('ParseObject', () => { expect(o.set('ACL', { '*': { read: true, write: false } })).toBe(o); expect(() => { o.set('$$$', 'o_O'); - }).toThrow(new ParseError(ParseError.INVALID_KEY_NAME, `Invalid key name: "$$$"`)); + }).toThrow(new ParseError(ParseError.INVALID_KEY_NAME, 'Invalid key name: $$$')); }); it('ignores validation if ignoreValidation option is passed to set()', () => { @@ -1003,6 +1003,8 @@ describe('ParseObject', () => { expect(o.isValid()).toBe(true); o.set('someKey', 'someValue'); expect(o.isValid()).toBe(true); + o.set('_internalField', 'allow_underscore'); + expect(o.isValid()).toBe(true); o._finishFetch({ objectId: 'O3', 'invalid!key': 'oops', diff --git a/src/__tests__/ParseOp-test.js b/src/__tests__/ParseOp-test.js index 838904523..82075d251 100644 --- a/src/__tests__/ParseOp-test.js +++ b/src/__tests__/ParseOp-test.js @@ -20,22 +20,30 @@ mockObject.fromJSON = function (json) { return new mockObject(json.className, json.objectId); }; mockObject.registerSubclass = function () {}; -jest.setMock('../ParseObject', mockObject); +jest.setMock('../ParseObject', { + __esModule: true, + default: mockObject, +}); const mockRelation = function (parent, key) { this.parent = parent; this.key = key; }; -jest.setMock('../ParseRelation', mockRelation); +jest.setMock('../ParseRelation', { + __esModule: true, + default: mockRelation, +}); -const ParseRelation = require('../ParseRelation'); -const ParseObject = require('../ParseObject'); +const ParseRelation = require('../ParseRelation').default; +const ParseObject = require('../ParseObject').default; const ParseOp = require('../ParseOp'); -const CoreManager = require('../CoreManager'); -jest.spyOn(CoreManager, 'getParseObject').mockImplementation(() => require('../ParseObject')); +const CoreManager = require('../CoreManager').default; +jest + .spyOn(CoreManager, 'getParseObject') + .mockImplementation(() => require('../ParseObject').default); jest .spyOn(CoreManager, 'getEventuallyQueue') - .mockImplementation(() => require('../EventuallyQueue')); + .mockImplementation(() => require('../EventuallyQueue').default); const { Op, SetOp, UnsetOp, IncrementOp, AddOp, AddUniqueOp, RemoveOp, RelationOp, opFromJSON } = ParseOp; diff --git a/src/__tests__/ParseQuery-test.js b/src/__tests__/ParseQuery-test.js index 22413dc80..5cad3c1fb 100644 --- a/src/__tests__/ParseQuery-test.js +++ b/src/__tests__/ParseQuery-test.js @@ -26,8 +26,8 @@ const mockLocalDatastore = { }; jest.setMock('../LocalDatastore', mockLocalDatastore); -let CoreManager = require('../CoreManager'); -const EventEmitter = require('../EventEmitter'); +let CoreManager = require('../CoreManager').default; +const EventEmitter = require('../EventEmitter').default; const ParseError = require('../ParseError').default; const ParseGeoPoint = require('../ParseGeoPoint').default; let ParseObject = require('../ParseObject').default; @@ -1263,6 +1263,7 @@ describe('ParseQuery', () => { }, }); expect(options.useMasterKey).toEqual(true); + expect(options.useMaintenanceKey).toEqual(true); expect(options.sessionToken).toEqual('1234'); return Promise.resolve({ results: [], @@ -1274,6 +1275,7 @@ describe('ParseQuery', () => { q.equalTo('size', 'small') .first({ useMasterKey: true, + useMaintenanceKey: true, sessionToken: '1234', }) .then(obj => { @@ -1440,6 +1442,7 @@ describe('ParseQuery', () => { }, }); expect(options.useMasterKey).toEqual(true); + expect(options.useMaintenanceKey).toEqual(true); expect(options.sessionToken).toEqual('1234'); expect(options.context).toEqual(context); return Promise.resolve({ @@ -1451,6 +1454,7 @@ describe('ParseQuery', () => { const q = new ParseQuery('Item'); q.get('I27', { useMasterKey: true, + useMaintenanceKey: true, sessionToken: '1234', context: context, }).then(() => { @@ -1587,6 +1591,7 @@ describe('ParseQuery', () => { }, }); expect(options.useMasterKey).toEqual(true); + expect(options.useMaintenanceKey).toEqual(true); expect(options.sessionToken).toEqual('1234'); expect(options.context).toEqual(context); return Promise.resolve({ @@ -1599,6 +1604,7 @@ describe('ParseQuery', () => { q.containedIn('size', ['small', 'medium']) .find({ useMasterKey: true, + useMaintenanceKey: true, sessionToken: '1234', context: context, }) @@ -1713,6 +1719,7 @@ describe('ParseQuery', () => { it('passes options through to the REST API', async () => { const batchOptions = { useMasterKey: true, + useMaintenanceKey: true, sessionToken: '1234', batchSize: 50, }; @@ -1727,6 +1734,7 @@ describe('ParseQuery', () => { where: {}, }); expect(options.useMasterKey).toBe(true); + expect(options.useMaintenanceKey).toEqual(true); expect(options.sessionToken).toEqual('1234'); }); @@ -1840,6 +1848,7 @@ describe('ParseQuery', () => { it('passes options through to the REST API', async () => { const batchOptions = { useMasterKey: true, + useMaintenanceKey: true, sessionToken: '1234', batchSize: 50, json: true, @@ -1855,6 +1864,7 @@ describe('ParseQuery', () => { where: {}, }); expect(options.useMasterKey).toBe(true); + expect(options.useMaintenanceKey).toEqual(true); expect(options.sessionToken).toEqual('1234'); expect(options.json).toEqual(true); }); @@ -1962,6 +1972,7 @@ describe('ParseQuery', () => { }, }); expect(options.useMasterKey).toEqual(true); + expect(options.useMaintenanceKey).toEqual(true); expect(options.sessionToken).toEqual('1234'); expect(options.context).toEqual(context); return Promise.resolve({ @@ -1986,6 +1997,7 @@ describe('ParseQuery', () => { }, { useMasterKey: true, + useMaintenanceKey: true, sessionToken: '1234', context: context, } @@ -2014,6 +2026,7 @@ describe('ParseQuery', () => { hint: '_id_', }); expect(options.useMasterKey).toEqual(true); + expect(options.useMaintenanceKey).toEqual(true); expect(options.sessionToken).toEqual('1234'); expect(options.context).toEqual(context); return Promise.resolve({ @@ -2039,6 +2052,7 @@ describe('ParseQuery', () => { }, { useMasterKey: true, + useMaintenanceKey: true, sessionToken: '1234', context: context, } @@ -2288,7 +2302,7 @@ describe('ParseQuery', () => { jest.dontMock('../ParseObject'); jest.resetModules(); ParseObject = require('../ParseObject').default; - CoreManager = require('../CoreManager'); + CoreManager = require('../CoreManager').default; ParseQuery = require('../ParseQuery').default; ParseObject.enableSingleInstance(); @@ -2338,7 +2352,7 @@ describe('ParseQuery', () => { jest.dontMock('../ParseObject'); jest.resetModules(); ParseObject = require('../ParseObject').default; - CoreManager = require('../CoreManager'); + CoreManager = require('../CoreManager').default; ParseQuery = require('../ParseQuery').default; ParseObject.enableSingleInstance(); @@ -2413,7 +2427,7 @@ describe('ParseQuery', () => { jest.dontMock('../ParseObject'); jest.resetModules(); ParseObject = require('../ParseObject').default; - CoreManager = require('../CoreManager'); + CoreManager = require('../CoreManager').default; ParseQuery = require('../ParseQuery').default; ParseObject.enableSingleInstance(); @@ -2463,7 +2477,7 @@ describe('ParseQuery', () => { jest.dontMock('../ParseObject'); jest.resetModules(); ParseObject = require('../ParseObject').default; - CoreManager = require('../CoreManager'); + CoreManager = require('../CoreManager').default; ParseQuery = require('../ParseQuery').default; ParseObject.enableSingleInstance(); @@ -2761,6 +2775,7 @@ describe('ParseQuery', () => { group: { objectId: '$name' }, }); expect(options.useMasterKey).toEqual(true); + expect(options.useMaintenanceKey).toEqual(true); expect(options.requestTask).toBeDefined(); return Promise.resolve({ results: [], @@ -2882,7 +2897,7 @@ describe('ParseQuery', () => { jest.dontMock('../ParseObject'); jest.resetModules(); ParseObject = require('../ParseObject').default; - CoreManager = require('../CoreManager'); + CoreManager = require('../CoreManager').default; ParseQuery = require('../ParseQuery').default; ParseObject.enableSingleInstance(); @@ -2918,7 +2933,7 @@ describe('ParseQuery', () => { jest.dontMock('../ParseObject'); jest.resetModules(); ParseObject = require('../ParseObject').default; - CoreManager = require('../CoreManager'); + CoreManager = require('../CoreManager').default; ParseQuery = require('../ParseQuery').default; ParseObject.enableSingleInstance(); diff --git a/src/__tests__/ParseRelation-test.js b/src/__tests__/ParseRelation-test.js index 92a15e03b..0f789807c 100644 --- a/src/__tests__/ParseRelation-test.js +++ b/src/__tests__/ParseRelation-test.js @@ -40,7 +40,10 @@ mockObject.prototype = { return finalOp; }, }; -jest.setMock('../ParseObject', mockObject); +jest.setMock('../ParseObject', { + __esModule: true, + default: mockObject, +}); const mockQuery = function (className) { this.className = className; @@ -53,11 +56,14 @@ mockQuery.prototype = { this.where[key][comparison] = value; }, }; -jest.setMock('../ParseQuery', mockQuery); +jest.setMock('../ParseQuery', { + __esModule: true, + default: mockQuery, +}); -const ParseObject = require('../ParseObject'); +const ParseObject = require('../ParseObject').default; const ParseRelation = require('../ParseRelation').default; -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; CoreManager.setParseObject(mockObject); CoreManager.setParseQuery(mockQuery); CoreManager.setParseOp(require('../ParseOp')); diff --git a/src/__tests__/ParseSchema-test.js b/src/__tests__/ParseSchema-test.js index b3891a242..540ea90eb 100644 --- a/src/__tests__/ParseSchema-test.js +++ b/src/__tests__/ParseSchema-test.js @@ -12,6 +12,10 @@ const mockObject = function (className, id) { }; }; jest.setMock('../ParseObject', mockObject); +jest.setMock('../ParseObject', { + __esModule: true, + default: mockObject, +}); const mockCLP = function (clp) { this.permissionsMap = clp; @@ -19,12 +23,14 @@ const mockCLP = function (clp) { return { ...this.permissionsMap }; }; }; -jest.setMock('../ParseCLP', mockCLP); - -const ParseObject = require('../ParseObject'); -const ParseCLP = require('../ParseCLP'); +jest.setMock('../ParseCLP', { + __esModule: true, + default: mockCLP, +}); +const ParseObject = require('../ParseObject').default; +const ParseCLP = require('../ParseCLP').default; const ParseSchema = require('../ParseSchema').default; -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; const defaultController = CoreManager.getSchemaController(); diff --git a/src/__tests__/ParseSession-test.js b/src/__tests__/ParseSession-test.js index 6c2108929..54031396d 100644 --- a/src/__tests__/ParseSession-test.js +++ b/src/__tests__/ParseSession-test.js @@ -28,7 +28,7 @@ mockUser.current = function () { }; jest.setMock('../ParseUser', mockUser); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; const ParseObject = require('../ParseObject').default; const ParseSession = require('../ParseSession').default; diff --git a/src/__tests__/ParseUser-test.js b/src/__tests__/ParseUser-test.js index 708666b31..2a0a7b6bf 100644 --- a/src/__tests__/ParseUser-test.js +++ b/src/__tests__/ParseUser-test.js @@ -32,13 +32,13 @@ jest.dontMock('./test_helpers/mockAsyncStorage'); const flushPromises = require('./test_helpers/flushPromises'); const mockAsyncStorage = require('./test_helpers/mockAsyncStorage'); -const CoreManager = require('../CoreManager'); -const CryptoController = require('../CryptoController'); -const StorageController = require('../StorageController.default'); -const LocalDatastore = require('../LocalDatastore'); +const CoreManager = require('../CoreManager').default; +const CryptoController = require('../CryptoController').default; +const StorageController = require('../StorageController.default').default; +const LocalDatastore = require('../LocalDatastore').default; const ParseObject = require('../ParseObject').default; const ParseUser = require('../ParseUser').default; -const Storage = require('../Storage'); +const Storage = require('../Storage').default; const ParseError = require('../ParseError').default; const AnonymousUtils = require('../AnonymousUtils').default; diff --git a/src/__tests__/Push-test.js b/src/__tests__/Push-test.js index 70affe624..4bb32fe3b 100644 --- a/src/__tests__/Push-test.js +++ b/src/__tests__/Push-test.js @@ -12,10 +12,13 @@ mockQuery.prototype = { }; }, }; -jest.setMock('../ParseQuery', mockQuery); +jest.setMock('../ParseQuery', { + __esModule: true, + default: mockQuery, +}); -const CoreManager = require('../CoreManager'); -const ParseQuery = require('../ParseQuery'); +const CoreManager = require('../CoreManager').default; +const ParseQuery = require('../ParseQuery').default; const Push = require('../Push'); const defaultController = CoreManager.getPushController(); diff --git a/src/__tests__/RESTController-test.js b/src/__tests__/RESTController-test.js index 412d5f2e8..5f9d3671b 100644 --- a/src/__tests__/RESTController-test.js +++ b/src/__tests__/RESTController-test.js @@ -5,8 +5,8 @@ jest.mock('../uuid', () => { return () => (value++).toString(); }); -const CoreManager = require('../CoreManager'); -const RESTController = require('../RESTController'); +const CoreManager = require('../CoreManager').default; +const RESTController = require('../RESTController').default; const flushPromises = require('./test_helpers/flushPromises'); const mockXHR = require('./test_helpers/mockXHR'); const mockWeChat = require('./test_helpers/mockWeChat'); @@ -558,6 +558,28 @@ describe('RESTController', () => { }); }); + it('sends the maintenance key when requested', async () => { + CoreManager.set('MAINTENANCE_KEY', 'MK'); + const xhr = { + setRequestHeader: jest.fn(), + open: jest.fn(), + send: jest.fn(), + }; + RESTController._setXHR(function () { + return xhr; + }); + RESTController.request('GET', 'classes/MyObject', {}, { useMaintenanceKey: true }); + await flushPromises(); + expect(JSON.parse(xhr.send.mock.calls[0][0])).toEqual({ + _method: 'GET', + _ApplicationId: 'A', + _JavaScriptKey: 'B', + _MaintenanceKey: 'MK', + _ClientVersion: 'V', + _InstallationId: 'iid', + }); + }); + it('includes the status code when requested', done => { RESTController._setXHR(mockXHR([{ status: 200, response: { success: true } }])); RESTController.request('POST', 'users', {}, { returnStatus: true }).then(response => { @@ -723,7 +745,7 @@ describe('RESTController', () => { }); it('can handle wechat request', async () => { - const XHR = require('../Xhr.weapp'); + const XHR = require('../Xhr.weapp').default; const xhr = new XHR(); jest.spyOn(xhr, 'open'); jest.spyOn(xhr, 'send'); @@ -753,7 +775,7 @@ describe('RESTController', () => { }); it('can handle wechat ajax', async () => { - const XHR = require('../Xhr.weapp'); + const XHR = require('../Xhr.weapp').default; const xhr = new XHR(); jest.spyOn(xhr, 'open'); jest.spyOn(xhr, 'send'); diff --git a/src/__tests__/SingleInstanceStateController-test.js b/src/__tests__/SingleInstanceStateController-test.js index 171f3b2ac..0f7e4c8f4 100644 --- a/src/__tests__/SingleInstanceStateController-test.js +++ b/src/__tests__/SingleInstanceStateController-test.js @@ -12,16 +12,19 @@ jest.dontMock('./test_helpers/flushPromises'); const mockObject = function () {}; mockObject.registerSubclass = function () {}; -jest.setMock('../ParseObject', mockObject); +jest.setMock('../ParseObject', { + __esModule: true, + default: mockObject, +}); jest.useFakeTimers(); const ParseFile = require('../ParseFile').default; const ParseGeoPoint = require('../ParseGeoPoint').default; const ParseOps = require('../ParseOp'); const SingleInstanceStateController = require('../SingleInstanceStateController'); -const TaskQueue = require('../TaskQueue'); +const TaskQueue = require('../TaskQueue').default; const flushPromises = require('./test_helpers/flushPromises'); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; CoreManager.setParseObject(mockObject); describe('SingleInstanceStateController', () => { diff --git a/src/__tests__/Storage-test.js b/src/__tests__/Storage-test.js index 8107e5bc1..a42b105f0 100644 --- a/src/__tests__/Storage-test.js +++ b/src/__tests__/Storage-test.js @@ -3,7 +3,7 @@ jest.autoMockOff(); const mockRNStorageInterface = require('./test_helpers/mockRNStorage'); const mockIndexedDB = require('./test_helpers/mockIndexedDB'); const mockWeChat = require('./test_helpers/mockWeChat'); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; global.wx = mockWeChat; global.indexedDB = mockIndexedDB; @@ -12,7 +12,7 @@ jest.mock('idb-keyval', () => { }); const idbKeyVal = require('idb-keyval'); -const BrowserStorageController = require('../StorageController.browser'); +const BrowserStorageController = require('../StorageController.browser').default; describe('Browser StorageController', () => { beforeEach(() => { @@ -40,7 +40,7 @@ describe('Browser StorageController', () => { }); }); -const RNStorageController = require('../StorageController.react-native'); +const RNStorageController = require('../StorageController.react-native').default; describe('React Native StorageController', () => { beforeEach(() => { @@ -160,7 +160,7 @@ describe('IndexDB StorageController', () => { let IndexedDBStorageController; beforeEach(() => { jest.isolateModules(() => { - IndexedDBStorageController = require('../IndexedDBStorageController'); + IndexedDBStorageController = require('../IndexedDBStorageController').default; }); IndexedDBStorageController.clear(); }); @@ -199,7 +199,7 @@ describe('IndexDB StorageController', () => { it('handle indexedDB is not defined', async () => { global.indexedDB = undefined; - const dbController = require('../IndexedDBStorageController'); + const dbController = require('../IndexedDBStorageController').default; expect(dbController).toBeUndefined(); global.indexedDB = mockIndexedDB; }); @@ -210,14 +210,14 @@ describe('IndexDB StorageController', () => { jest.spyOn(idbKeyVal, 'createStore').mockImplementationOnce(() => { throw new Error('Protected'); }); - const dbController = require('../IndexedDBStorageController'); + const dbController = require('../IndexedDBStorageController').default; expect(dbController).toBeUndefined(); expect(idbKeyVal.createStore).toHaveBeenCalled(); }); }); }); -const DefaultStorageController = require('../StorageController.default'); +const DefaultStorageController = require('../StorageController.default').default; describe('Default StorageController', () => { beforeEach(() => { @@ -245,7 +245,7 @@ describe('Default StorageController', () => { }); }); -const WeappStorageController = require('../StorageController.weapp'); +const WeappStorageController = require('../StorageController.weapp').default; describe('WeChat StorageController', () => { beforeEach(() => { @@ -274,11 +274,11 @@ describe('WeChat StorageController', () => { }); }); -const Storage = require('../Storage'); +const Storage = require('../Storage').default; describe('Storage (Default StorageController)', () => { beforeEach(() => { - CoreManager.setStorageController(require('../StorageController.default')); + CoreManager.setStorageController(require('../StorageController.default').default); }); it('can store and retrieve values', () => { @@ -342,7 +342,7 @@ describe('Storage (Default StorageController)', () => { describe('Storage (Async StorageController)', () => { beforeEach(() => { CoreManager.setAsyncStorage(mockRNStorageInterface); - CoreManager.setStorageController(require('../StorageController.react-native')); + CoreManager.setStorageController(require('../StorageController.react-native').default); }); it('throws when using a synchronous method', () => { diff --git a/src/__tests__/TaskQueue-test.js b/src/__tests__/TaskQueue-test.js index 10d736439..e480c8cba 100644 --- a/src/__tests__/TaskQueue-test.js +++ b/src/__tests__/TaskQueue-test.js @@ -1,6 +1,6 @@ jest.autoMockOff(); -const TaskQueue = require('../TaskQueue'); +const TaskQueue = require('../TaskQueue').default; const { resolvingPromise } = require('../promiseUtils'); const flushPromises = require('./test_helpers/flushPromises'); diff --git a/src/__tests__/UniqueInstanceStateController-test.js b/src/__tests__/UniqueInstanceStateController-test.js index 1c6c53f38..b70145ea5 100644 --- a/src/__tests__/UniqueInstanceStateController-test.js +++ b/src/__tests__/UniqueInstanceStateController-test.js @@ -15,16 +15,19 @@ const mockObject = function (className) { this.className = className; }; mockObject.registerSubclass = function () {}; -jest.setMock('../ParseObject', mockObject); +jest.setMock('../ParseObject', { + __esModule: true, + default: mockObject, +}); const ParseFile = require('../ParseFile').default; const ParseGeoPoint = require('../ParseGeoPoint').default; -const ParseObject = require('../ParseObject'); +const ParseObject = require('../ParseObject').default; const ParseOps = require('../ParseOp'); const UniqueInstanceStateController = require('../UniqueInstanceStateController'); -const TaskQueue = require('../TaskQueue'); +const TaskQueue = require('../TaskQueue').default; const { resolvingPromise } = require('../promiseUtils'); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; CoreManager.setParseObject(mockObject); describe('UniqueInstanceStateController', () => { diff --git a/src/__tests__/arrayContainsObject-test.js b/src/__tests__/arrayContainsObject-test.js index 3381d7387..8956279c2 100644 --- a/src/__tests__/arrayContainsObject-test.js +++ b/src/__tests__/arrayContainsObject-test.js @@ -11,12 +11,17 @@ const mockObject = function (className, id) { mockObject.prototype._getId = function () { return this.id || this._localId; }; -jest.setMock('../ParseObject', mockObject); +jest.setMock('../ParseObject', { + __esModule: true, + default: mockObject, +}); const arrayContainsObject = require('../arrayContainsObject').default; -const ParseObject = require('../ParseObject'); -const CoreManager = require('../CoreManager'); -jest.spyOn(CoreManager, 'getParseObject').mockImplementation(() => require('../ParseObject')); +const ParseObject = require('../ParseObject').default; +const CoreManager = require('../CoreManager').default; +jest + .spyOn(CoreManager, 'getParseObject') + .mockImplementation(() => require('../ParseObject').default); describe('arrayContainsObject', () => { it('detects objects by their id', () => { diff --git a/src/__tests__/browser-test.js b/src/__tests__/browser-test.js index 175cfec4a..c09decc5e 100644 --- a/src/__tests__/browser-test.js +++ b/src/__tests__/browser-test.js @@ -10,7 +10,7 @@ jest.dontMock('../Storage'); jest.dontMock('crypto-js/aes'); jest.setMock('../EventuallyQueue', { poll: jest.fn() }); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; const ParseError = require('../ParseError').default; const EventuallyQueue = require('../EventuallyQueue'); @@ -62,11 +62,11 @@ describe('Browser', () => { }); it('load StorageController', () => { - const StorageController = require('../StorageController'); + const StorageController = require('../StorageController').default; CoreManager.setStorageController(StorageController); jest.spyOn(StorageController, 'setItem'); - const storage = require('../Storage'); + const storage = require('../Storage').default; storage.setItem('key', 'value'); expect(StorageController.setItem).toHaveBeenCalledTimes(1); }); @@ -84,7 +84,7 @@ describe('Browser', () => { } } global.XDomainRequest = XDomainRequest; - const RESTController = require('../RESTController'); + const RESTController = require('../RESTController').default; const options = { progress: () => {}, requestTask: () => {}, @@ -114,7 +114,7 @@ describe('Browser', () => { class XMLHttpRequest {} global.XDomainRequest = XDomainRequest; global.XMLHttpRequest = XMLHttpRequest; - const RESTController = require('../RESTController'); + const RESTController = require('../RESTController').default; try { await RESTController.ajax('POST', 'classes/TestObject'); expect(true).toBe(false); @@ -142,7 +142,7 @@ describe('Browser', () => { class XMLHttpRequest {} global.XDomainRequest = XDomainRequest; global.XMLHttpRequest = XMLHttpRequest; - const RESTController = require('../RESTController'); + const RESTController = require('../RESTController').default; try { await RESTController.ajax('POST', 'classes/TestObject'); expect(true).toBe(false); diff --git a/src/__tests__/canBeSerialized-test.js b/src/__tests__/canBeSerialized-test.js index c65fdddee..c6bd8aac7 100644 --- a/src/__tests__/canBeSerialized-test.js +++ b/src/__tests__/canBeSerialized-test.js @@ -6,8 +6,11 @@ function mockObject(id, attributes) { this.attributes = attributes; } mockObject.registerSubclass = function () {}; -jest.setMock('../ParseObject', mockObject); -const CoreManager = require('../CoreManager'); +jest.setMock('../ParseObject', { + __esModule: true, + default: mockObject, +}); +const CoreManager = require('../CoreManager').default; CoreManager.setParseObject(mockObject); function mockFile(url) { @@ -16,11 +19,14 @@ function mockFile(url) { mockFile.prototype.url = function () { return this._url; }; -jest.setMock('../ParseFile', mockFile); +jest.setMock('../ParseFile', { + __esModule: true, + default: mockFile, +}); const canBeSerialized = require('../canBeSerialized').default; -const ParseFile = require('../ParseFile'); -const ParseObject = require('../ParseObject'); +const ParseFile = require('../ParseFile').default; +const ParseObject = require('../ParseObject').default; const ParseRelation = require('../ParseRelation').default; describe('canBeSerialized', () => { diff --git a/src/__tests__/encode-test.js b/src/__tests__/encode-test.js index 6cf1d142b..57600313d 100644 --- a/src/__tests__/encode-test.js +++ b/src/__tests__/encode-test.js @@ -38,15 +38,18 @@ mockObject.prototype = { return json; }, }; -jest.setMock('../ParseObject', mockObject); +jest.setMock('../ParseObject', { + __esModule: true, + default: mockObject, +}); const encode = require('../encode').default; const ParseACL = require('../ParseACL').default; const ParseFile = require('../ParseFile').default; const ParseGeoPoint = require('../ParseGeoPoint').default; -const ParseObject = require('../ParseObject'); +const ParseObject = require('../ParseObject').default; const ParseRelation = require('../ParseRelation').default; -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; CoreManager.setParseObject(mockObject); CoreManager.setParseOp(require('../ParseOp')); CoreManager.setParseUser(require('../ParseUser').default); diff --git a/src/__tests__/react-native-test.js b/src/__tests__/react-native-test.js index 731684760..521b37f06 100644 --- a/src/__tests__/react-native-test.js +++ b/src/__tests__/react-native-test.js @@ -25,7 +25,7 @@ jest.mock( ); const mockEmitter = require('react-native/Libraries/vendor/emitter/EventEmitter').default; -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; describe('React Native', () => { beforeEach(() => { @@ -37,8 +37,8 @@ describe('React Native', () => { }); it('load EventEmitter', () => { - const eventEmitter = require('../EventEmitter'); - expect(eventEmitter).toEqual(mockEmitter); + const EventEmitter = require('../EventEmitter').default; + expect(EventEmitter).toEqual(mockEmitter); }); it('load CryptoController', () => { @@ -48,31 +48,31 @@ describe('React Native', () => { toString: () => 'World', }; }); - const CryptoController = require('../CryptoController'); + const CryptoController = require('../CryptoController').default; const phrase = CryptoController.encrypt({}, 'salt'); expect(phrase).toBe('World'); expect(CryptoJS.AES.encrypt).toHaveBeenCalled(); }); it('load LocalDatastoreController', () => { - const LocalDatastoreController = require('../LocalDatastoreController'); + const LocalDatastoreController = require('../LocalDatastoreController').default; require('../LocalDatastore'); const LDC = CoreManager.getLocalDatastoreController(); expect(LocalDatastoreController).toEqual(LDC); }); it('load StorageController', () => { - const StorageController = require('../StorageController'); + const StorageController = require('../StorageController').default; CoreManager.setStorageController(StorageController); jest.spyOn(StorageController, 'setItemAsync'); - const storage = require('../Storage'); + const storage = require('../Storage').default; storage.setItemAsync('key', 'value'); expect(StorageController.setItemAsync).toHaveBeenCalledTimes(1); }); it('load WebSocketController', () => { - const WebSocketController = require('../WebSocketController'); + const WebSocketController = require('../WebSocketController').default; CoreManager.setWebSocketController(WebSocketController); jest.mock('../EventEmitter', () => { diff --git a/src/__tests__/unique-test.js b/src/__tests__/unique-test.js index 2d3855230..ff2251135 100644 --- a/src/__tests__/unique-test.js +++ b/src/__tests__/unique-test.js @@ -12,12 +12,17 @@ const mockObject = function (className, id) { mockObject.prototype._getId = function () { return this.id || this._localId; }; -jest.setMock('../ParseObject', mockObject); +jest.setMock('../ParseObject', { + __esModule: true, + default: mockObject, +}); const unique = require('../unique').default; -const ParseObject = require('../ParseObject'); -const CoreManager = require('../CoreManager'); -jest.spyOn(CoreManager, 'getParseObject').mockImplementation(() => require('../ParseObject')); +const ParseObject = require('../ParseObject').default; +const CoreManager = require('../CoreManager').default; +jest + .spyOn(CoreManager, 'getParseObject') + .mockImplementation(() => require('../ParseObject').default); describe('unique', () => { it('produces an array with unique elements', () => { diff --git a/src/__tests__/unsavedChildren-test.js b/src/__tests__/unsavedChildren-test.js index f85a0c7eb..44ca755bd 100644 --- a/src/__tests__/unsavedChildren-test.js +++ b/src/__tests__/unsavedChildren-test.js @@ -18,12 +18,15 @@ mockObject.prototype = { return this._dirty; }, }; -jest.setMock('../ParseObject', mockObject); -const CoreManager = require('../CoreManager'); +jest.setMock('../ParseObject', { + __esModule: true, + default: mockObject, +}); +const CoreManager = require('../CoreManager').default; CoreManager.setParseObject(mockObject); const ParseFile = require('../ParseFile').default; -const ParseObject = require('../ParseObject'); +const ParseObject = require('../ParseObject').default; const ParseRelation = require('../ParseRelation').default; const unsavedChildren = require('../unsavedChildren').default; diff --git a/src/__tests__/weapp-test.js b/src/__tests__/weapp-test.js index c693d087e..d1ef52179 100644 --- a/src/__tests__/weapp-test.js +++ b/src/__tests__/weapp-test.js @@ -15,7 +15,7 @@ jest.dontMock('../uuid'); jest.dontMock('crypto-js/aes'); jest.dontMock('./test_helpers/mockWeChat'); -const CoreManager = require('../CoreManager'); +const CoreManager = require('../CoreManager').default; const mockWeChat = require('./test_helpers/mockWeChat'); global.wx = mockWeChat; @@ -34,22 +34,22 @@ describe('WeChat', () => { }); it('load StorageController', () => { - const StorageController = require('../StorageController'); + const StorageController = require('../StorageController').default; CoreManager.setStorageController(StorageController); jest.spyOn(StorageController, 'setItem'); - const storage = require('../Storage'); + const storage = require('../Storage').default; storage.setItem('key', 'value'); expect(StorageController.setItem).toHaveBeenCalledTimes(1); }); it('load RESTController', () => { - const XHR = require('../Xhr.weapp'); - const RESTController = require('../RESTController'); + const XHR = require('../Xhr.weapp').default; + const RESTController = require('../RESTController').default; expect(RESTController._getXHR()).toEqual(XHR); }); it('load ParseFile', () => { - const XHR = require('../Xhr.weapp'); + const XHR = require('../Xhr.weapp').default; require('../ParseFile'); const fileController = CoreManager.getFileController(); expect(fileController._getXHR()).toEqual(XHR); @@ -65,14 +65,14 @@ describe('WeChat', () => { }); it('load uuid module', () => { - const uuidv4 = require('../uuid'); + const uuidv4 = require('../uuid').default; expect(uuidv4()).not.toEqual(0); expect(uuidv4()).not.toEqual(uuidv4()); }); describe('Socket', () => { it('send', () => { - const Websocket = require('../Socket.weapp'); + const Websocket = require('../Socket.weapp').default; jest.spyOn(mockWeChat, 'connectSocket'); const socket = new Websocket('wss://examples.com'); socket.onopen(); diff --git a/src/uuid.ts b/src/uuid.ts index 1ba54b844..62782451e 100644 --- a/src/uuid.ts +++ b/src/uuid.ts @@ -20,5 +20,4 @@ if (process.env.PARSE_BUILD === 'weapp') { uuid = v4; } -module.exports = uuid; export default uuid; diff --git a/types/Analytics.d.ts b/types/Analytics.d.ts index ae2ff3ac9..498c9c912 100644 --- a/types/Analytics.d.ts +++ b/types/Analytics.d.ts @@ -37,9 +37,6 @@ * @returns {Promise} A promise that is resolved when the round-trip * to the server completes. */ -export declare function track( - name: string, - dimensions: { +export declare function track(name: string, dimensions: { [key: string]: string; - } -): Promise; +}): Promise; diff --git a/types/AnonymousUtils.d.ts b/types/AnonymousUtils.d.ts index d7517bf94..aedb277d4 100644 --- a/types/AnonymousUtils.d.ts +++ b/types/AnonymousUtils.d.ts @@ -29,56 +29,56 @@ import type { RequestOptions } from './RESTController'; * @static */ declare const AnonymousUtils: { - /** - * Gets whether the user has their account linked to anonymous user. - * - * @function isLinked - * @name Parse.AnonymousUtils.isLinked - * @param {Parse.User} user User to check for. - * The user must be logged in on this device. - * @returns {boolean} true if the user has their account - * linked to an anonymous user. - * @static - */ - isLinked(user: ParseUser): boolean; - /** - * Logs in a user Anonymously. - * - * @function logIn - * @name Parse.AnonymousUtils.logIn - * @param {object} options MasterKey / SessionToken. - * @returns {Promise} Logged in user - * @static - */ - logIn(options?: RequestOptions): Promise; - /** - * Links Anonymous User to an existing PFUser. - * - * @function link - * @name Parse.AnonymousUtils.link - * @param {Parse.User} user User to link. This must be the current user. - * @param {object} options MasterKey / SessionToken. - * @returns {Promise} Linked with User - * @static - */ - link(user: ParseUser, options?: RequestOptions): Promise; - /** - * Returns true if Authentication Provider has been registered for use. - * - * @function isRegistered - * @name Parse.AnonymousUtils.isRegistered - * @returns {boolean} - * @static - */ - isRegistered(): boolean; - _getAuthProvider(): { - restoreAuthentication(): boolean; - getAuthType(): string; - getAuthData(): { - authData: { - id: string; - }; + /** + * Gets whether the user has their account linked to anonymous user. + * + * @function isLinked + * @name Parse.AnonymousUtils.isLinked + * @param {Parse.User} user User to check for. + * The user must be logged in on this device. + * @returns {boolean} true if the user has their account + * linked to an anonymous user. + * @static + */ + isLinked(user: ParseUser): boolean; + /** + * Logs in a user Anonymously. + * + * @function logIn + * @name Parse.AnonymousUtils.logIn + * @param {object} options MasterKey / SessionToken. + * @returns {Promise} Logged in user + * @static + */ + logIn(options?: RequestOptions): Promise; + /** + * Links Anonymous User to an existing PFUser. + * + * @function link + * @name Parse.AnonymousUtils.link + * @param {Parse.User} user User to link. This must be the current user. + * @param {object} options MasterKey / SessionToken. + * @returns {Promise} Linked with User + * @static + */ + link(user: ParseUser, options?: RequestOptions): Promise; + /** + * Returns true if Authentication Provider has been registered for use. + * + * @function isRegistered + * @name Parse.AnonymousUtils.isRegistered + * @returns {boolean} + * @static + */ + isRegistered(): boolean; + _getAuthProvider(): { + restoreAuthentication(): boolean; + getAuthType(): string; + getAuthData(): { + authData: { + id: string; + }; + }; }; - }; }; export default AnonymousUtils; diff --git a/types/Cloud.d.ts b/types/Cloud.d.ts index 5fe5a74c5..7a288f908 100644 --- a/types/Cloud.d.ts +++ b/types/Cloud.d.ts @@ -30,7 +30,10 @@ import type { RequestOptions } from './RESTController'; * @returns {Promise} A promise that will be resolved with the result * of the function. */ -export declare function run(name: string, data: any, options: RequestOptions): Promise; +export declare function run any>(name: string, data?: null, options?: RequestOptions): Promise>; +export declare function run[0]]: Parameters[0][P]; +}) => any>(name: string, data: Parameters[0], options?: RequestOptions): Promise>; /** * Gets data for the current set of cloud jobs. * diff --git a/types/CoreManager.d.ts b/types/CoreManager.d.ts index f7aeefda3..93148d43c 100644 --- a/types/CoreManager.d.ts +++ b/types/CoreManager.d.ts @@ -13,367 +13,313 @@ import type ParseSession from './ParseSession'; import type { HookDeclaration, HookDeleteArg } from './ParseHooks'; import type ParseConfig from './ParseConfig'; import type LiveQueryClient from './LiveQueryClient'; -import type ParseSchema from './ParseSchema'; import type ParseInstallation from './ParseInstallation'; type AnalyticsController = { - track: ( - name: string, - dimensions: { - [key: string]: string; - } - ) => Promise; + track: (name: string, dimensions: { + [key: string]: string; + }) => Promise; }; type CloudController = { - run: (name: string, data: any, options: RequestOptions) => Promise; - getJobsData: (options: RequestOptions) => Promise; - /** Returns promise which resolves with JobStatusId of the job */ - startJob: (name: string, data: any, options: RequestOptions) => Promise; + run: (name: string, data: any, options?: RequestOptions) => Promise; + getJobsData: (options?: RequestOptions) => Promise; + /** Returns promise which resolves with JobStatusId of the job */ + startJob: (name: string, data: any, options?: RequestOptions) => Promise; }; type ConfigController = { - current: () => Promise | ParseConfig; - get: (opts?: RequestOptions) => Promise; - save: ( - attrs: { - [key: string]: any; - }, - masterKeyOnlyFlags?: { - [key: string]: any; - } - ) => Promise; + current: () => Promise | ParseConfig; + get: (opts?: RequestOptions) => Promise; + save: (attrs: { + [key: string]: any; + }, masterKeyOnlyFlags?: { + [key: string]: any; + }) => Promise; }; type CryptoController = { - encrypt: (obj: any, secretKey: string) => string; - decrypt: (encryptedText: string, secretKey: any) => string; + encrypt: (obj: any, secretKey: string) => string; + decrypt: (encryptedText: string, secretKey: any) => string; }; type FileController = { - saveFile: (name: string, source: FileSource, options?: FullOptions) => Promise; - saveBase64: ( - name: string, - source: FileSource, - options?: FileSaveOptions - ) => Promise<{ - name: string; - url: string; - }>; - download: ( - uri: string, - options?: any - ) => Promise<{ - base64?: string; - contentType?: string; - }>; - deleteFile: ( - name: string, - options?: { - useMasterKey?: boolean; - } - ) => Promise; + saveFile: (name: string, source: FileSource, options?: FullOptions) => Promise; + saveBase64: (name: string, source: FileSource, options?: FileSaveOptions) => Promise<{ + name: string; + url: string; + }>; + download: (uri: string, options?: any) => Promise<{ + base64?: string; + contentType?: string; + }>; + deleteFile: (name: string, options?: { + useMasterKey?: boolean; + }) => Promise; }; type InstallationController = { - currentInstallationId: () => Promise; - currentInstallation: () => Promise; - updateInstallationOnDisk: (installation: ParseInstallation) => Promise; + currentInstallationId: () => Promise; + currentInstallation: () => Promise; + updateInstallationOnDisk: (installation: ParseInstallation) => Promise; }; type ObjectController = { - fetch: ( - object: ParseObject | Array, - forceFetch: boolean, - options: RequestOptions - ) => Promise | ParseObject | undefined>; - save: ( - object: ParseObject | Array | null, - options: RequestOptions - ) => Promise | ParseFile | undefined>; - destroy: ( - object: ParseObject | Array, - options: RequestOptions - ) => Promise>; + fetch: (object: ParseObject | Array, forceFetch: boolean, options?: RequestOptions) => Promise | ParseObject | undefined>; + save: (object: ParseObject | Array | null, options?: RequestOptions) => Promise | ParseFile | undefined>; + destroy: (object: ParseObject | Array, options?: RequestOptions) => Promise>; }; type ObjectStateController = { - getState: (obj: any) => State | null; - initializeState: (obj: any, initial?: State) => State; - removeState: (obj: any) => State | null; - getServerData: (obj: any) => AttributeMap; - setServerData: (obj: any, attributes: AttributeMap) => void; - getPendingOps: (obj: any) => Array; - setPendingOp: (obj: any, attr: string, op?: Op) => void; - pushPendingState: (obj: any) => void; - popPendingState: (obj: any) => OpsMap | undefined; - mergeFirstPendingState: (obj: any) => void; - getObjectCache: (obj: any) => ObjectCache; - estimateAttribute: (obj: any, attr: string) => any; - estimateAttributes: (obj: any) => AttributeMap; - commitServerChanges: (obj: any, changes: AttributeMap) => void; - enqueueTask: (obj: any, task: () => Promise) => Promise; - clearAllState: () => void; - duplicateState: (source: any, dest: any) => void; + getState: (obj: any) => State | null; + initializeState: (obj: any, initial?: State) => State; + removeState: (obj: any) => State | null; + getServerData: (obj: any) => AttributeMap; + setServerData: (obj: any, attributes: AttributeMap) => void; + getPendingOps: (obj: any) => Array; + setPendingOp: (obj: any, attr: string, op?: Op) => void; + pushPendingState: (obj: any) => void; + popPendingState: (obj: any) => OpsMap | undefined; + mergeFirstPendingState: (obj: any) => void; + getObjectCache: (obj: any) => ObjectCache; + estimateAttribute: (obj: any, attr: string) => any; + estimateAttributes: (obj: any) => AttributeMap; + commitServerChanges: (obj: any, changes: AttributeMap) => void; + enqueueTask: (obj: any, task: () => Promise) => Promise; + clearAllState: () => void; + duplicateState: (source: any, dest: any) => void; }; type PushController = { - send: (data: PushData, options?: FullOptions) => Promise; + send: (data: PushData, options?: FullOptions) => Promise; }; type QueryController = { - find( - className: string, - params: QueryJSON, - options: RequestOptions - ): Promise<{ - results?: Array; - className?: string; - count?: number; - }>; - aggregate( - className: string, - params: any, - options: RequestOptions - ): Promise<{ - results?: Array; - }>; + find(className: string, params: QueryJSON, options?: RequestOptions): Promise<{ + results?: Array; + className?: string; + count?: number; + }>; + aggregate(className: string, params: any, options?: RequestOptions): Promise<{ + results?: Array; + }>; }; -type EventuallyQueue = { - save: (object: ParseObject, serverOptions: SaveOptions) => Promise; - destroy: (object: ParseObject, serverOptions: RequestOptions) => Promise; - poll: (ms?: number) => void; +export type QueueObject = { + queueId: string; + action: string; + object: ParseObject; + serverOptions: SaveOptions | RequestOptions; + id: string; + className: string; + hash: string; + createdAt: Date; +}; +export type Queue = Array; +export type EventuallyQueue = { + save: (object: ParseObject, serverOptions?: SaveOptions) => Promise; + destroy: (object: ParseObject, serverOptions?: RequestOptions) => Promise; + generateQueueId: (action: string, object: ParseObject) => string; + enqueue(action: string, object: ParseObject, serverOptions?: SaveOptions | RequestOptions): Promise; + store(data: Queue): Promise; + load(): Promise; + getQueue(): Promise; + setQueue(queue: Queue): Promise; + remove(queueId: string): Promise; + clear(): Promise; + queueItemExists(queue: Queue, queueId: string): number; + length(): Promise; + sendQueue(): Promise; + sendQueueCallback(object: ParseObject, queueObject: QueueObject): Promise; + poll(ms?: number): void; + stopPoll(): void; + isPolling(): boolean; + process: { + create(ObjectType: any, queueObject: any): Promise; + byId(ObjectType: any, queueObject: any): Promise; + byHash(ObjectType: any, queueObject: any): Promise; + }; }; type RESTController = { - request: (method: string, path: string, data?: any, options?: RequestOptions) => Promise; - ajax: ( - method: string, - url: string, - data: any, - headers?: any, - options?: FullOptions - ) => Promise; - handleError: (err?: any) => void; + request: (method: string, path: string, data?: any, options?: RequestOptions) => Promise; + ajax: (method: string, url: string, data: any, headers?: any, options?: FullOptions) => Promise; + handleError: (err?: any) => void; }; type SchemaController = { - purge: (className: string) => Promise; - get: ( - className: string, - options?: RequestOptions - ) => Promise<{ - results: ParseSchema[]; - }>; - delete: (className: string, options?: RequestOptions) => Promise; - create: (className: string, params: any, options?: RequestOptions) => Promise; - update: (className: string, params: any, options?: RequestOptions) => Promise; - send(className: string, method: string, params: any, options: RequestOptions): Promise; + purge: (className: string) => Promise; + get: (className: string, options?: RequestOptions) => Promise; + delete: (className: string, options?: RequestOptions) => Promise; + create: (className: string, params: any, options?: RequestOptions) => Promise; + update: (className: string, params: any, options?: RequestOptions) => Promise; + send(className: string, method: string, params: any, options?: RequestOptions): Promise; }; type SessionController = { - getSession: (token: RequestOptions) => Promise; + getSession: (options?: RequestOptions) => Promise; +}; +type StorageController = { + async: 0; + getItem: (path: string) => string | null; + setItem: (path: string, value: string) => void; + removeItem: (path: string) => void; + getItemAsync?: (path: string) => Promise; + setItemAsync?: (path: string, value: string) => Promise; + removeItemAsync?: (path: string) => Promise; + clear: () => void; + getAllKeys?: () => Array; + getAllKeysAsync?: () => Promise>; +} | { + async: 1; + getItem?: (path: string) => string | null; + setItem?: (path: string, value: string) => void; + removeItem?: (path: string) => void; + getItemAsync: (path: string) => Promise; + setItemAsync: (path: string, value: string) => Promise; + removeItemAsync: (path: string) => Promise; + clear: () => void; + getAllKeys?: () => Array; + getAllKeysAsync?: () => Promise>; }; -type StorageController = - | { - async: 0; - getItem: (path: string) => string | null; - setItem: (path: string, value: string) => void; - removeItem: (path: string) => void; - getItemAsync?: (path: string) => Promise; - setItemAsync?: (path: string, value: string) => Promise; - removeItemAsync?: (path: string) => Promise; - clear: () => void; - getAllKeys?: () => Array; - getAllKeysAsync?: () => Promise>; - } - | { - async: 1; - getItem?: (path: string) => string | null; - setItem?: (path: string, value: string) => void; - removeItem?: (path: string) => void; - getItemAsync: (path: string) => Promise; - setItemAsync: (path: string, value: string) => Promise; - removeItemAsync: (path: string) => Promise; - clear: () => void; - getAllKeys?: () => Array; - getAllKeysAsync?: () => Promise>; - }; type LocalDatastoreController = { - fromPinWithName: (name: string) => any | undefined; - pinWithName: (name: string, objects: any) => void; - unPinWithName: (name: string) => void; - getAllContents: () => any | undefined; - clear: () => void; + fromPinWithName: (name: string) => any | undefined; + pinWithName: (name: string, objects: any) => void; + unPinWithName: (name: string) => void; + getAllContents: () => any | undefined; + clear: () => void; }; type UserController = { - setCurrentUser: (user: ParseUser) => Promise; - currentUser: () => ParseUser | null; - currentUserAsync: () => Promise; - signUp: (user: ParseUser, attrs: AttributeMap, options: RequestOptions) => Promise; - logIn: (user: ParseUser, options: RequestOptions) => Promise; - loginAs: (user: ParseUser, userId: string) => Promise; - become: (user: ParseUser, options: RequestOptions) => Promise; - hydrate: (user: ParseUser, userJSON: AttributeMap) => Promise; - logOut: (options: RequestOptions) => Promise; - me: (user: ParseUser, options: RequestOptions) => Promise; - requestPasswordReset: (email: string, options: RequestOptions) => Promise; - updateUserOnDisk: (user: ParseUser) => Promise; - upgradeToRevocableSession: (user: ParseUser, options: RequestOptions) => Promise; - linkWith: (user: ParseUser, authData: AuthData, options?: FullOptions) => Promise; - removeUserFromDisk: () => Promise; - verifyPassword: ( - username: string, - password: string, - options: RequestOptions - ) => Promise; - requestEmailVerification: (email: string, options: RequestOptions) => Promise; + setCurrentUser: (user: ParseUser) => Promise; + currentUser: () => ParseUser | null; + currentUserAsync: () => Promise; + signUp: (user: ParseUser, attrs: AttributeMap, options?: RequestOptions) => Promise; + logIn: (user: ParseUser, options?: RequestOptions) => Promise; + loginAs: (user: ParseUser, userId: string) => Promise; + become: (user: ParseUser, options?: RequestOptions) => Promise; + hydrate: (user: ParseUser, userJSON: AttributeMap) => Promise; + logOut: (options?: RequestOptions) => Promise; + me: (user: ParseUser, options?: RequestOptions) => Promise; + requestPasswordReset: (email: string, options?: RequestOptions) => Promise; + updateUserOnDisk: (user: ParseUser) => Promise; + upgradeToRevocableSession: (user: ParseUser, options?: RequestOptions) => Promise; + linkWith: (user: ParseUser, authData: AuthData, options?: FullOptions) => Promise; + removeUserFromDisk: () => Promise; + verifyPassword: (username: string, password: string, options?: RequestOptions) => Promise; + requestEmailVerification: (email: string, options?: RequestOptions) => Promise; }; type HooksController = { - get: (type: string, functionName?: string, triggerName?: string) => Promise; - create: (hook: HookDeclaration) => Promise; - remove: (hook: HookDeleteArg) => Promise; - update: (hook: HookDeclaration) => Promise; - sendRequest?: (method: string, path: string, body?: any) => Promise; + get: (type: string, functionName?: string, triggerName?: string) => Promise; + create: (hook: HookDeclaration) => Promise; + remove: (hook: HookDeleteArg) => Promise; + update: (hook: HookDeclaration) => Promise; + sendRequest?: (method: string, path: string, body?: any) => Promise; }; type LiveQueryControllerType = { - setDefaultLiveQueryClient(liveQueryClient: LiveQueryClient): void; - getDefaultLiveQueryClient(): Promise; - _clearCachedDefaultClient(): void; + setDefaultLiveQueryClient(liveQueryClient: LiveQueryClient): void; + getDefaultLiveQueryClient(): Promise; + _clearCachedDefaultClient(): void; }; /** Based on https://github.com/react-native-async-storage/async-storage/blob/main/packages/default-storage-backend/src/types.ts */ type AsyncStorageType = { - /** Fetches an item for a `key` and invokes a callback upon completion. */ - getItem: ( - key: string, - callback?: (error?: Error | null, result?: string | null) => void - ) => Promise; - /** Sets the value for a `key` and invokes a callback upon completion. */ - setItem: (key: string, value: string, callback?: (error?: Error | null) => void) => Promise; - /** Removes an item for a `key` and invokes a callback upon completion. */ - removeItem: (key: string, callback?: (error?: Error | null) => void) => Promise; - /** Merges an existing `key` value with an input value, assuming both values are stringified JSON. */ - mergeItem: ( - key: string, - value: string, - callback?: (error?: Error | null) => void - ) => Promise; - /** - * Erases *all* `AsyncStorage` for all clients, libraries, etc. You probably - * don't want to call this; use `removeItem` or `multiRemove` to clear only - * your app's keys. - */ - clear: (callback?: (error?: Error | null) => void) => Promise; - /** Gets *all* keys known to your app; for all callers, libraries, etc. */ - getAllKeys: ( - callback?: (error?: Error | null, result?: readonly string[] | null) => void - ) => Promise; - /** - * This allows you to batch the fetching of items given an array of `key` - * inputs. Your callback will be invoked with an array of corresponding - * key-value pairs found. - */ - multiGet: ( - keys: readonly string[], - callback?: ( - errors?: readonly (Error | null)[] | null, - result?: readonly [string, string][] - ) => void - ) => Promise; - /** - * Use this as a batch operation for storing multiple key-value pairs. When - * the operation completes you'll get a single callback with any errors. - * - * See https://react-native-async-storage.github.io/async-storage/docs/api#multiset - */ - multiSet: ( - keyValuePairs: [string, string][], - callback?: (errors?: readonly (Error | null)[] | null) => void - ) => Promise; - /** - * Call this to batch the deletion of all keys in the `keys` array. - * - * See https://react-native-async-storage.github.io/async-storage/docs/api#multiremove - */ - multiRemove: ( - keys: readonly string[], - callback?: (errors?: readonly (Error | null)[] | null) => void - ) => Promise; - /** - * Batch operation to merge in existing and new values for a given set of - * keys. This assumes that the values are stringified JSON. - * - * See https://react-native-async-storage.github.io/async-storage/docs/api#multimerge - */ - multiMerge: ( - keyValuePairs: [string, string][], - callback?: (errors?: readonly (Error | null)[] | null) => void - ) => Promise; + /** Fetches an item for a `key` and invokes a callback upon completion. */ + getItem: (key: string, callback?: (error?: Error | null, result?: string | null) => void) => Promise; + /** Sets the value for a `key` and invokes a callback upon completion. */ + setItem: (key: string, value: string, callback?: (error?: Error | null) => void) => Promise; + /** Removes an item for a `key` and invokes a callback upon completion. */ + removeItem: (key: string, callback?: (error?: Error | null) => void) => Promise; + /** Merges an existing `key` value with an input value, assuming both values are stringified JSON. */ + mergeItem: (key: string, value: string, callback?: (error?: Error | null) => void) => Promise; + /** + * Erases *all* `AsyncStorage` for all clients, libraries, etc. You probably + * don't want to call this; use `removeItem` or `multiRemove` to clear only + * your app's keys. + */ + clear: (callback?: (error?: Error | null) => void) => Promise; + /** Gets *all* keys known to your app; for all callers, libraries, etc. */ + getAllKeys: (callback?: (error?: Error | null, result?: readonly string[] | null) => void) => Promise; + /** + * This allows you to batch the fetching of items given an array of `key` + * inputs. Your callback will be invoked with an array of corresponding + * key-value pairs found. + */ + multiGet: (keys: readonly string[], callback?: (errors?: readonly (Error | null)[] | null, result?: readonly [string, string][]) => void) => Promise; + /** + * Use this as a batch operation for storing multiple key-value pairs. When + * the operation completes you'll get a single callback with any errors. + * + * See https://react-native-async-storage.github.io/async-storage/docs/api#multiset + */ + multiSet: (keyValuePairs: [string, string][], callback?: (errors?: readonly (Error | null)[] | null) => void) => Promise; + /** + * Call this to batch the deletion of all keys in the `keys` array. + * + * See https://react-native-async-storage.github.io/async-storage/docs/api#multiremove + */ + multiRemove: (keys: readonly string[], callback?: (errors?: readonly (Error | null)[] | null) => void) => Promise; + /** + * Batch operation to merge in existing and new values for a given set of + * keys. This assumes that the values are stringified JSON. + * + * See https://react-native-async-storage.github.io/async-storage/docs/api#multimerge + */ + multiMerge: (keyValuePairs: [string, string][], callback?: (errors?: readonly (Error | null)[] | null) => void) => Promise; }; export type WebSocketController = { - onopen: () => void; - onmessage: (message: any) => void; - onclose: (arg?: any) => void; - onerror: (error: any) => void; - send: (data: any) => void; - close: () => void; + onopen: () => void; + onmessage: (message: any) => void; + onclose: (arg?: any) => void; + onerror: (error: any) => void; + send: (data: any) => void; + close: () => void; }; declare const CoreManager: { - get: (key: string) => any; - set: (key: string, value: any) => void; - setIfNeeded: (key: string, value: any) => any; - setAnalyticsController(controller: AnalyticsController): void; - getAnalyticsController(): AnalyticsController; - setCloudController(controller: CloudController): void; - getCloudController(): CloudController; - setConfigController(controller: ConfigController): void; - getConfigController(): ConfigController; - setCryptoController(controller: CryptoController): void; - getCryptoController(): CryptoController; - setEventEmitter(eventEmitter: any): void; - getEventEmitter(): any; - setFileController(controller: FileController): void; - setEventuallyQueue(controller: EventuallyQueue): void; - getEventuallyQueue(): EventuallyQueue; - getFileController(): FileController; - setInstallationController(controller: InstallationController): void; - getInstallationController(): InstallationController; - setLiveQuery(liveQuery: any): void; - getLiveQuery(): any; - setObjectController(controller: ObjectController): void; - getObjectController(): ObjectController; - setObjectStateController(controller: ObjectStateController): void; - getObjectStateController(): ObjectStateController; - setPushController(controller: PushController): void; - getPushController(): PushController; - setQueryController(controller: QueryController): void; - getQueryController(): QueryController; - setRESTController(controller: RESTController): void; - getRESTController(): RESTController; - setSchemaController(controller: SchemaController): void; - getSchemaController(): SchemaController; - setSessionController(controller: SessionController): void; - getSessionController(): SessionController; - setStorageController(controller: StorageController): void; - setLocalDatastoreController(controller: LocalDatastoreController): void; - getLocalDatastoreController(): LocalDatastoreController; - setLocalDatastore(store: any): void; - getLocalDatastore(): any; - getStorageController(): StorageController; - setAsyncStorage(storage: AsyncStorageType): void; - getAsyncStorage(): AsyncStorageType; - setWebSocketController( - controller: new ( - url: string | URL, - protocols?: string | string[] | undefined - ) => WebSocketController - ): void; - getWebSocketController(): new ( - url: string | URL, - protocols?: string | string[] | undefined - ) => WebSocketController; - setUserController(controller: UserController): void; - getUserController(): UserController; - setLiveQueryController(controller: LiveQueryControllerType): void; - getLiveQueryController(): LiveQueryControllerType; - setHooksController(controller: HooksController): void; - getHooksController(): HooksController; - setParseOp(op: any): void; - getParseOp(): any; - setParseObject(object: any): void; - getParseObject(): any; - setParseQuery(query: any): void; - getParseQuery(): any; - setParseRole(role: any): void; - getParseRole(): any; - setParseUser(user: any): void; - getParseUser(): any; + get: (key: string) => any; + set: (key: string, value: any) => void; + setIfNeeded: (key: string, value: any) => any; + setAnalyticsController(controller: AnalyticsController): void; + getAnalyticsController(): AnalyticsController; + setCloudController(controller: CloudController): void; + getCloudController(): CloudController; + setConfigController(controller: ConfigController): void; + getConfigController(): ConfigController; + setCryptoController(controller: CryptoController): void; + getCryptoController(): CryptoController; + setEventEmitter(eventEmitter: any): void; + getEventEmitter(): any; + setFileController(controller: FileController): void; + setEventuallyQueue(controller: EventuallyQueue): void; + getEventuallyQueue(): EventuallyQueue; + getFileController(): FileController; + setInstallationController(controller: InstallationController): void; + getInstallationController(): InstallationController; + setLiveQuery(liveQuery: any): void; + getLiveQuery(): any; + setObjectController(controller: ObjectController): void; + getObjectController(): ObjectController; + setObjectStateController(controller: ObjectStateController): void; + getObjectStateController(): ObjectStateController; + setPushController(controller: PushController): void; + getPushController(): PushController; + setQueryController(controller: QueryController): void; + getQueryController(): QueryController; + setRESTController(controller: RESTController): void; + getRESTController(): RESTController; + setSchemaController(controller: SchemaController): void; + getSchemaController(): SchemaController; + setSessionController(controller: SessionController): void; + getSessionController(): SessionController; + setStorageController(controller: StorageController): void; + setLocalDatastoreController(controller: LocalDatastoreController): void; + getLocalDatastoreController(): LocalDatastoreController; + setLocalDatastore(store: any): void; + getLocalDatastore(): any; + getStorageController(): StorageController; + setAsyncStorage(storage: AsyncStorageType): void; + getAsyncStorage(): AsyncStorageType; + setWebSocketController(controller: new (url: string | URL, protocols?: string | string[] | undefined) => WebSocketController): void; + getWebSocketController(): new (url: string | URL, protocols?: string | string[] | undefined) => WebSocketController; + setUserController(controller: UserController): void; + getUserController(): UserController; + setLiveQueryController(controller: LiveQueryControllerType): void; + getLiveQueryController(): LiveQueryControllerType; + setHooksController(controller: HooksController): void; + getHooksController(): HooksController; + setParseOp(op: any): void; + getParseOp(): any; + setParseObject(object: any): void; + getParseObject(): any; + setParseQuery(query: any): void; + getParseQuery(): any; + setParseRole(role: any): void; + getParseRole(): any; + setParseUser(user: any): void; + getParseUser(): any; }; export default CoreManager; diff --git a/types/CryptoController.d.ts b/types/CryptoController.d.ts index 362d3eca7..1f6e27162 100644 --- a/types/CryptoController.d.ts +++ b/types/CryptoController.d.ts @@ -1,5 +1,5 @@ declare const CryptoController: { - encrypt(obj: any, secretKey: string): string; - decrypt(encryptedText: string, secretKey: string): string; + encrypt(obj: any, secretKey: string): string; + decrypt(encryptedText: string, secretKey: string): string; }; export default CryptoController; diff --git a/types/EventuallyQueue.d.ts b/types/EventuallyQueue.d.ts index 78d76d077..c45778f0d 100644 --- a/types/EventuallyQueue.d.ts +++ b/types/EventuallyQueue.d.ts @@ -1,17 +1,7 @@ import ParseObject from './ParseObject'; +import type { Queue, QueueObject } from './CoreManager'; import type { SaveOptions } from './ParseObject'; import type { RequestOptions } from './RESTController'; -type QueueObject = { - queueId: string; - action: string; - object: ParseObject; - serverOptions: SaveOptions | RequestOptions; - id: string; - className: string; - hash: string; - createdAt: Date; -}; -type Queue = Array; /** * Provides utility functions to queue objects that will be * saved to the server at a later date. @@ -20,163 +10,159 @@ type Queue = Array; * @static */ declare const EventuallyQueue: { - /** - * Add object to queue with save operation. - * - * @function save - * @name Parse.EventuallyQueue.save - * @param {ParseObject} object Parse.Object to be saved eventually - * @param {object} [serverOptions] See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#save Parse.Object.save} options. - * @returns {Promise} A promise that is fulfilled if object is added to queue. - * @static - * @see Parse.Object#saveEventually - */ - save(object: ParseObject, serverOptions?: SaveOptions): Promise; - /** - * Add object to queue with save operation. - * - * @function destroy - * @name Parse.EventuallyQueue.destroy - * @param {ParseObject} object Parse.Object to be destroyed eventually - * @param {object} [serverOptions] See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#destroy Parse.Object.destroy} options - * @returns {Promise} A promise that is fulfilled if object is added to queue. - * @static - * @see Parse.Object#destroyEventually - */ - destroy(object: ParseObject, serverOptions?: RequestOptions): Promise; - /** - * Generate unique identifier to avoid duplicates and maintain previous state. - * - * @param {string} action save / destroy - * @param {object} object Parse.Object to be queued - * @returns {string} - * @static - * @ignore - */ - generateQueueId(action: string, object: ParseObject): string; - /** - * Build queue object and add to queue. - * - * @param {string} action save / destroy - * @param {object} object Parse.Object to be queued - * @param {object} [serverOptions] - * @returns {Promise} A promise that is fulfilled if object is added to queue. - * @static - * @ignore - */ - enqueue( - action: string, - object: ParseObject, - serverOptions: SaveOptions | RequestOptions - ): Promise; - store(data: QueueObject[]): Promise; - load(): Promise; - /** - * Sets the in-memory queue from local storage and returns. - * - * @function getQueue - * @name Parse.EventuallyQueue.getQueue - * @returns {Promise} - * @static - */ - getQueue(): Promise; - /** - * Saves the queue to local storage - * - * @param {Queue} queue Queue containing Parse.Object data. - * @returns {Promise} A promise that is fulfilled when queue is stored. - * @static - * @ignore - */ - setQueue(queue: Queue): Promise; - /** - * Removes Parse.Object data from queue. - * - * @param {string} queueId Unique identifier for Parse.Object data. - * @returns {Promise} A promise that is fulfilled when queue is stored. - * @static - * @ignore - */ - remove(queueId: string): Promise; - /** - * Removes all objects from queue. - * - * @function clear - * @name Parse.EventuallyQueue.clear - * @returns {Promise} A promise that is fulfilled when queue is cleared. - * @static - */ - clear(): Promise; - /** - * Return the index of a queueId in the queue. Returns -1 if not found. - * - * @param {Queue} queue Queue containing Parse.Object data. - * @param {string} queueId Unique identifier for Parse.Object data. - * @returns {number} - * @static - * @ignore - */ - queueItemExists(queue: Queue, queueId: string): number; - /** - * Return the number of objects in the queue. - * - * @function length - * @name Parse.EventuallyQueue.length - * @returns {Promise} - * @static - */ - length(): Promise; - /** - * Sends the queue to the server. - * - * @function sendQueue - * @name Parse.EventuallyQueue.sendQueue - * @returns {Promise} Returns true if queue was sent successfully. - * @static - */ - sendQueue(): Promise; - /** - * Build queue object and add to queue. - * - * @param {ParseObject} object Parse.Object to be processed - * @param {QueueObject} queueObject Parse.Object data from the queue - * @returns {Promise} A promise that is fulfilled when operation is performed. - * @static - * @ignore - */ - sendQueueCallback(object: ParseObject, queueObject: QueueObject): Promise; - /** - * Start polling server for network connection. - * Will send queue if connection is established. - * - * @function poll - * @name Parse.EventuallyQueue.poll - * @param [ms] Milliseconds to ping the server. Default 2000ms - * @static - */ - poll(ms?: number): void; - /** - * Turns off polling. - * - * @function stopPoll - * @name Parse.EventuallyQueue.stopPoll - * @static - */ - stopPoll(): void; - /** - * Return true if pinging the server. - * - * @function isPolling - * @name Parse.EventuallyQueue.isPolling - * @returns {boolean} - * @static - */ - isPolling(): boolean; - _setPolling(flag: boolean): void; - process: { - create(ObjectType: any, queueObject: any): Promise; - byId(ObjectType: any, queueObject: any): Promise; - byHash(ObjectType: any, queueObject: any): Promise; - }; + /** + * Add object to queue with save operation. + * + * @function save + * @name Parse.EventuallyQueue.save + * @param {ParseObject} object Parse.Object to be saved eventually + * @param {object} [serverOptions] See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#save Parse.Object.save} options. + * @returns {Promise} A promise that is fulfilled if object is added to queue. + * @static + * @see Parse.Object#saveEventually + */ + save(object: ParseObject, serverOptions?: SaveOptions): Promise; + /** + * Add object to queue with save operation. + * + * @function destroy + * @name Parse.EventuallyQueue.destroy + * @param {ParseObject} object Parse.Object to be destroyed eventually + * @param {object} [serverOptions] See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#destroy Parse.Object.destroy} options + * @returns {Promise} A promise that is fulfilled if object is added to queue. + * @static + * @see Parse.Object#destroyEventually + */ + destroy(object: ParseObject, serverOptions?: RequestOptions): Promise; + /** + * Generate unique identifier to avoid duplicates and maintain previous state. + * + * @param {string} action save / destroy + * @param {object} object Parse.Object to be queued + * @returns {string} + * @static + * @ignore + */ + generateQueueId(action: string, object: ParseObject): string; + /** + * Build queue object and add to queue. + * + * @param {string} action save / destroy + * @param {object} object Parse.Object to be queued + * @param {object} [serverOptions] + * @returns {Promise} A promise that is fulfilled if object is added to queue. + * @static + * @ignore + */ + enqueue(action: string, object: ParseObject, serverOptions?: SaveOptions | RequestOptions): Promise; + store(data: Queue): Promise; + load(): Promise; + /** + * Sets the in-memory queue from local storage and returns. + * + * @function getQueue + * @name Parse.EventuallyQueue.getQueue + * @returns {Promise} + * @static + */ + getQueue(): Promise; + /** + * Saves the queue to local storage + * + * @param {Queue} queue Queue containing Parse.Object data. + * @returns {Promise} A promise that is fulfilled when queue is stored. + * @static + * @ignore + */ + setQueue(queue: Queue): Promise; + /** + * Removes Parse.Object data from queue. + * + * @param {string} queueId Unique identifier for Parse.Object data. + * @returns {Promise} A promise that is fulfilled when queue is stored. + * @static + * @ignore + */ + remove(queueId: string): Promise; + /** + * Removes all objects from queue. + * + * @function clear + * @name Parse.EventuallyQueue.clear + * @returns {Promise} A promise that is fulfilled when queue is cleared. + * @static + */ + clear(): Promise; + /** + * Return the index of a queueId in the queue. Returns -1 if not found. + * + * @param {Queue} queue Queue containing Parse.Object data. + * @param {string} queueId Unique identifier for Parse.Object data. + * @returns {number} + * @static + * @ignore + */ + queueItemExists(queue: Queue, queueId: string): number; + /** + * Return the number of objects in the queue. + * + * @function length + * @name Parse.EventuallyQueue.length + * @returns {Promise} + * @static + */ + length(): Promise; + /** + * Sends the queue to the server. + * + * @function sendQueue + * @name Parse.EventuallyQueue.sendQueue + * @returns {Promise} Returns true if queue was sent successfully. + * @static + */ + sendQueue(): Promise; + /** + * Build queue object and add to queue. + * + * @param {ParseObject} object Parse.Object to be processed + * @param {QueueObject} queueObject Parse.Object data from the queue + * @returns {Promise} A promise that is fulfilled when operation is performed. + * @static + * @ignore + */ + sendQueueCallback(object: ParseObject, queueObject: QueueObject): Promise; + /** + * Start polling server for network connection. + * Will send queue if connection is established. + * + * @function poll + * @name Parse.EventuallyQueue.poll + * @param [ms] Milliseconds to ping the server. Default 2000ms + * @static + */ + poll(ms?: number): void; + /** + * Turns off polling. + * + * @function stopPoll + * @name Parse.EventuallyQueue.stopPoll + * @static + */ + stopPoll(): void; + /** + * Return true if pinging the server. + * + * @function isPolling + * @name Parse.EventuallyQueue.isPolling + * @returns {boolean} + * @static + */ + isPolling(): boolean; + _setPolling(flag: boolean): void; + process: { + create(ObjectType: any, queueObject: any): Promise; + byId(ObjectType: any, queueObject: any): Promise; + byHash(ObjectType: any, queueObject: any): Promise; + }; }; export default EventuallyQueue; diff --git a/types/FacebookUtils.d.ts b/types/FacebookUtils.d.ts index 3cfebcaff..02fbab208 100644 --- a/types/FacebookUtils.d.ts +++ b/types/FacebookUtils.d.ts @@ -1,5 +1,5 @@ import ParseUser from './ParseUser'; -import type { AuthProviderType } from './ParseUser'; +import type { AuthProvider } from './ParseUser'; /** * Provides a set of utilities for using Parse with Facebook. * @@ -8,100 +8,100 @@ import type { AuthProviderType } from './ParseUser'; * @hideconstructor */ declare const FacebookUtils: { - /** - * Initializes Parse Facebook integration. Call this function after you - * have loaded the Facebook Javascript SDK with the same parameters - * as you would pass to - * - * FB.init(). Parse.FacebookUtils will invoke FB.init() for you - * with these arguments. - * - * @function init - * @name Parse.FacebookUtils.init - * @param {object} options Facebook options argument as described here: - * - * FB.init(). The status flag will be coerced to 'false' because it - * interferes with Parse Facebook integration. Call FB.getLoginStatus() - * explicitly if this behavior is required by your application. - */ - init(options: any): void; - /** - * Gets whether the user has their account linked to Facebook. - * - * @function isLinked - * @name Parse.FacebookUtils.isLinked - * @param {Parse.User} user User to check for a facebook link. - * The user must be logged in on this device. - * @returns {boolean} true if the user has their account - * linked to Facebook. - */ - isLinked(user: any): any; - /** - * Logs in a user using Facebook. This method delegates to the Facebook - * SDK to authenticate the user, and then automatically logs in (or - * creates, in the case where it is a new user) a Parse.User. - * - * Standard API: - * - * logIn(permission: string, authData: Object); - * - * Advanced API: Used for handling your own oAuth tokens - * {@link https://docs.parseplatform.org/rest/guide/#linking-users} - * - * logIn(authData: Object, options?: Object); - * - * @function logIn - * @name Parse.FacebookUtils.logIn - * @param {(string | object)} permissions The permissions required for Facebook - * log in. This is a comma-separated string of permissions. - * Alternatively, supply a Facebook authData object as described in our - * REST API docs if you want to handle getting facebook auth tokens - * yourself. - * @param {object} options MasterKey / SessionToken. Alternatively can be used for authData if permissions is a string - * @returns {Promise} - */ - logIn(permissions: any, options: any): Promise; - /** - * Links Facebook to an existing PFUser. This method delegates to the - * Facebook SDK to authenticate the user, and then automatically links - * the account to the Parse.User. - * - * Standard API: - * - * link(user: Parse.User, permission: string, authData?: Object); - * - * Advanced API: Used for handling your own oAuth tokens - * {@link https://docs.parseplatform.org/rest/guide/#linking-users} - * - * link(user: Parse.User, authData: Object, options?: FullOptions); - * - * @function link - * @name Parse.FacebookUtils.link - * @param {Parse.User} user User to link to Facebook. This must be the - * current user. - * @param {(string | object)} permissions The permissions required for Facebook - * log in. This is a comma-separated string of permissions. - * Alternatively, supply a Facebook authData object as described in our - * REST API docs if you want to handle getting facebook auth tokens - * yourself. - * @param {object} options MasterKey / SessionToken. Alternatively can be used for authData if permissions is a string - * @returns {Promise} - */ - link(user: any, permissions: any, options: any): any; - /** - * Unlinks the Parse.User from a Facebook account. - * - * @function unlink - * @name Parse.FacebookUtils.unlink - * @param {Parse.User} user User to unlink from Facebook. This must be the - * current user. - * @param {object} options Standard options object with success and error - * callbacks. - * @returns {Promise} - */ - unlink: (user: any, options: any) => any; - _getAuthProvider(): AuthProviderType; + /** + * Initializes Parse Facebook integration. Call this function after you + * have loaded the Facebook Javascript SDK with the same parameters + * as you would pass to + * + * FB.init(). Parse.FacebookUtils will invoke FB.init() for you + * with these arguments. + * + * @function init + * @name Parse.FacebookUtils.init + * @param {object} options Facebook options argument as described here: + * + * FB.init(). The status flag will be coerced to 'false' because it + * interferes with Parse Facebook integration. Call FB.getLoginStatus() + * explicitly if this behavior is required by your application. + */ + init(options: any): void; + /** + * Gets whether the user has their account linked to Facebook. + * + * @function isLinked + * @name Parse.FacebookUtils.isLinked + * @param {Parse.User} user User to check for a facebook link. + * The user must be logged in on this device. + * @returns {boolean} true if the user has their account + * linked to Facebook. + */ + isLinked(user: any): any; + /** + * Logs in a user using Facebook. This method delegates to the Facebook + * SDK to authenticate the user, and then automatically logs in (or + * creates, in the case where it is a new user) a Parse.User. + * + * Standard API: + * + * logIn(permission: string, authData: Object); + * + * Advanced API: Used for handling your own oAuth tokens + * {@link https://docs.parseplatform.org/rest/guide/#linking-users} + * + * logIn(authData: Object, options?: Object); + * + * @function logIn + * @name Parse.FacebookUtils.logIn + * @param {(string | object)} permissions The permissions required for Facebook + * log in. This is a comma-separated string of permissions. + * Alternatively, supply a Facebook authData object as described in our + * REST API docs if you want to handle getting facebook auth tokens + * yourself. + * @param {object} options MasterKey / SessionToken. Alternatively can be used for authData if permissions is a string + * @returns {Promise} + */ + logIn(permissions: any, options: any): Promise>; + /** + * Links Facebook to an existing PFUser. This method delegates to the + * Facebook SDK to authenticate the user, and then automatically links + * the account to the Parse.User. + * + * Standard API: + * + * link(user: Parse.User, permission: string, authData?: Object); + * + * Advanced API: Used for handling your own oAuth tokens + * {@link https://docs.parseplatform.org/rest/guide/#linking-users} + * + * link(user: Parse.User, authData: Object, options?: FullOptions); + * + * @function link + * @name Parse.FacebookUtils.link + * @param {Parse.User} user User to link to Facebook. This must be the + * current user. + * @param {(string | object)} permissions The permissions required for Facebook + * log in. This is a comma-separated string of permissions. + * Alternatively, supply a Facebook authData object as described in our + * REST API docs if you want to handle getting facebook auth tokens + * yourself. + * @param {object} options MasterKey / SessionToken. Alternatively can be used for authData if permissions is a string + * @returns {Promise} + */ + link(user: any, permissions: any, options: any): any; + /** + * Unlinks the Parse.User from a Facebook account. + * + * @function unlink + * @name Parse.FacebookUtils.unlink + * @param {Parse.User} user User to unlink from Facebook. This must be the + * current user. + * @param {object} options Standard options object with success and error + * callbacks. + * @returns {Promise} + */ + unlink: (user: any, options: any) => any; + _getAuthProvider(): AuthProvider; }; export default FacebookUtils; diff --git a/types/InstallationController.d.ts b/types/InstallationController.d.ts index 9797e9d93..1409c39db 100644 --- a/types/InstallationController.d.ts +++ b/types/InstallationController.d.ts @@ -1,10 +1,10 @@ import ParseInstallation from './ParseInstallation'; declare const InstallationController: { - updateInstallationOnDisk(installation: ParseInstallation): Promise; - currentInstallationId(): Promise; - currentInstallation(): Promise; - _clearCache(): void; - _setInstallationIdCache(iid: string): void; - _setCurrentInstallationCache(installation: ParseInstallation, matchesDisk?: boolean): void; + updateInstallationOnDisk(installation: ParseInstallation): Promise; + currentInstallationId(): Promise; + currentInstallation(): Promise; + _clearCache(): void; + _setInstallationIdCache(iid: string): void; + _setCurrentInstallationCache(installation: ParseInstallation, matchesDisk?: boolean): void; }; export default InstallationController; diff --git a/types/LiveQueryClient.d.ts b/types/LiveQueryClient.d.ts index 49fbe38c5..4f41545dc 100644 --- a/types/LiveQueryClient.d.ts +++ b/types/LiveQueryClient.d.ts @@ -44,92 +44,85 @@ import type ParseQuery from './ParseQuery'; * @alias Parse.LiveQueryClient */ declare class LiveQueryClient { - attempts: number; - id: number; - requestId: number; - applicationId: string; - serverURL: string; - javascriptKey?: string; - masterKey?: string; - sessionToken?: string; - installationId?: string; - additionalProperties: boolean; - connectPromise: any; - subscriptions: Map; - socket: WebSocketController & { - closingPromise?: any; - }; - state: string; - reconnectHandle: any; - emitter: any; - on: any; - emit: any; - /** - * @param {object} options - * @param {string} options.applicationId - applicationId of your Parse app - * @param {string} options.serverURL - the URL of your LiveQuery server - * @param {string} options.javascriptKey (optional) - * @param {string} options.masterKey (optional) Your Parse Master Key. (Node.js only!) - * @param {string} options.sessionToken (optional) - * @param {string} options.installationId (optional) - */ - constructor({ - applicationId, - serverURL, - javascriptKey, - masterKey, - sessionToken, - installationId, - }: { - applicationId: any; - serverURL: any; - javascriptKey: any; - masterKey: any; - sessionToken: any; - installationId: any; - }); - shouldOpen(): any; - /** - * Subscribes to a ParseQuery - * - * If you provide the sessionToken, when the LiveQuery server gets ParseObject's - * updates from parse server, it'll try to check whether the sessionToken fulfills - * the ParseObject's ACL. The LiveQuery server will only send updates to clients whose - * sessionToken is fit for the ParseObject's ACL. You can check the LiveQuery protocol - * here for more details. The subscription you get is the same subscription you get - * from our Standard API. - * - * @param {ParseQuery} query - the ParseQuery you want to subscribe to - * @param {string} sessionToken (optional) - * @returns {LiveQuerySubscription | undefined} - */ - subscribe(query: ParseQuery, sessionToken?: string): LiveQuerySubscription | undefined; - /** - * After calling unsubscribe you'll stop receiving events from the subscription object. - * - * @param {object} subscription - subscription you would like to unsubscribe from. - * @returns {Promise | undefined} - */ - unsubscribe(subscription: LiveQuerySubscription): Promise; - /** - * After open is called, the LiveQueryClient will try to send a connect request - * to the LiveQuery server. - * - */ - open(): void; - resubscribe(): void; - /** - * This method will close the WebSocket connection to this LiveQueryClient, - * cancel the auto reconnect and unsubscribe all subscriptions based on it. - * - * @returns {Promise | undefined} CloseEvent {@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close_event} - */ - close(): Promise; - _handleReset(): void; - _handleWebSocketOpen(): void; - _handleWebSocketMessage(event: any): void; - _handleWebSocketClose(): void; - _handleWebSocketError(error: any): void; - _handleReconnect(): void; + attempts: number; + id: number; + requestId: number; + applicationId: string; + serverURL: string; + javascriptKey?: string; + masterKey?: string; + sessionToken?: string; + installationId?: string; + additionalProperties: boolean; + connectPromise: any; + subscriptions: Map; + socket: WebSocketController & { + closingPromise?: any; + }; + state: string; + reconnectHandle: any; + emitter: any; + on: any; + emit: any; + /** + * @param {object} options + * @param {string} options.applicationId - applicationId of your Parse app + * @param {string} options.serverURL - the URL of your LiveQuery server + * @param {string} options.javascriptKey (optional) + * @param {string} options.masterKey (optional) Your Parse Master Key. (Node.js only!) + * @param {string} options.sessionToken (optional) + * @param {string} options.installationId (optional) + */ + constructor({ applicationId, serverURL, javascriptKey, masterKey, sessionToken, installationId, }: { + applicationId: any; + serverURL: any; + javascriptKey: any; + masterKey: any; + sessionToken: any; + installationId: any; + }); + shouldOpen(): any; + /** + * Subscribes to a ParseQuery + * + * If you provide the sessionToken, when the LiveQuery server gets ParseObject's + * updates from parse server, it'll try to check whether the sessionToken fulfills + * the ParseObject's ACL. The LiveQuery server will only send updates to clients whose + * sessionToken is fit for the ParseObject's ACL. You can check the LiveQuery protocol + * here for more details. The subscription you get is the same subscription you get + * from our Standard API. + * + * @param {ParseQuery} query - the ParseQuery you want to subscribe to + * @param {string} sessionToken (optional) + * @returns {LiveQuerySubscription | undefined} + */ + subscribe(query: ParseQuery, sessionToken?: string): LiveQuerySubscription | undefined; + /** + * After calling unsubscribe you'll stop receiving events from the subscription object. + * + * @param {object} subscription - subscription you would like to unsubscribe from. + * @returns {Promise | undefined} + */ + unsubscribe(subscription: LiveQuerySubscription): Promise; + /** + * After open is called, the LiveQueryClient will try to send a connect request + * to the LiveQuery server. + * + */ + open(): void; + resubscribe(): void; + /** + * This method will close the WebSocket connection to this LiveQueryClient, + * cancel the auto reconnect and unsubscribe all subscriptions based on it. + * + * @returns {Promise | undefined} CloseEvent {@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close_event} + */ + close(): Promise; + _handleReset(): void; + _handleWebSocketOpen(): void; + _handleWebSocketMessage(event: any): void; + _handleWebSocketClose(): void; + _handleWebSocketError(error: any): void; + _handleReconnect(): void; } export default LiveQueryClient; diff --git a/types/LiveQuerySubscription.d.ts b/types/LiveQuerySubscription.d.ts index e312d2a86..7bc4df0e7 100644 --- a/types/LiveQuerySubscription.d.ts +++ b/types/LiveQuerySubscription.d.ts @@ -1,4 +1,5 @@ import type ParseQuery from './ParseQuery'; +import type { EventEmitter } from 'events'; /** * Creates a new LiveQuery Subscription. * cloud functions. @@ -81,22 +82,22 @@ import type ParseQuery from './ParseQuery'; * * });

*/ -declare class Subscription { - id: string | number; - query: ParseQuery; - sessionToken?: string; - subscribePromise: any; - unsubscribePromise: any; - subscribed: boolean; - emitter: any; - on: any; - emit: any; - constructor(id: string | number, query: ParseQuery, sessionToken?: string); - /** - * Close the subscription - * - * @returns {Promise} - */ - unsubscribe(): Promise; +declare class LiveQuerySubscription { + id: string | number; + query: ParseQuery; + sessionToken?: string; + subscribePromise: any; + unsubscribePromise: any; + subscribed: boolean; + emitter: EventEmitter; + on: EventEmitter['on']; + emit: EventEmitter['emit']; + constructor(id: string | number, query: ParseQuery, sessionToken?: string); + /** + * Close the subscription + * + * @returns {Promise} + */ + unsubscribe(): Promise; } -export default Subscription; +export default LiveQuerySubscription; diff --git a/types/LocalDatastore.d.ts b/types/LocalDatastore.d.ts index 4559910a9..d6f795de0 100644 --- a/types/LocalDatastore.d.ts +++ b/types/LocalDatastore.d.ts @@ -20,37 +20,37 @@ import type ParseObject from './ParseObject'; * @static */ declare const LocalDatastore: { - isEnabled: boolean; - isSyncing: boolean; - fromPinWithName(name: string): Promise>; - pinWithName(name: string, value: any): Promise; - unPinWithName(name: string): Promise; - _getAllContents(): Promise; - _getRawStorage(): Promise; - _clear(): Promise; - _handlePinAllWithName(name: string, objects: Array): Promise; - _handleUnPinAllWithName(name: string, objects: Array): Promise; - _getChildren(object: ParseObject): any; - _traverse(object: any, encountered: any): void; - _serializeObjectsFromPinName(name: string): Promise; - _serializeObject(objectKey: string, localDatastore: any): Promise; - _updateObjectIfPinned(object: ParseObject): Promise; - _destroyObjectIfPinned(object: ParseObject): Promise; - _updateLocalIdForObject(localId: string, object: ParseObject): Promise; - /** - * Updates Local Datastore from Server - * - *
-   * await Parse.LocalDatastore.updateFromServer();
-   * 
- * - * @function updateFromServer - * @name Parse.LocalDatastore.updateFromServer - * @static - */ - updateFromServer(): Promise; - getKeyForObject(object: any): string; - getPinName(pinName?: string): string; - checkIfEnabled(): any; + isEnabled: boolean; + isSyncing: boolean; + fromPinWithName(name: string): Promise>; + pinWithName(name: string, value: any): Promise; + unPinWithName(name: string): Promise; + _getAllContents(): Promise; + _getRawStorage(): Promise; + _clear(): Promise; + _handlePinAllWithName(name: string, objects: Array): Promise; + _handleUnPinAllWithName(name: string, objects: Array): Promise; + _getChildren(object: ParseObject): any; + _traverse(object: any, encountered: any): void; + _serializeObjectsFromPinName(name: string): Promise; + _serializeObject(objectKey: string, localDatastore: any): Promise; + _updateObjectIfPinned(object: ParseObject): Promise; + _destroyObjectIfPinned(object: ParseObject): Promise; + _updateLocalIdForObject(localId: string, object: ParseObject): Promise; + /** + * Updates Local Datastore from Server + * + *
+     * await Parse.LocalDatastore.updateFromServer();
+     * 
+ * + * @function updateFromServer + * @name Parse.LocalDatastore.updateFromServer + * @static + */ + updateFromServer(): Promise; + getKeyForObject(object: any): string; + getPinName(pinName?: string): string; + checkIfEnabled(): any; }; export default LocalDatastore; diff --git a/types/LocalDatastoreController.default.d.ts b/types/LocalDatastoreController.default.d.ts index 3737f59a7..14416a1b7 100644 --- a/types/LocalDatastoreController.default.d.ts +++ b/types/LocalDatastoreController.default.d.ts @@ -1,9 +1,9 @@ declare const LocalDatastoreController: { - fromPinWithName(name: string): Promise>; - pinWithName(name: string, value: any): Promise; - unPinWithName(name: string): Promise; - getAllContents(): Promise; - getRawStorage(): Promise; - clear(): Promise; + fromPinWithName(name: string): Promise>; + pinWithName(name: string, value: any): Promise; + unPinWithName(name: string): Promise; + getAllContents(): Promise; + getRawStorage(): Promise; + clear(): Promise; }; export default LocalDatastoreController; diff --git a/types/LocalDatastoreController.react-native.d.ts b/types/LocalDatastoreController.react-native.d.ts index 96b58dfd5..2db09d794 100644 --- a/types/LocalDatastoreController.react-native.d.ts +++ b/types/LocalDatastoreController.react-native.d.ts @@ -1,9 +1,9 @@ declare const LocalDatastoreController: { - fromPinWithName(name: string): Promise>; - pinWithName(name: string, value: any): Promise; - unPinWithName(name: string): Promise; - getAllContents(): Promise; - getRawStorage(): Promise; - clear(): Promise; + fromPinWithName(name: string): Promise>; + pinWithName(name: string, value: any): Promise; + unPinWithName(name: string): Promise; + getAllContents(): Promise; + getRawStorage(): Promise; + clear(): Promise; }; export default LocalDatastoreController; diff --git a/types/LocalDatastoreUtils.d.ts b/types/LocalDatastoreUtils.d.ts index db607c44e..7472e6570 100644 --- a/types/LocalDatastoreUtils.d.ts +++ b/types/LocalDatastoreUtils.d.ts @@ -1,5 +1,5 @@ -declare const DEFAULT_PIN = '_default'; -declare const PIN_PREFIX = 'parsePin_'; -declare const OBJECT_PREFIX = 'Parse_LDS_'; +declare const DEFAULT_PIN = "_default"; +declare const PIN_PREFIX = "parsePin_"; +declare const OBJECT_PREFIX = "Parse_LDS_"; declare function isLocalDatastoreKey(key: string): boolean; export { DEFAULT_PIN, PIN_PREFIX, OBJECT_PREFIX, isLocalDatastoreKey }; diff --git a/types/ObjectStateMutations.d.ts b/types/ObjectStateMutations.d.ts index 75d1793eb..7a2086d80 100644 --- a/types/ObjectStateMutations.d.ts +++ b/types/ObjectStateMutations.d.ts @@ -2,20 +2,20 @@ import TaskQueue from './TaskQueue'; import type { Op } from './ParseOp'; import type ParseObject from './ParseObject'; export type AttributeMap = { - [attr: string]: any; + [attr: string]: any; }; export type OpsMap = { - [attr: string]: Op; + [attr: string]: Op; }; export type ObjectCache = { - [attr: string]: string; + [attr: string]: string; }; export type State = { - serverData: AttributeMap; - pendingOps: Array; - objectCache: ObjectCache; - tasks: TaskQueue; - existed: boolean; + serverData: AttributeMap; + pendingOps: Array; + objectCache: ObjectCache; + tasks: TaskQueue; + existed: boolean; }; export declare function defaultState(): State; export declare function setServerData(serverData: AttributeMap, attributes: AttributeMap): void; @@ -23,19 +23,6 @@ export declare function setPendingOp(pendingOps: Array, attr: string, op export declare function pushPendingState(pendingOps: Array): void; export declare function popPendingState(pendingOps: Array): OpsMap; export declare function mergeFirstPendingState(pendingOps: Array): void; -export declare function estimateAttribute( - serverData: AttributeMap, - pendingOps: Array, - object: ParseObject, - attr: string -): any; -export declare function estimateAttributes( - serverData: AttributeMap, - pendingOps: Array, - object: ParseObject -): AttributeMap; -export declare function commitServerChanges( - serverData: AttributeMap, - objectCache: ObjectCache, - changes: AttributeMap -): void; +export declare function estimateAttribute(serverData: AttributeMap, pendingOps: Array, object: ParseObject, attr: string): any; +export declare function estimateAttributes(serverData: AttributeMap, pendingOps: Array, object: ParseObject): AttributeMap; +export declare function commitServerChanges(serverData: AttributeMap, objectCache: ObjectCache, changes: AttributeMap): void; diff --git a/types/OfflineQuery.d.ts b/types/OfflineQuery.d.ts index 1361e7efc..9cca71c1b 100644 --- a/types/OfflineQuery.d.ts +++ b/types/OfflineQuery.d.ts @@ -14,7 +14,7 @@ declare function matchesQuery(className: any, object: any, objects: any, query: any): boolean; declare function validateQuery(query: any): void; declare const OfflineQuery: { - matchesQuery: typeof matchesQuery; - validateQuery: typeof validateQuery; + matchesQuery: typeof matchesQuery; + validateQuery: typeof validateQuery; }; export default OfflineQuery; diff --git a/types/Parse.d.ts b/types/Parse.d.ts index 4500ea0ab..cefbc562f 100644 --- a/types/Parse.d.ts +++ b/types/Parse.d.ts @@ -1,4 +1,3 @@ -import EventuallyQueue from './EventuallyQueue'; import * as ParseOp from './ParseOp'; import ACL from './ParseACL'; import * as Analytics from './Analytics'; @@ -21,435 +20,234 @@ import Session from './ParseSession'; import User from './ParseUser'; import ParseLiveQuery from './ParseLiveQuery'; import LiveQueryClient from './LiveQueryClient'; +import type { EventuallyQueue } from './CoreManager'; declare const Parse: { - ACL: typeof ACL; - Analytics: typeof Analytics; - AnonymousUtils: { - isLinked(user: User): boolean; - logIn(options?: import('./RESTController').RequestOptions): Promise; - link(user: User, options?: import('./RESTController').RequestOptions): Promise; - isRegistered(): boolean; - _getAuthProvider(): { - restoreAuthentication(): boolean; - getAuthType(): string; - getAuthData(): { - authData: { - id: string; + ACL: typeof ACL; + Analytics: typeof Analytics; + AnonymousUtils: { + isLinked(user: User): boolean; + logIn(options?: import("./RESTController").RequestOptions): Promise; + link(user: User, options?: import("./RESTController").RequestOptions): Promise; + isRegistered(): boolean; + _getAuthProvider(): { + restoreAuthentication(): boolean; + getAuthType(): string; + getAuthData(): { + authData: { + id: string; + }; + }; }; - }; }; - }; - Cloud: typeof Cloud; - CLP: typeof CLP; - CoreManager: { - get: (key: string) => any; - set: (key: string, value: any) => void; - setIfNeeded: (key: string, value: any) => any; - setAnalyticsController(controller: { - track: ( - name: string, - dimensions: { - [key: string]: string; - } - ) => Promise; - }): void; - getAnalyticsController(): { - track: ( - name: string, - dimensions: { - [key: string]: string; - } - ) => Promise; - }; - setCloudController(controller: { - run: ( - name: string, - data: any, - options: import('./RESTController').RequestOptions - ) => Promise; - getJobsData: (options: import('./RESTController').RequestOptions) => Promise; - startJob: ( - name: string, - data: any, - options: import('./RESTController').RequestOptions - ) => Promise; - }): void; - getCloudController(): { - run: ( - name: string, - data: any, - options: import('./RESTController').RequestOptions - ) => Promise; - getJobsData: (options: import('./RESTController').RequestOptions) => Promise; - startJob: ( - name: string, - data: any, - options: import('./RESTController').RequestOptions - ) => Promise; - }; - setConfigController(controller: { - current: () => Promise | Config; - get: (opts?: import('./RESTController').RequestOptions) => Promise; - save: ( - attrs: { - [key: string]: any; - }, - masterKeyOnlyFlags?: { - [key: string]: any; - } - ) => Promise; - }): void; - getConfigController(): { - current: () => Promise | Config; - get: (opts?: import('./RESTController').RequestOptions) => Promise; - save: ( - attrs: { - [key: string]: any; - }, - masterKeyOnlyFlags?: { - [key: string]: any; - } - ) => Promise; - }; - setCryptoController(controller: { - encrypt: (obj: any, secretKey: string) => string; - decrypt: (encryptedText: string, secretKey: any) => string; - }): void; - getCryptoController(): { - encrypt: (obj: any, secretKey: string) => string; - decrypt: (encryptedText: string, secretKey: any) => string; - }; - setEventEmitter(eventEmitter: any): void; - getEventEmitter(): any; - setFileController(controller: { - saveFile: ( - name: string, - source: import('./ParseFile').FileSource, - options?: import('./RESTController').FullOptions - ) => Promise; - saveBase64: ( - name: string, - source: import('./ParseFile').FileSource, - options?: import('./ParseFile').FileSaveOptions - ) => Promise<{ - name: string; - url: string; - }>; - download: ( - uri: string, - options?: any - ) => Promise<{ - base64?: string; - contentType?: string; - }>; - deleteFile: ( - name: string, - options?: { - useMasterKey?: boolean; - } - ) => Promise; - }): void; - setEventuallyQueue(controller: { - save: ( - object: ParseObject, - serverOptions: import('./ParseObject').SaveOptions - ) => Promise; - destroy: ( - object: ParseObject, - serverOptions: import('./RESTController').RequestOptions - ) => Promise; - poll: (ms?: number) => void; - }): void; - getEventuallyQueue(): { - save: ( - object: ParseObject, - serverOptions: import('./ParseObject').SaveOptions - ) => Promise; - destroy: ( - object: ParseObject, - serverOptions: import('./RESTController').RequestOptions - ) => Promise; - poll: (ms?: number) => void; - }; - getFileController(): { - saveFile: ( - name: string, - source: import('./ParseFile').FileSource, - options?: import('./RESTController').FullOptions - ) => Promise; - saveBase64: ( - name: string, - source: import('./ParseFile').FileSource, - options?: import('./ParseFile').FileSaveOptions - ) => Promise<{ - name: string; - url: string; - }>; - download: ( - uri: string, - options?: any - ) => Promise<{ - base64?: string; - contentType?: string; - }>; - deleteFile: ( - name: string, - options?: { - useMasterKey?: boolean; - } - ) => Promise; - }; - setInstallationController(controller: { - currentInstallationId: () => Promise; - currentInstallation: () => Promise; - updateInstallationOnDisk: (installation: Installation) => Promise; - }): void; - getInstallationController(): { - currentInstallationId: () => Promise; - currentInstallation: () => Promise; - updateInstallationOnDisk: (installation: Installation) => Promise; - }; - setLiveQuery(liveQuery: any): void; - getLiveQuery(): any; - setObjectController(controller: { - fetch: ( - object: ParseObject | Array, - forceFetch: boolean, - options: import('./RESTController').RequestOptions - ) => Promise | ParseObject | undefined>; - save: ( - object: ParseObject | Array | null, - options: import('./RESTController').RequestOptions - ) => Promise | File | undefined>; - destroy: ( - object: ParseObject | Array, - options: import('./RESTController').RequestOptions - ) => Promise>; - }): void; - getObjectController(): { - fetch: ( - object: ParseObject | Array, - forceFetch: boolean, - options: import('./RESTController').RequestOptions - ) => Promise | ParseObject | undefined>; - save: ( - object: ParseObject | Array | null, - options: import('./RESTController').RequestOptions - ) => Promise | File | undefined>; - destroy: ( - object: ParseObject | Array, - options: import('./RESTController').RequestOptions - ) => Promise>; - }; - setObjectStateController(controller: { - getState: (obj: any) => import('./ObjectStateMutations').State | null; - initializeState: ( - obj: any, - initial?: import('./ObjectStateMutations').State - ) => import('./ObjectStateMutations').State; - removeState: (obj: any) => import('./ObjectStateMutations').State | null; - getServerData: (obj: any) => import('./ObjectStateMutations').AttributeMap; - setServerData: (obj: any, attributes: import('./ObjectStateMutations').AttributeMap) => void; - getPendingOps: (obj: any) => Array; - setPendingOp: (obj: any, attr: string, op?: ParseOp.Op) => void; - pushPendingState: (obj: any) => void; - popPendingState: (obj: any) => import('./ObjectStateMutations').OpsMap | undefined; - mergeFirstPendingState: (obj: any) => void; - getObjectCache: (obj: any) => import('./ObjectStateMutations').ObjectCache; - estimateAttribute: (obj: any, attr: string) => any; - estimateAttributes: (obj: any) => import('./ObjectStateMutations').AttributeMap; - commitServerChanges: ( - obj: any, - changes: import('./ObjectStateMutations').AttributeMap - ) => void; - enqueueTask: (obj: any, task: () => Promise) => Promise; - clearAllState: () => void; - duplicateState: (source: any, dest: any) => void; - }): void; - getObjectStateController(): { - getState: (obj: any) => import('./ObjectStateMutations').State | null; - initializeState: ( - obj: any, - initial?: import('./ObjectStateMutations').State - ) => import('./ObjectStateMutations').State; - removeState: (obj: any) => import('./ObjectStateMutations').State | null; - getServerData: (obj: any) => import('./ObjectStateMutations').AttributeMap; - setServerData: (obj: any, attributes: import('./ObjectStateMutations').AttributeMap) => void; - getPendingOps: (obj: any) => Array; - setPendingOp: (obj: any, attr: string, op?: ParseOp.Op) => void; - pushPendingState: (obj: any) => void; - popPendingState: (obj: any) => import('./ObjectStateMutations').OpsMap | undefined; - mergeFirstPendingState: (obj: any) => void; - getObjectCache: (obj: any) => import('./ObjectStateMutations').ObjectCache; - estimateAttribute: (obj: any, attr: string) => any; - estimateAttributes: (obj: any) => import('./ObjectStateMutations').AttributeMap; - commitServerChanges: ( - obj: any, - changes: import('./ObjectStateMutations').AttributeMap - ) => void; - enqueueTask: (obj: any, task: () => Promise) => Promise; - clearAllState: () => void; - duplicateState: (source: any, dest: any) => void; - }; - setPushController(controller: { - send: (data: Push.PushData, options?: import('./RESTController').FullOptions) => Promise; - }): void; - getPushController(): { - send: (data: Push.PushData, options?: import('./RESTController').FullOptions) => Promise; - }; - setQueryController(controller: { - find( - className: string, - params: import('./ParseQuery').QueryJSON, - options: import('./RESTController').RequestOptions - ): Promise<{ - results?: Array; - className?: string; - count?: number; - }>; - aggregate( - className: string, - params: any, - options: import('./RESTController').RequestOptions - ): Promise<{ - results?: Array; - }>; - }): void; - getQueryController(): { - find( - className: string, - params: import('./ParseQuery').QueryJSON, - options: import('./RESTController').RequestOptions - ): Promise<{ - results?: Array; - className?: string; - count?: number; - }>; - aggregate( - className: string, - params: any, - options: import('./RESTController').RequestOptions - ): Promise<{ - results?: Array; - }>; - }; - setRESTController(controller: { - request: ( - method: string, - path: string, - data?: any, - options?: import('./RESTController').RequestOptions - ) => Promise; - ajax: ( - method: string, - url: string, - data: any, - headers?: any, - options?: import('./RESTController').FullOptions - ) => Promise; - handleError: ( - err? /** - * Call this method to set your LocalDatastoreStorage engine - * If using React-Native use {@link Parse.setAsyncStorage Parse.setAsyncStorage()} - * - * @param {LocalDatastoreController} controller a data storage. - * @static - */ - : any - ) => void; - }): void; - getRESTController(): { - request: ( - method: string, - path: string, - data?: any, - options?: import('./RESTController').RequestOptions - ) => Promise; - ajax: ( - method: string, - url: string, - data: any, - headers?: any, - options?: import('./RESTController').FullOptions - ) => Promise; - handleError: ( - err? /** - * Call this method to set your LocalDatastoreStorage engine - * If using React-Native use {@link Parse.setAsyncStorage Parse.setAsyncStorage()} - * - * @param {LocalDatastoreController} controller a data storage. - * @static - */ - : any - ) => void; - }; - setSchemaController(controller: { - purge: (className: string) => Promise; - get: ( - className: string, - options?: import('./RESTController').RequestOptions - ) => Promise<{ - results: Schema[]; - }>; - delete: ( - className: string, - options?: import('./RESTController').RequestOptions - ) => Promise; - create: ( - className: string, - params: any, - options?: import('./RESTController').RequestOptions - ) => Promise; - update: ( - className: string, - params: any, - options?: import('./RESTController').RequestOptions - ) => Promise; - send( - className: string, - method: string, - params: any, - options: import('./RESTController').RequestOptions - ): Promise; - }): void; - getSchemaController(): { - purge: (className: string) => Promise; - get: ( - className: string, - options?: import('./RESTController').RequestOptions - ) => Promise<{ - results: Schema[]; - }>; - delete: ( - className: string, - options?: import('./RESTController').RequestOptions - ) => Promise; - create: ( - className: string, - params: any, - options?: import('./RESTController').RequestOptions - ) => Promise; - update: ( - className: string, - params: any, - options?: import('./RESTController').RequestOptions - ) => Promise; - send( - className: string, - method: string, - params: any, - options: import('./RESTController').RequestOptions - ): Promise; - }; - setSessionController(controller: { - getSession: (token: import('./RESTController').RequestOptions) => Promise; - }): void; - getSessionController(): { - getSession: (token: import('./RESTController').RequestOptions) => Promise; - }; - setStorageController( - controller: - | { + Cloud: typeof Cloud; + CLP: typeof CLP; + CoreManager: { + get: (key: string) => any; + set: (key: string, value: any) => void; + setIfNeeded: (key: string, value: any) => any; + setAnalyticsController(controller: { + track: (name: string, dimensions: { + [key: string]: string; + }) => Promise; + }): void; + getAnalyticsController(): { + track: (name: string, dimensions: { + [key: string]: string; + }) => Promise; + }; + setCloudController(controller: { + run: (name: string, data: any, options?: import("./RESTController").RequestOptions) => Promise; + getJobsData: (options?: import("./RESTController").RequestOptions) => Promise; + startJob: (name: string, data: any, options?: import("./RESTController").RequestOptions) => Promise; + }): void; + getCloudController(): { + run: (name: string, data: any, options?: import("./RESTController").RequestOptions) => Promise; + getJobsData: (options?: import("./RESTController").RequestOptions) => Promise; + startJob: (name: string, data: any, options?: import("./RESTController").RequestOptions) => Promise; + }; + setConfigController(controller: { + current: () => Promise | Config; + get: (opts?: import("./RESTController").RequestOptions) => Promise; + save: (attrs: { + [key: string]: any; + }, masterKeyOnlyFlags?: { + [key: string]: any; + }) => Promise; + }): void; + getConfigController(): { + current: () => Promise | Config; + get: (opts?: import("./RESTController").RequestOptions) => Promise; + save: (attrs: { + [key: string]: any; + }, masterKeyOnlyFlags?: { + [key: string]: any; + }) => Promise; + }; + setCryptoController(controller: { + encrypt: (obj: any, secretKey: string) => string; + decrypt: (encryptedText: string, secretKey: any) => string; + }): void; + getCryptoController(): { + encrypt: (obj: any, secretKey: string) => string; + decrypt: (encryptedText: string, secretKey: any) => string; + }; + setEventEmitter(eventEmitter: any): void; + getEventEmitter(): any; + setFileController(controller: { + saveFile: (name: string, source: import("./ParseFile").FileSource, options?: import("./RESTController").FullOptions) => Promise; + saveBase64: (name: string, source: import("./ParseFile").FileSource, options?: import("./ParseFile").FileSaveOptions) => Promise<{ + name: string; + url: string; + }>; + download: (uri: string, options?: any) => Promise<{ + base64?: string; + contentType?: string; + }>; + deleteFile: (name: string, options?: { + useMasterKey?: boolean; + }) => Promise; + }): void; + setEventuallyQueue(controller: EventuallyQueue): void; + getEventuallyQueue(): EventuallyQueue; + getFileController(): { + saveFile: (name: string, source: import("./ParseFile").FileSource, options?: import("./RESTController").FullOptions) => Promise; + saveBase64: (name: string, source: import("./ParseFile").FileSource, options?: import("./ParseFile").FileSaveOptions) => Promise<{ + name: string; + url: string; + }>; + download: (uri: string, options?: any) => Promise<{ + base64?: string; + contentType?: string; + }>; + deleteFile: (name: string, options?: { + useMasterKey?: boolean; + }) => Promise; + }; + setInstallationController(controller: { + currentInstallationId: () => Promise; + currentInstallation: () => Promise; + updateInstallationOnDisk: (installation: Installation) => Promise; + }): void; + getInstallationController(): { + currentInstallationId: () => Promise; + currentInstallation: () => Promise; + updateInstallationOnDisk: (installation: Installation) => Promise; + }; + setLiveQuery(liveQuery: any): void; + getLiveQuery(): any; + setObjectController(controller: { + fetch: (object: ParseObject | Array, forceFetch: boolean, options?: import("./RESTController").RequestOptions) => Promise | ParseObject | undefined>; + save: (object: ParseObject | Array | null, options?: import("./RESTController").RequestOptions) => Promise | File | undefined>; + destroy: (object: ParseObject | Array, options?: import("./RESTController").RequestOptions) => Promise>; + }): void; + getObjectController(): { + fetch: (object: ParseObject | Array, forceFetch: boolean, options?: import("./RESTController").RequestOptions) => Promise | ParseObject | undefined>; + save: (object: ParseObject | Array | null, options?: import("./RESTController").RequestOptions) => Promise | File | undefined>; + destroy: (object: ParseObject | Array, options?: import("./RESTController").RequestOptions) => Promise>; + }; + setObjectStateController(controller: { + getState: (obj: any) => import("./ObjectStateMutations").State | null; + initializeState: (obj: any, initial?: import("./ObjectStateMutations").State) => import("./ObjectStateMutations").State; + removeState: (obj: any) => import("./ObjectStateMutations").State | null; + getServerData: (obj: any) => import("./ObjectStateMutations").AttributeMap; + setServerData: (obj: any, attributes: import("./ObjectStateMutations").AttributeMap) => void; + getPendingOps: (obj: any) => Array; + setPendingOp: (obj: any, attr: string, op?: ParseOp.Op) => void; + pushPendingState: (obj: any) => void; + popPendingState: (obj: any) => import("./ObjectStateMutations").OpsMap | undefined; + mergeFirstPendingState: (obj: any) => void; + getObjectCache: (obj: any) => import("./ObjectStateMutations").ObjectCache; + estimateAttribute: (obj: any, attr: string) => any; + estimateAttributes: (obj: any) => import("./ObjectStateMutations").AttributeMap; + commitServerChanges: (obj: any, changes: import("./ObjectStateMutations").AttributeMap) => void; + enqueueTask: (obj: any, task: () => Promise) => Promise; + clearAllState: () => void; + duplicateState: (source: any, dest: any) => void; + }): void; + getObjectStateController(): { + getState: (obj: any) => import("./ObjectStateMutations").State | null; + initializeState: (obj: any, initial?: import("./ObjectStateMutations").State) => import("./ObjectStateMutations").State; + removeState: (obj: any) => import("./ObjectStateMutations").State | null; + getServerData: (obj: any) => import("./ObjectStateMutations").AttributeMap; + setServerData: (obj: any, attributes: import("./ObjectStateMutations").AttributeMap) => void; + getPendingOps: (obj: any) => Array; + setPendingOp: (obj: any, attr: string, op?: ParseOp.Op) => void; + pushPendingState: (obj: any) => void; + popPendingState: (obj: any) => import("./ObjectStateMutations").OpsMap | undefined; + mergeFirstPendingState: (obj: any) => void; + getObjectCache: (obj: any) => import("./ObjectStateMutations").ObjectCache; + estimateAttribute: (obj: any, attr: string) => any; + estimateAttributes: (obj: any) => import("./ObjectStateMutations").AttributeMap; + commitServerChanges: (obj: any, changes: import("./ObjectStateMutations").AttributeMap) => void; + enqueueTask: (obj: any, task: () => Promise) => Promise; + clearAllState: () => void; + duplicateState: (source: any, dest: any) => void; + }; + setPushController(controller: { + send: (data: Push.PushData, options?: import("./RESTController").FullOptions) => Promise; + }): void; + getPushController(): { + send: (data: Push.PushData, options?: import("./RESTController").FullOptions) => Promise; + }; + setQueryController(controller: { + find(className: string, params: import("./ParseQuery").QueryJSON, options?: import("./RESTController").RequestOptions): Promise<{ + results?: Array; + className?: string; + count?: number; + }>; + aggregate(className: string, params: any, options?: import("./RESTController").RequestOptions): Promise<{ + results?: Array; + }>; + }): void; + getQueryController(): { + find(className: string, params: import("./ParseQuery").QueryJSON, options?: import("./RESTController").RequestOptions): Promise<{ + results?: Array; + className?: string; + count?: number; + }>; + aggregate(className: string, params: any, options?: import("./RESTController").RequestOptions): Promise<{ + results?: Array; + }>; + }; + setRESTController(controller: { + request: (method: string, path: string, data?: any, options?: import("./RESTController").RequestOptions) => Promise; + ajax: (method: string, url: string, data: any, headers?: any, options?: import("./RESTController").FullOptions) => Promise; + handleError: (err?: any) => void; + }): void; + getRESTController(): { + request: (method: string, path: string, data?: any, options?: import("./RESTController").RequestOptions) => Promise; + ajax: (method: string, url: string, data: any, headers?: any, options?: import("./RESTController").FullOptions) => Promise; + handleError: (err?: any) => void; + }; + setSchemaController(controller: { + purge: (className: string) => Promise; + get: (className: string, options?: import("./RESTController").RequestOptions) => Promise; + delete: (className: string, options?: import("./RESTController").RequestOptions) => Promise; + create: (className: string, params: any, options? /** + * @member {string} Parse.maintenanceKey + * @static + */: import("./RESTController").RequestOptions) => Promise; + update: (className: string, params: any, options?: import("./RESTController").RequestOptions) => Promise; + send(className: string, method: string, params: any, options?: import("./RESTController").RequestOptions): Promise; + }): void; + getSchemaController(): { + purge: (className: string) => Promise; + get: (className: string, options?: import("./RESTController").RequestOptions) => Promise; + delete: (className: string, options?: import("./RESTController").RequestOptions) => Promise; + create: (className: string, params: any, options? /** + * @member {string} Parse.maintenanceKey + * @static + */: import("./RESTController").RequestOptions) => Promise; + update: (className: string, params: any, options?: import("./RESTController").RequestOptions) => Promise; + send(className: string, method: string, params: any, options?: import("./RESTController").RequestOptions): Promise; + }; + setSessionController(controller: { + getSession: (options?: import("./RESTController").RequestOptions) => Promise; + }): void; + getSessionController(): { + getSession: (options?: import("./RESTController").RequestOptions) => Promise; + }; + setStorageController(controller: { async: 0; getItem: (path: string) => string | null; setItem: (path: string, value: string) => void; @@ -460,8 +258,7 @@ declare const Parse: { clear: () => void; getAllKeys?: () => Array; getAllKeysAsync?: () => Promise>; - } - | { + } | { async: 1; getItem?: (path: string) => string | null; setItem?: (path: string, value: string) => void; @@ -472,476 +269,365 @@ declare const Parse: { clear: () => void; getAllKeys?: () => Array; getAllKeysAsync?: () => Promise>; - } - ): void; - setLocalDatastoreController(controller: { - fromPinWithName: (name: string) => any | undefined; - pinWithName: (name: string, objects: any) => void; - unPinWithName: (name: string) => void; - getAllContents: () => any | undefined; - clear: () => void; - }): void; - getLocalDatastoreController(): { - fromPinWithName: (name: string) => any | undefined; - pinWithName: (name: string, objects: any) => void; - unPinWithName: (name: string) => void; - getAllContents: () => any | undefined; - clear: () => void; - }; - setLocalDatastore(store: any): void; - getLocalDatastore(): any; - getStorageController(): - | { - async: 0; - getItem: (path: string) => string | null; - setItem: (path: string, value: string) => void; - removeItem: (path: string) => void; - getItemAsync?: (path: string) => Promise; - setItemAsync?: (path: string, value: string) => Promise; - removeItemAsync?: (path: string) => Promise; - clear: () => void; - getAllKeys?: () => Array; - getAllKeysAsync?: () => Promise>; - } - | { - async: 1; - getItem?: (path: string) => string | null; - setItem?: (path: string, value: string) => void; - removeItem?: (path: string) => void; - getItemAsync: (path: string) => Promise; - setItemAsync: (path: string, value: string) => Promise; - removeItemAsync: (path: string) => Promise; - clear: () => void; - getAllKeys?: () => Array; - getAllKeysAsync?: () => Promise>; + }): void; + setLocalDatastoreController(controller: { + fromPinWithName: (name: string) => any | undefined; + pinWithName: (name: string, objects: any) => void; + unPinWithName: (name: string) => void; + getAllContents: () => any | undefined; + clear: () => void; + }): void; + getLocalDatastoreController(): { + fromPinWithName: (name: string) => any | undefined; + pinWithName: (name: string, objects: any) => void; + unPinWithName: (name: string) => void; + getAllContents: () => any | undefined; + clear: () => void; + }; + setLocalDatastore(store: any): void; + getLocalDatastore(): any; + getStorageController(): { + async: 0; + getItem: (path: string) => string | null; + setItem: (path: string, value: string) => void; + removeItem: (path: string) => void; + getItemAsync?: (path: string) => Promise; + setItemAsync?: (path: string, value: string) => Promise; + removeItemAsync?: (path: string) => Promise; + clear: () => void; + getAllKeys?: () => Array; + getAllKeysAsync?: () => Promise>; + } | { + async: 1; + getItem?: (path: string) => string | null; + setItem?: (path: string, value: string) => void; + removeItem?: (path: string) => void; + getItemAsync: (path: string) => Promise; + setItemAsync: (path: string, value: string) => Promise; + removeItemAsync: (path: string) => Promise; + clear: () => void; + getAllKeys?: () => Array; + getAllKeysAsync?: () => Promise>; + }; + setAsyncStorage(storage: { + getItem: (key: string, callback?: (error?: Error | null, result?: string | null) => void) => Promise; + setItem: (key: string, value: string, callback?: (error?: Error | null) => void) => Promise; + removeItem: (key: string, callback?: (error?: Error | null) => void) => Promise; + mergeItem: (key: string, value: string, callback?: (error?: Error | null) => void) => Promise; + clear: (callback?: (error?: Error | null) => void) => Promise; + getAllKeys: (callback?: (error?: Error | null, result?: readonly string[] | null) => void) => Promise; + multiGet: (keys: readonly string[], callback?: (errors?: readonly (Error | null)[] | null, result?: readonly [string, string][]) => void) => Promise; + multiSet: (keyValuePairs: [string, string][], callback?: (errors?: readonly (Error | null)[] | null) => void) => Promise; + multiRemove: (keys: readonly string[], callback?: (errors?: readonly (Error | null)[] | null) => void) => Promise; + multiMerge: (keyValuePairs: [string, string][], callback?: (errors?: readonly (Error | null)[] | null) => void) => Promise; + }): void; + getAsyncStorage(): { + getItem: (key: string, callback?: (error?: Error | null, result?: string | null) => void) => Promise; + setItem: (key: string, value: string, callback?: (error?: Error | null) => void) => Promise; + removeItem: (key: string, callback?: (error?: Error | null) => void) => Promise; + mergeItem: (key: string, value: string, callback?: (error?: Error | null) => void) => Promise; + clear: (callback?: (error?: Error | null) => void) => Promise; + getAllKeys: (callback?: (error?: Error | null, result?: readonly string[] | null) => void) => Promise; + multiGet: (keys: readonly string[], callback?: (errors?: readonly (Error | null)[] | null, result?: readonly [string, string][]) => void) => Promise; + multiSet: (keyValuePairs: [string, string][], callback?: (errors?: readonly (Error | null)[] | null) => void) => Promise; + multiRemove: (keys: readonly string[], callback?: (errors?: readonly (Error | null)[] | null) => void) => Promise; + multiMerge: (keyValuePairs: [string, string][], callback?: (errors?: readonly (Error | null)[] | null) => void) => Promise; + }; + setWebSocketController(controller: new (url: string | URL, protocols?: string | string[] | undefined) => import("./CoreManager").WebSocketController): void; + getWebSocketController(): new (url: string | URL, protocols?: string | string[] | undefined) => import("./CoreManager").WebSocketController; + setUserController(controller: { + setCurrentUser: (user: User) => Promise; + currentUser: () => User | null; + currentUserAsync: () => Promise; + signUp: (user: User, attrs: import("./ObjectStateMutations").AttributeMap, options?: import("./RESTController").RequestOptions) => Promise; + logIn: (user: User, options?: import("./RESTController").RequestOptions) => Promise; + loginAs: (user: User, userId: string) => Promise; + become: (user: User, options?: import("./RESTController").RequestOptions) => Promise; + hydrate: (user: User, userJSON: import("./ObjectStateMutations").AttributeMap) => Promise; + logOut: (options?: import("./RESTController").RequestOptions) => Promise; + me: (user: User, options?: import("./RESTController").RequestOptions) => Promise; + requestPasswordReset: (email: string, options?: import("./RESTController").RequestOptions) => Promise; + updateUserOnDisk: (user: User) => Promise; + upgradeToRevocableSession: (user: User, options?: import("./RESTController").RequestOptions) => Promise; + linkWith: (user: User, authData: import("./ParseUser").AuthData, options?: import("./RESTController").FullOptions) => Promise; + removeUserFromDisk: () => Promise; + verifyPassword: (username: string, password: string, options?: import("./RESTController").RequestOptions) => Promise; + requestEmailVerification: (email: string, options?: import("./RESTController").RequestOptions) => Promise; + }): void; + getUserController(): { + setCurrentUser: (user: User) => Promise; + currentUser: () => User | null; + currentUserAsync: () => Promise; + signUp: (user: User, attrs: import("./ObjectStateMutations").AttributeMap, options?: import("./RESTController").RequestOptions) => Promise; + logIn: (user: User, options?: import("./RESTController").RequestOptions) => Promise; + loginAs: (user: User, userId: string) => Promise; + become: (user: User, options?: import("./RESTController").RequestOptions) => Promise; + hydrate: (user: User, userJSON: import("./ObjectStateMutations").AttributeMap) => Promise; + logOut: (options?: import("./RESTController").RequestOptions) => Promise; + me: (user: User, options?: import("./RESTController").RequestOptions) => Promise; + requestPasswordReset: (email: string, options?: import("./RESTController").RequestOptions) => Promise; + updateUserOnDisk: (user: User) => Promise; + upgradeToRevocableSession: (user: User, options?: import("./RESTController").RequestOptions) => Promise; + linkWith: (user: User, authData: import("./ParseUser").AuthData, options?: import("./RESTController").FullOptions) => Promise; + removeUserFromDisk: () => Promise; + verifyPassword: (username: string, password: string, options?: import("./RESTController").RequestOptions) => Promise; + requestEmailVerification: (email: string, options?: import("./RESTController").RequestOptions) => Promise; }; - setAsyncStorage(storage: { - getItem: ( - key: string, - callback?: (error?: Error | null, result?: string | null) => void - ) => Promise; - setItem: ( - key: string, - value: string, - callback?: (error?: Error | null) => void - ) => Promise; - removeItem: (key: string, callback?: (error?: Error | null) => void) => Promise; - mergeItem: ( - key: string, - value: string, - callback?: (error?: Error | null) => void - ) => Promise; - clear: (callback?: (error?: Error | null) => void) => Promise; - getAllKeys: ( - callback?: (error?: Error | null, result?: readonly string[] | null) => void - ) => Promise; - multiGet: ( - keys: readonly string[], - callback?: ( - errors?: readonly (Error | null)[] | null, - result?: readonly [string, string][] - ) => void - ) => Promise; - multiSet: ( - keyValuePairs: [string, string][], - callback?: (errors?: readonly (Error | null)[] | null) => void - ) => Promise; - multiRemove: ( - keys: readonly string[], - callback?: (errors?: readonly (Error | null)[] | null) => void - ) => Promise; - multiMerge: ( - keyValuePairs: [string, string][], - callback?: (errors?: readonly (Error | null)[] | null) => void - ) => Promise; - }): void; - getAsyncStorage(): { - getItem: ( - key: string, - callback?: (error?: Error | null, result?: string | null) => void - ) => Promise; - setItem: ( - key: string, - value: string, - callback?: (error?: Error | null) => void - ) => Promise; - removeItem: (key: string, callback?: (error?: Error | null) => void) => Promise; - mergeItem: ( - key: string, - value: string, - callback?: (error?: Error | null) => void - ) => Promise; - clear: (callback?: (error?: Error | null) => void) => Promise; - getAllKeys: ( - callback?: (error?: Error | null, result?: readonly string[] | null) => void - ) => Promise; - multiGet: ( - keys: readonly string[], - callback?: ( - errors?: readonly (Error | null)[] | null, - result?: readonly [string, string][] - ) => void - ) => Promise; - multiSet: ( - keyValuePairs: [string, string][], - callback?: (errors?: readonly (Error | null)[] | null) => void - ) => Promise; - multiRemove: ( - keys: readonly string[], - callback?: (errors?: readonly (Error | null)[] | null) => void - ) => Promise; - multiMerge: ( - keyValuePairs: [string, string][], - callback?: (errors?: readonly (Error | null)[] | null) => void - ) => Promise; + setLiveQueryController(controller: { + setDefaultLiveQueryClient(liveQueryClient: LiveQueryClient): void; + getDefaultLiveQueryClient(): Promise; + _clearCachedDefaultClient(): void; + }): void; + getLiveQueryController(): { + setDefaultLiveQueryClient(liveQueryClient: LiveQueryClient): void; + getDefaultLiveQueryClient(): Promise; + _clearCachedDefaultClient(): void; + }; + setHooksController(controller: { + get: (type: string, functionName?: string, triggerName?: string) => Promise; + create: (hook: Hooks.HookDeclaration) => Promise; + remove: (hook: Hooks.HookDeleteArg) => Promise; + update: (hook: Hooks.HookDeclaration) => Promise; + sendRequest?: (method: string, path: string, body?: any) => Promise; + }): void; + getHooksController(): { + get: (type: string, functionName?: string, triggerName?: string) => Promise; + create: (hook: Hooks.HookDeclaration) => Promise; + remove: (hook: Hooks.HookDeleteArg) => Promise; + update: (hook: Hooks.HookDeclaration) => Promise; + sendRequest?: (method: string, path: string, body?: any) => Promise; + }; + setParseOp(op: any): void; + getParseOp(): any; + setParseObject(object: any): void; + getParseObject(): any; + setParseQuery(query: any): void; + getParseQuery(): any; + setParseRole(role: any): void; + getParseRole(): any; + setParseUser(user: any): void; + getParseUser(): any; + }; + Config: typeof Config; + Error: typeof ParseError; + FacebookUtils: { + init(options: any): void; + isLinked(user: any): any; + logIn(permissions: any, options: any): Promise>; + link(user: any, permissions: any, options: any): any; + unlink: (user: any, options: any) => any; + _getAuthProvider(): import("./ParseUser").AuthProvider; }; - setWebSocketController( - controller: new ( - url: string | URL, - protocols?: string | string[] | undefined - ) => import('./CoreManager').WebSocketController - ): void; - getWebSocketController(): new ( - url: string | URL, - protocols?: string | string[] | undefined - ) => import('./CoreManager').WebSocketController; - setUserController(controller: { - setCurrentUser: (user: User) => Promise; - currentUser: () => User | null; - currentUserAsync: () => Promise; - signUp: ( - user: User, - attrs: import('./ObjectStateMutations').AttributeMap, - options: import('./RESTController').RequestOptions - ) => Promise; - logIn: (user: User, options: import('./RESTController').RequestOptions) => Promise; - loginAs: (user: User, userId: string) => Promise; - become: (user: User, options: import('./RESTController').RequestOptions) => Promise; - hydrate: ( - user: User, - userJSON: import('./ObjectStateMutations').AttributeMap - ) => Promise; - logOut: (options: import('./RESTController').RequestOptions) => Promise; - me: (user: User, options: import('./RESTController').RequestOptions) => Promise; - requestPasswordReset: ( - email: string, - options: import('./RESTController').RequestOptions - ) => Promise; - updateUserOnDisk: (user: User) => Promise; - upgradeToRevocableSession: ( - user: User, - options: import('./RESTController').RequestOptions - ) => Promise; - linkWith: ( - user: User, - authData: import('./ParseUser').AuthData, - options?: import('./RESTController').FullOptions - ) => Promise; - removeUserFromDisk: () => Promise; - verifyPassword: ( - username: string, - password: string, - options: import('./RESTController').RequestOptions - ) => Promise; - requestEmailVerification: ( - email: string, - options: import('./RESTController').RequestOptions - ) => Promise; - }): void; - getUserController(): { - setCurrentUser: (user: User) => Promise; - currentUser: () => User | null; - currentUserAsync: () => Promise; - signUp: ( - user: User, - attrs: import('./ObjectStateMutations').AttributeMap, - options: import('./RESTController').RequestOptions - ) => Promise; - logIn: (user: User, options: import('./RESTController').RequestOptions) => Promise; - loginAs: (user: User, userId: string) => Promise; - become: (user: User, options: import('./RESTController').RequestOptions) => Promise; - hydrate: ( - user: User, - userJSON: import('./ObjectStateMutations').AttributeMap - ) => Promise; - logOut: (options: import('./RESTController').RequestOptions) => Promise; - me: (user: User, options: import('./RESTController').RequestOptions) => Promise; - requestPasswordReset: ( - email: string, - options: import('./RESTController').RequestOptions - ) => Promise; - updateUserOnDisk: (user: User) => Promise; - upgradeToRevocableSession: ( - user: User, - options: import('./RESTController').RequestOptions - ) => Promise; - linkWith: ( - user: User, - authData: import('./ParseUser').AuthData, - options?: import('./RESTController').FullOptions - ) => Promise; - removeUserFromDisk: () => Promise; - verifyPassword: ( - username: string, - password: string, - options: import('./RESTController').RequestOptions - ) => Promise; - requestEmailVerification: ( - email: string, - options: import('./RESTController').RequestOptions - ) => Promise; + File: typeof File; + GeoPoint: typeof GeoPoint; + Polygon: typeof Polygon; + Installation: typeof Installation; + LocalDatastore: { + isEnabled: boolean; + isSyncing: boolean; + fromPinWithName(name: string): Promise>; + pinWithName(name: string, value: any): Promise; + unPinWithName(name: string): Promise; + _getAllContents(): Promise; + _getRawStorage(): Promise; + _clear(): Promise; + _handlePinAllWithName(name: string, objects: Array): Promise; + _handleUnPinAllWithName(name: string, objects: Array): Promise; + _getChildren(object: ParseObject): any; + _traverse(object: any, encountered: any): void; + _serializeObjectsFromPinName(name: string): Promise; + _serializeObject(objectKey: string, localDatastore: any): Promise; + _updateObjectIfPinned(object: ParseObject): Promise; + _destroyObjectIfPinned(object: ParseObject): Promise; + _updateLocalIdForObject(localId: string, object: ParseObject): Promise; + updateFromServer(): Promise; + getKeyForObject(object: any): string; + getPinName(pinName?: string): string; + checkIfEnabled(): any; }; - setLiveQueryController(controller: { - setDefaultLiveQueryClient(liveQueryClient: LiveQueryClient): void; - getDefaultLiveQueryClient(): Promise; - _clearCachedDefaultClient(): void; - }): void; - getLiveQueryController(): { - setDefaultLiveQueryClient(liveQueryClient: LiveQueryClient): void; - getDefaultLiveQueryClient(): Promise; - _clearCachedDefaultClient(): void; + Object: typeof ParseObject; + Op: { + Set: typeof ParseOp.SetOp; + Unset: typeof ParseOp.UnsetOp; + Increment: typeof ParseOp.IncrementOp; + Add: typeof ParseOp.AddOp; + Remove: typeof ParseOp.RemoveOp; + AddUnique: typeof ParseOp.AddUniqueOp; + Relation: typeof ParseOp.RelationOp; }; - setHooksController(controller: { - get: (type: string, functionName?: string, triggerName?: string) => Promise; - create: (hook: Hooks.HookDeclaration) => Promise; - remove: (hook: Hooks.HookDeleteArg) => Promise; - update: (hook: Hooks.HookDeclaration) => Promise; - sendRequest?: (method: string, path: string, body?: any) => Promise; - }): void; - getHooksController(): { - get: (type: string, functionName?: string, triggerName?: string) => Promise; - create: (hook: Hooks.HookDeclaration) => Promise; - remove: (hook: Hooks.HookDeleteArg) => Promise; - update: (hook: Hooks.HookDeclaration) => Promise; - sendRequest?: (method: string, path: string, body?: any) => Promise; + Push: typeof Push; + Query: typeof Query; + Relation: typeof Relation; + Role: typeof Role; + Schema: typeof Schema; + Session: typeof Session; + Storage: { + async(): boolean; + getItem(path: string): string | null; + getItemAsync(path: string): Promise; + setItem(path: string, value: string): void; + setItemAsync(path: string, value: string): Promise; + removeItem(path: string): void; + removeItemAsync(path: string): Promise; + getAllKeys(): Array; + getAllKeysAsync(): Promise>; + generatePath(path: string): string; + _clear(): void; }; - setParseOp(op: any): void; - getParseOp(): any; - setParseObject(object: any): void; - getParseObject(): any; - setParseQuery(query: any): void; - getParseQuery(): any; - setParseRole(role: any): void; - getParseRole(): any; - setParseUser(user: any): void; - getParseUser(): any; - }; - Config: typeof Config; - Error: typeof ParseError; - FacebookUtils: { - init(options: any): void; - isLinked(user: any): any; - logIn(permissions: any, options: any): Promise; - link(user: any, permissions: any, options: any): any; - unlink: (user: any, options: any) => any; - _getAuthProvider(): import('./ParseUser').AuthProviderType; - }; - File: typeof File; - GeoPoint: typeof GeoPoint; - Polygon: typeof Polygon; - Installation: typeof Installation; - LocalDatastore: { - isEnabled: boolean; - isSyncing: boolean; - fromPinWithName(name: string): Promise>; - pinWithName(name: string, value: any): Promise; - unPinWithName(name: string): Promise; - _getAllContents(): Promise; - _getRawStorage(): Promise; - _clear(): Promise; - _handlePinAllWithName(name: string, objects: Array): Promise; - _handleUnPinAllWithName(name: string, objects: Array): Promise; - _getChildren(object: ParseObject): any; - _traverse(object: any, encountered: any): void; - _serializeObjectsFromPinName(name: string): Promise; - _serializeObject(objectKey: string, localDatastore: any): Promise; - _updateObjectIfPinned(object: ParseObject): Promise; - _destroyObjectIfPinned(object: ParseObject): Promise; - _updateLocalIdForObject(localId: string, object: ParseObject): Promise; - updateFromServer(): Promise; - getKeyForObject(object: any): string; - getPinName(pinName?: string): string; - checkIfEnabled(): any; - }; - Object: typeof ParseObject; - Op: { - Set: typeof ParseOp.SetOp; - Unset: typeof ParseOp.UnsetOp; - Increment: typeof ParseOp.IncrementOp; - Add: typeof ParseOp.AddOp; - Remove: typeof ParseOp.RemoveOp; - AddUnique: typeof ParseOp.AddUniqueOp; - Relation: typeof ParseOp.RelationOp; - }; - Push: typeof Push; - Query: typeof Query; - Relation: typeof Relation; - Role: typeof Role; - Schema: typeof Schema; - Session: typeof Session; - Storage: { - async(): boolean; - getItem(path: string): string | null; - getItemAsync(path: string): Promise; - setItem(path: string, value: string): void; - setItemAsync(path: string, value: string): Promise; - removeItem(path: string): void; - removeItemAsync(path: string): Promise; - getAllKeys(): Array; - getAllKeysAsync(): Promise>; - generatePath(path: string): string; - _clear(): void; - }; - User: typeof User; - LiveQueryClient: typeof LiveQueryClient; - IndexedDB: any; - Hooks: any; - Parse: any; - get EventuallyQueue(): any; - /** - * @member {EventuallyQueue} Parse.EventuallyQueue - * @static - */ - set EventuallyQueue(queue: typeof EventuallyQueue); - /** - * Call this method first to set up your authentication tokens for Parse. - * - * @param {string} applicationId Your Parse Application ID. - * @param {string} [javaScriptKey] Your Parse JavaScript Key (Not needed for parse-server) - * @param {string} [masterKey] Your Parse Master Key. (Node.js only!) - * @static - */ - initialize(applicationId: string, javaScriptKey: string): void; - _initialize(applicationId: string, javaScriptKey: string, masterKey?: string): void; - /** - * Call this method to set your AsyncStorage engine - * Starting Parse@1.11, the ParseSDK do not provide a React AsyncStorage as the ReactNative module - * is not provided at a stable path and changes over versions. - * - * @param {AsyncStorage} storage a react native async storage. - * @static - */ - setAsyncStorage(storage: any): void; - /** - * Call this method to set your LocalDatastoreStorage engine - * If using React-Native use {@link Parse.setAsyncStorage Parse.setAsyncStorage()} - * - * @param {LocalDatastoreController} controller a data storage. - * @static - */ - setLocalDatastoreController(controller: any): void; - /** - * Returns information regarding the current server's health - * - * @returns {Promise} - * @static - */ - getServerHealth(): Promise; - /** - * @member {string} Parse.applicationId - * @static - */ - applicationId: any; - /** - * @member {string} Parse.javaScriptKey - * @static - */ - javaScriptKey: any; - /** - * @member {string} Parse.masterKey - * @static - */ - masterKey: any; - /** - * @member {string} Parse.serverURL - * @static - */ - serverURL: any; - /** - * @member {string} Parse.serverAuthToken - * @static - */ - serverAuthToken: any; - /** - * @member {string} Parse.serverAuthType - * @static - */ - serverAuthType: any; - /** - * @member {ParseLiveQuery} Parse.LiveQuery - * @static - */ - LiveQuery: ParseLiveQuery; - /** - * @member {string} Parse.liveQueryServerURL - * @static - */ - liveQueryServerURL: any; - /** - * @member {boolean} Parse.encryptedUser - * @static - */ - encryptedUser: boolean; - /** - * @member {string} Parse.secret - * @static - */ - secret: any; - /** - * @member {boolean} Parse.idempotency - * @static - */ - idempotency: any; - /** - * @member {boolean} Parse.allowCustomObjectId - * @static - */ - allowCustomObjectId: any; - _request(...args: any[]): any; - _ajax(...args: any[]): any; - _decode(_: any, value: any): any; - _encode(value: any, _: any, disallowObjects: any): any; - _getInstallationId(): Promise; - /** - * Enable pinning in your application. - * This must be called after `Parse.initialize` in your application. - * - * @param [polling] Allow pinging the server /health endpoint. Default true - * @param [ms] Milliseconds to ping the server. Default 2000ms - * @static - */ - enableLocalDatastore(polling?: boolean, ms?: number): void; - /** - * Flag that indicates whether Local Datastore is enabled. - * - * @static - * @returns {boolean} - */ - isLocalDatastoreEnabled(): any; - /** - * Gets all contents from Local Datastore - * - *
-   * await Parse.dumpLocalDatastore();
-   * 
- * - * @static - * @returns {object} - */ - dumpLocalDatastore(): Promise; - /** - * Enable the current user encryption. - * This must be called before login any user. - * - * @static - */ - enableEncryptedUser(): void; - /** - * Flag that indicates whether Encrypted User is enabled. - * - * @static - * @returns {boolean} - */ - isEncryptedUserEnabled(): any; + User: typeof User; + LiveQueryClient: typeof LiveQueryClient; + IndexedDB: any; + Hooks: any; + Parse: any; + /** + * @member {EventuallyQueue} Parse.EventuallyQueue + * @static + */ + EventuallyQueue: EventuallyQueue; + /** + * Call this method first to set up your authentication tokens for Parse. + * + * @param {string} applicationId Your Parse Application ID. + * @param {string} [javaScriptKey] Your Parse JavaScript Key (Not needed for parse-server) + * @param {string} [masterKey] Your Parse Master Key. (Node.js only!) + * @static + */ + initialize(applicationId: string, javaScriptKey: string): void; + _initialize(applicationId: string, javaScriptKey: string, masterKey?: string, maintenanceKey?: string): void; + /** + * Call this method to set your AsyncStorage engine + * Starting Parse@1.11, the ParseSDK do not provide a React AsyncStorage as the ReactNative module + * is not provided at a stable path and changes over versions. + * + * @param {AsyncStorage} storage a react native async storage. + * @static + */ + setAsyncStorage(storage: any): void; + /** + * Call this method to set your LocalDatastoreStorage engine + * If using React-Native use {@link Parse.setAsyncStorage Parse.setAsyncStorage()} + * + * @param {LocalDatastoreController} controller a data storage. + * @static + */ + setLocalDatastoreController(controller: any): void; + /** + * Returns information regarding the current server's health + * + * @returns {Promise} + * @static + */ + getServerHealth(): Promise; + /** + * @member {string} Parse.applicationId + * @static + */ + applicationId: any; + /** + * @member {string} Parse.javaScriptKey + * @static + */ + javaScriptKey: any; + /** + * @member {string} Parse.masterKey + * @static + */ + masterKey: any; + /** + * @member {string} Parse.maintenanceKey + * @static + */ + maintenanceKey: any; + /** + * @member {string} Parse.serverURL + * @static + */ + serverURL: any; + /** + * @member {string} Parse.serverAuthToken + * @static + */ + serverAuthToken: any; + /** + * @member {string} Parse.serverAuthType + * @static + */ + serverAuthType: any; + /** + * @member {ParseLiveQuery} Parse.LiveQuery + * @static + */ + LiveQuery: ParseLiveQuery; + /** + * @member {string} Parse.liveQueryServerURL + * @static + */ + liveQueryServerURL: any; + /** + * @member {boolean} Parse.encryptedUser + * @static + */ + encryptedUser: boolean; + /** + * @member {string} Parse.secret + * @static + */ + secret: any; + /** + * @member {boolean} Parse.idempotency + * @static + */ + idempotency: any; + /** + * @member {boolean} Parse.allowCustomObjectId + * @static + */ + allowCustomObjectId: any; + _request(...args: any[]): any; + _ajax(...args: any[]): any; + _decode(_: any, value: any): any; + _encode(value: any, _: any, disallowObjects: any): any; + _getInstallationId(): Promise; + /** + * Enable pinning in your application. + * This must be called after `Parse.initialize` in your application. + * + * @param [polling] Allow pinging the server /health endpoint. Default true + * @param [ms] Milliseconds to ping the server. Default 2000ms + * @static + */ + enableLocalDatastore(polling?: boolean, ms?: number): void; + /** + * Flag that indicates whether Local Datastore is enabled. + * + * @static + * @returns {boolean} + */ + isLocalDatastoreEnabled(): boolean; + /** + * Gets all contents from Local Datastore + * + *
+     * await Parse.dumpLocalDatastore();
+     * 
+ * + * @static + * @returns {object} + */ + dumpLocalDatastore(): Promise; + /** + * Enable the current user encryption. + * This must be called before login any user. + * + * @static + */ + enableEncryptedUser(): void; + /** + * Flag that indicates whether Encrypted User is enabled. + * + * @static + * @returns {boolean} + */ + isEncryptedUserEnabled(): any; }; export default Parse; diff --git a/types/ParseACL.d.ts b/types/ParseACL.d.ts index fc8da8570..124f27d10 100644 --- a/types/ParseACL.d.ts +++ b/types/ParseACL.d.ts @@ -1,10 +1,10 @@ import type ParseRole from './ParseRole'; import type ParseUser from './ParseUser'; type PermissionsMap = { - [permission: string]: boolean; + [permission: string]: boolean; }; type ByIdMap = { - [userId: string]: PermissionsMap; + [userId: string]: PermissionsMap; }; /** * Creates a new ACL. @@ -21,121 +21,121 @@ type ByIdMap = { * @alias Parse.ACL */ declare class ParseACL { - permissionsById: ByIdMap; - /** - * @param {(Parse.User | object)} arg1 The user to initialize the ACL for - */ - constructor(arg1: ParseUser | ByIdMap); - /** - * Returns a JSON-encoded version of the ACL. - * - * @returns {object} - */ - toJSON(): ByIdMap; - /** - * Returns whether this ACL is equal to another object - * - * @param {ParseACL} other The other object's ACL to compare to - * @returns {boolean} - */ - equals(other: ParseACL): boolean; - _setAccess(accessType: string, userId: ParseUser | ParseRole | string, allowed: boolean): void; - _getAccess(accessType: string, userId: ParseUser | ParseRole | string): boolean; - /** - * Sets whether the given user is allowed to read this object. - * - * @param userId An instance of Parse.User or its objectId. - * @param {boolean} allowed Whether that user should have read access. - */ - setReadAccess(userId: ParseUser | ParseRole | string, allowed: boolean): void; - /** - * Get whether the given user id is *explicitly* allowed to read this object. - * Even if this returns false, the user may still be able to access it if - * getPublicReadAccess returns true or a role that the user belongs to has - * write access. - * - * @param userId An instance of Parse.User or its objectId, or a Parse.Role. - * @returns {boolean} - */ - getReadAccess(userId: ParseUser | ParseRole | string): boolean; - /** - * Sets whether the given user id is allowed to write this object. - * - * @param userId An instance of Parse.User or its objectId, or a Parse.Role.. - * @param {boolean} allowed Whether that user should have write access. - */ - setWriteAccess(userId: ParseUser | ParseRole | string, allowed: boolean): void; - /** - * Gets whether the given user id is *explicitly* allowed to write this object. - * Even if this returns false, the user may still be able to write it if - * getPublicWriteAccess returns true or a role that the user belongs to has - * write access. - * - * @param userId An instance of Parse.User or its objectId, or a Parse.Role. - * @returns {boolean} - */ - getWriteAccess(userId: ParseUser | ParseRole | string): boolean; - /** - * Sets whether the public is allowed to read this object. - * - * @param {boolean} allowed - */ - setPublicReadAccess(allowed: boolean): void; - /** - * Gets whether the public is allowed to read this object. - * - * @returns {boolean} - */ - getPublicReadAccess(): boolean; - /** - * Sets whether the public is allowed to write this object. - * - * @param {boolean} allowed - */ - setPublicWriteAccess(allowed: boolean): void; - /** - * Gets whether the public is allowed to write this object. - * - * @returns {boolean} - */ - getPublicWriteAccess(): boolean; - /** - * Gets whether users belonging to the given role are allowed - * to read this object. Even if this returns false, the role may - * still be able to write it if a parent role has read access. - * - * @param role The name of the role, or a Parse.Role object. - * @returns {boolean} true if the role has read access. false otherwise. - * @throws {TypeError} If role is neither a Parse.Role nor a String. - */ - getRoleReadAccess(role: ParseRole | string): boolean; - /** - * Gets whether users belonging to the given role are allowed - * to write this object. Even if this returns false, the role may - * still be able to write it if a parent role has write access. - * - * @param role The name of the role, or a Parse.Role object. - * @returns {boolean} true if the role has write access. false otherwise. - * @throws {TypeError} If role is neither a Parse.Role nor a String. - */ - getRoleWriteAccess(role: ParseRole | string): boolean; - /** - * Sets whether users belonging to the given role are allowed - * to read this object. - * - * @param role The name of the role, or a Parse.Role object. - * @param {boolean} allowed Whether the given role can read this object. - * @throws {TypeError} If role is neither a Parse.Role nor a String. - */ - setRoleReadAccess(role: ParseRole | string, allowed: boolean): void; - /** - * Sets whether users belonging to the given role are allowed - * to write this object. - * - * @param role The name of the role, or a Parse.Role object. - * @param {boolean} allowed Whether the given role can write this object. - * @throws {TypeError} If role is neither a Parse.Role nor a String. - */ - setRoleWriteAccess(role: ParseRole | string, allowed: boolean): void; + permissionsById: ByIdMap; + /** + * @param {(Parse.User | object | null)} arg1 The user to initialize the ACL for + */ + constructor(arg1?: ParseUser | ByIdMap | null); + /** + * Returns a JSON-encoded version of the ACL. + * + * @returns {object} + */ + toJSON(): ByIdMap; + /** + * Returns whether this ACL is equal to another object + * + * @param {ParseACL} other The other object's ACL to compare to + * @returns {boolean} + */ + equals(other: ParseACL): boolean; + _setAccess(accessType: string, userId: ParseUser | ParseRole | string, allowed: boolean): void; + _getAccess(accessType: string, userId: ParseUser | ParseRole | string): boolean; + /** + * Sets whether the given user is allowed to read this object. + * + * @param userId An instance of Parse.User or its objectId. + * @param {boolean} allowed Whether that user should have read access. + */ + setReadAccess(userId: ParseUser | ParseRole | string, allowed: boolean): void; + /** + * Get whether the given user id is *explicitly* allowed to read this object. + * Even if this returns false, the user may still be able to access it if + * getPublicReadAccess returns true or a role that the user belongs to has + * write access. + * + * @param userId An instance of Parse.User or its objectId, or a Parse.Role. + * @returns {boolean} + */ + getReadAccess(userId: ParseUser | ParseRole | string): boolean; + /** + * Sets whether the given user id is allowed to write this object. + * + * @param userId An instance of Parse.User or its objectId, or a Parse.Role.. + * @param {boolean} allowed Whether that user should have write access. + */ + setWriteAccess(userId: ParseUser | ParseRole | string, allowed: boolean): void; + /** + * Gets whether the given user id is *explicitly* allowed to write this object. + * Even if this returns false, the user may still be able to write it if + * getPublicWriteAccess returns true or a role that the user belongs to has + * write access. + * + * @param userId An instance of Parse.User or its objectId, or a Parse.Role. + * @returns {boolean} + */ + getWriteAccess(userId: ParseUser | ParseRole | string): boolean; + /** + * Sets whether the public is allowed to read this object. + * + * @param {boolean} allowed + */ + setPublicReadAccess(allowed: boolean): void; + /** + * Gets whether the public is allowed to read this object. + * + * @returns {boolean} + */ + getPublicReadAccess(): boolean; + /** + * Sets whether the public is allowed to write this object. + * + * @param {boolean} allowed + */ + setPublicWriteAccess(allowed: boolean): void; + /** + * Gets whether the public is allowed to write this object. + * + * @returns {boolean} + */ + getPublicWriteAccess(): boolean; + /** + * Gets whether users belonging to the given role are allowed + * to read this object. Even if this returns false, the role may + * still be able to write it if a parent role has read access. + * + * @param role The name of the role, or a Parse.Role object. + * @returns {boolean} true if the role has read access. false otherwise. + * @throws {TypeError} If role is neither a Parse.Role nor a String. + */ + getRoleReadAccess(role: ParseRole | string): boolean; + /** + * Gets whether users belonging to the given role are allowed + * to write this object. Even if this returns false, the role may + * still be able to write it if a parent role has write access. + * + * @param role The name of the role, or a Parse.Role object. + * @returns {boolean} true if the role has write access. false otherwise. + * @throws {TypeError} If role is neither a Parse.Role nor a String. + */ + getRoleWriteAccess(role: ParseRole | string): boolean; + /** + * Sets whether users belonging to the given role are allowed + * to read this object. + * + * @param role The name of the role, or a Parse.Role object. + * @param {boolean} allowed Whether the given role can read this object. + * @throws {TypeError} If role is neither a Parse.Role nor a String. + */ + setRoleReadAccess(role: ParseRole | string, allowed: boolean): void; + /** + * Sets whether users belonging to the given role are allowed + * to write this object. + * + * @param role The name of the role, or a Parse.Role object. + * @param {boolean} allowed Whether the given role can write this object. + * @throws {TypeError} If role is neither a Parse.Role nor a String. + */ + setRoleWriteAccess(role: ParseRole | string, allowed: boolean): void; } export default ParseACL; diff --git a/types/ParseCLP.d.ts b/types/ParseCLP.d.ts index 9a3d8e3b3..eaa7d6b26 100644 --- a/types/ParseCLP.d.ts +++ b/types/ParseCLP.d.ts @@ -2,13 +2,13 @@ import ParseRole from './ParseRole'; import ParseUser from './ParseUser'; type Entity = ParseUser | ParseRole | string; type UsersMap = { - [userId: string]: boolean | any; + [userId: string]: boolean | any; }; export type PermissionsMap = { - writeUserFields?: string[]; - readUserFields?: string[]; + writeUserFields?: string[]; + readUserFields?: string[]; } & { - [permission: string]: UsersMap; + [permission: string]: UsersMap; }; /** * Creates a new CLP. @@ -103,191 +103,191 @@ export type PermissionsMap = { * @alias Parse.CLP */ declare class ParseCLP { - permissionsMap: PermissionsMap; - /** - * @param {(Parse.User | Parse.Role | object)} userId The user to initialize the CLP for - */ - constructor(userId: ParseUser | ParseRole | PermissionsMap); - /** - * Returns a JSON-encoded version of the CLP. - * - * @returns {object} - */ - toJSON(): PermissionsMap; - /** - * Returns whether this CLP is equal to another object - * - * @param other The other object to compare to - * @returns {boolean} - */ - equals(other: ParseCLP): boolean; - _getRoleName(role: ParseRole | string): string; - _parseEntity(entity: Entity): string; - _setAccess(permission: string, userId: Entity, allowed: boolean): void; - _getAccess(permission: string, userId: Entity, returnBoolean?: boolean): boolean | string[]; - _setArrayAccess(permission: string, userId: Entity, fields: string[]): void; - _setGroupPointerPermission(operation: string, pointerFields: string[]): void; - _getGroupPointerPermissions(operation: 'readUserFields' | 'writeUserFields'): string[]; - /** - * Sets user pointer fields to allow permission for get/count/find operations. - * - * @param {string[]} pointerFields User pointer fields - */ - setReadUserFields(pointerFields: string[]): void; - /** - * @returns {string[]} User pointer fields - */ - getReadUserFields(): string[]; - /** - * Sets user pointer fields to allow permission for create/delete/update/addField operations - * - * @param {string[]} pointerFields User pointer fields - */ - setWriteUserFields(pointerFields: string[]): void; - /** - * @returns {string[]} User pointer fields - */ - getWriteUserFields(): string[]; - /** - * Sets whether the given user is allowed to retrieve fields from this class. - * - * @param userId An instance of Parse.User or its objectId. - * @param {string[]} fields fields to be protected - */ - setProtectedFields(userId: Entity, fields: string[]): void; - /** - * Returns array of fields are accessable to this user. - * - * @param userId An instance of Parse.User or its objectId, or a Parse.Role. - * @returns {string[]} - */ - getProtectedFields(userId: Entity): string[]; - /** - * Sets whether the given user is allowed to read from this class. - * - * @param userId An instance of Parse.User or its objectId. - * @param {boolean} allowed whether that user should have read access. - */ - setReadAccess(userId: Entity, allowed: boolean): void; - /** - * Get whether the given user id is *explicitly* allowed to read from this class. - * Even if this returns false, the user may still be able to access it if - * getPublicReadAccess returns true or a role that the user belongs to has - * write access. - * - * @param userId An instance of Parse.User or its objectId, or a Parse.Role. - * @returns {boolean} - */ - getReadAccess(userId: Entity): boolean; - /** - * Sets whether the given user id is allowed to write to this class. - * - * @param userId An instance of Parse.User or its objectId, or a Parse.Role.. - * @param {boolean} allowed Whether that user should have write access. - */ - setWriteAccess(userId: Entity, allowed: boolean): void; - /** - * Gets whether the given user id is *explicitly* allowed to write to this class. - * Even if this returns false, the user may still be able to write it if - * getPublicWriteAccess returns true or a role that the user belongs to has - * write access. - * - * @param userId An instance of Parse.User or its objectId, or a Parse.Role. - * @returns {boolean} - */ - getWriteAccess(userId: Entity): boolean; - /** - * Sets whether the public is allowed to read from this class. - * - * @param {boolean} allowed - */ - setPublicReadAccess(allowed: boolean): void; - /** - * Gets whether the public is allowed to read from this class. - * - * @returns {boolean} - */ - getPublicReadAccess(): boolean; - /** - * Sets whether the public is allowed to write to this class. - * - * @param {boolean} allowed - */ - setPublicWriteAccess(allowed: boolean): void; - /** - * Gets whether the public is allowed to write to this class. - * - * @returns {boolean} - */ - getPublicWriteAccess(): boolean; - /** - * Sets whether the public is allowed to protect fields in this class. - * - * @param {string[]} fields - */ - setPublicProtectedFields(fields: string[]): void; - /** - * Gets whether the public is allowed to read fields from this class. - * - * @returns {string[]} - */ - getPublicProtectedFields(): string[]; - /** - * Gets whether users belonging to the given role are allowed - * to read from this class. Even if this returns false, the role may - * still be able to write it if a parent role has read access. - * - * @param role The name of the role, or a Parse.Role object. - * @returns {boolean} true if the role has read access. false otherwise. - * @throws {TypeError} If role is neither a Parse.Role nor a String. - */ - getRoleReadAccess(role: ParseRole | string): boolean; - /** - * Gets whether users belonging to the given role are allowed - * to write to this user. Even if this returns false, the role may - * still be able to write it if a parent role has write access. - * - * @param role The name of the role, or a Parse.Role object. - * @returns {boolean} true if the role has write access. false otherwise. - * @throws {TypeError} If role is neither a Parse.Role nor a String. - */ - getRoleWriteAccess(role: ParseRole | string): boolean; - /** - * Sets whether users belonging to the given role are allowed - * to read from this class. - * - * @param role The name of the role, or a Parse.Role object. - * @param {boolean} allowed Whether the given role can read this object. - * @throws {TypeError} If role is neither a Parse.Role nor a String. - */ - setRoleReadAccess(role: ParseRole | string, allowed: boolean): void; - /** - * Sets whether users belonging to the given role are allowed - * to write to this class. - * - * @param role The name of the role, or a Parse.Role object. - * @param {boolean} allowed Whether the given role can write this object. - * @throws {TypeError} If role is neither a Parse.Role nor a String. - */ - setRoleWriteAccess(role: ParseRole | string, allowed: boolean): void; - /** - * Gets whether users belonging to the given role are allowed - * to count to this user. Even if this returns false, the role may - * still be able to count it if a parent role has count access. - * - * @param role The name of the role, or a Parse.Role object. - * @returns {string[]} - * @throws {TypeError} If role is neither a Parse.Role nor a String. - */ - getRoleProtectedFields(role: ParseRole | string): string[]; - /** - * Sets whether users belonging to the given role are allowed - * to set access field in this class. - * - * @param role The name of the role, or a Parse.Role object. - * @param {string[]} fields Fields to be protected by Role. - * @throws {TypeError} If role is neither a Parse.Role nor a String. - */ - setRoleProtectedFields(role: ParseRole | string, fields: string[]): void; + permissionsMap: PermissionsMap; + /** + * @param {(Parse.User | Parse.Role | object)} userId The user to initialize the CLP for + */ + constructor(userId: ParseUser | ParseRole | PermissionsMap); + /** + * Returns a JSON-encoded version of the CLP. + * + * @returns {object} + */ + toJSON(): PermissionsMap; + /** + * Returns whether this CLP is equal to another object + * + * @param other The other object to compare to + * @returns {boolean} + */ + equals(other: ParseCLP): boolean; + _getRoleName(role: ParseRole | string): string; + _parseEntity(entity: Entity): string; + _setAccess(permission: string, userId: Entity, allowed: boolean): void; + _getAccess(permission: string, userId: Entity, returnBoolean?: boolean): boolean | string[]; + _setArrayAccess(permission: string, userId: Entity, fields: string[]): void; + _setGroupPointerPermission(operation: string, pointerFields: string[]): void; + _getGroupPointerPermissions(operation: 'readUserFields' | 'writeUserFields'): string[]; + /** + * Sets user pointer fields to allow permission for get/count/find operations. + * + * @param {string[]} pointerFields User pointer fields + */ + setReadUserFields(pointerFields: string[]): void; + /** + * @returns {string[]} User pointer fields + */ + getReadUserFields(): string[]; + /** + * Sets user pointer fields to allow permission for create/delete/update/addField operations + * + * @param {string[]} pointerFields User pointer fields + */ + setWriteUserFields(pointerFields: string[]): void; + /** + * @returns {string[]} User pointer fields + */ + getWriteUserFields(): string[]; + /** + * Sets whether the given user is allowed to retrieve fields from this class. + * + * @param userId An instance of Parse.User or its objectId. + * @param {string[]} fields fields to be protected + */ + setProtectedFields(userId: Entity, fields: string[]): void; + /** + * Returns array of fields are accessable to this user. + * + * @param userId An instance of Parse.User or its objectId, or a Parse.Role. + * @returns {string[]} + */ + getProtectedFields(userId: Entity): string[]; + /** + * Sets whether the given user is allowed to read from this class. + * + * @param userId An instance of Parse.User or its objectId. + * @param {boolean} allowed whether that user should have read access. + */ + setReadAccess(userId: Entity, allowed: boolean): void; + /** + * Get whether the given user id is *explicitly* allowed to read from this class. + * Even if this returns false, the user may still be able to access it if + * getPublicReadAccess returns true or a role that the user belongs to has + * write access. + * + * @param userId An instance of Parse.User or its objectId, or a Parse.Role. + * @returns {boolean} + */ + getReadAccess(userId: Entity): boolean; + /** + * Sets whether the given user id is allowed to write to this class. + * + * @param userId An instance of Parse.User or its objectId, or a Parse.Role.. + * @param {boolean} allowed Whether that user should have write access. + */ + setWriteAccess(userId: Entity, allowed: boolean): void; + /** + * Gets whether the given user id is *explicitly* allowed to write to this class. + * Even if this returns false, the user may still be able to write it if + * getPublicWriteAccess returns true or a role that the user belongs to has + * write access. + * + * @param userId An instance of Parse.User or its objectId, or a Parse.Role. + * @returns {boolean} + */ + getWriteAccess(userId: Entity): boolean; + /** + * Sets whether the public is allowed to read from this class. + * + * @param {boolean} allowed + */ + setPublicReadAccess(allowed: boolean): void; + /** + * Gets whether the public is allowed to read from this class. + * + * @returns {boolean} + */ + getPublicReadAccess(): boolean; + /** + * Sets whether the public is allowed to write to this class. + * + * @param {boolean} allowed + */ + setPublicWriteAccess(allowed: boolean): void; + /** + * Gets whether the public is allowed to write to this class. + * + * @returns {boolean} + */ + getPublicWriteAccess(): boolean; + /** + * Sets whether the public is allowed to protect fields in this class. + * + * @param {string[]} fields + */ + setPublicProtectedFields(fields: string[]): void; + /** + * Gets whether the public is allowed to read fields from this class. + * + * @returns {string[]} + */ + getPublicProtectedFields(): string[]; + /** + * Gets whether users belonging to the given role are allowed + * to read from this class. Even if this returns false, the role may + * still be able to write it if a parent role has read access. + * + * @param role The name of the role, or a Parse.Role object. + * @returns {boolean} true if the role has read access. false otherwise. + * @throws {TypeError} If role is neither a Parse.Role nor a String. + */ + getRoleReadAccess(role: ParseRole | string): boolean; + /** + * Gets whether users belonging to the given role are allowed + * to write to this user. Even if this returns false, the role may + * still be able to write it if a parent role has write access. + * + * @param role The name of the role, or a Parse.Role object. + * @returns {boolean} true if the role has write access. false otherwise. + * @throws {TypeError} If role is neither a Parse.Role nor a String. + */ + getRoleWriteAccess(role: ParseRole | string): boolean; + /** + * Sets whether users belonging to the given role are allowed + * to read from this class. + * + * @param role The name of the role, or a Parse.Role object. + * @param {boolean} allowed Whether the given role can read this object. + * @throws {TypeError} If role is neither a Parse.Role nor a String. + */ + setRoleReadAccess(role: ParseRole | string, allowed: boolean): void; + /** + * Sets whether users belonging to the given role are allowed + * to write to this class. + * + * @param role The name of the role, or a Parse.Role object. + * @param {boolean} allowed Whether the given role can write this object. + * @throws {TypeError} If role is neither a Parse.Role nor a String. + */ + setRoleWriteAccess(role: ParseRole | string, allowed: boolean): void; + /** + * Gets whether users belonging to the given role are allowed + * to count to this user. Even if this returns false, the role may + * still be able to count it if a parent role has count access. + * + * @param role The name of the role, or a Parse.Role object. + * @returns {string[]} + * @throws {TypeError} If role is neither a Parse.Role nor a String. + */ + getRoleProtectedFields(role: ParseRole | string): string[]; + /** + * Sets whether users belonging to the given role are allowed + * to set access field in this class. + * + * @param role The name of the role, or a Parse.Role object. + * @param {string[]} fields Fields to be protected by Role. + * @throws {TypeError} If role is neither a Parse.Role nor a String. + */ + setRoleProtectedFields(role: ParseRole | string, fields: string[]): void; } export default ParseCLP; diff --git a/types/ParseConfig.d.ts b/types/ParseConfig.d.ts index a4fb48d07..cfd77f36d 100644 --- a/types/ParseConfig.d.ts +++ b/types/ParseConfig.d.ts @@ -6,75 +6,72 @@ import type { RequestOptions } from './RESTController'; * @alias Parse.Config */ declare class ParseConfig { - attributes: { - [key: string]: any; - }; - _escapedAttributes: { - [key: string]: any; - }; - constructor(); - /** - * Gets the value of an attribute. - * - * @param {string} attr The name of an attribute. - * @returns {*} - */ - get(attr: string): any; - /** - * Gets the HTML-escaped value of an attribute. - * - * @param {string} attr The name of an attribute. - * @returns {string} - */ - escape(attr: string): string; - /** - * Retrieves the most recently-fetched configuration object, either from - * memory or from local storage if necessary. - * - * @static - * @returns {Parse.Config} The most recently-fetched Parse.Config if it - * exists, else an empty Parse.Config. - */ - static current(): ParseConfig | Promise; - /** - * Gets a new configuration object from the server. - * - * @static - * @param {object} options - * Valid options are:
    - *
  • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
- * @returns {Promise} A promise that is resolved with a newly-created - * configuration object when the get completes. - */ - static get(options?: RequestOptions): Promise; - /** - * Save value keys to the server. - * - * @static - * @param {object} attrs The config parameters and values. - * @param {object} masterKeyOnlyFlags The flags that define whether config parameters listed - * in `attrs` should be retrievable only by using the master key. - * For example: `param1: true` makes `param1` only retrievable by using the master key. - * If a parameter is not provided or set to `false`, it can be retrieved without - * using the master key. - * @returns {Promise} A promise that is resolved with a newly-created - * configuration object or with the current with the update. - */ - static save( - attrs: { - [key: string]: any; - }, - masterKeyOnlyFlags: { - [key: string]: any; - } - ): Promise; - /** - * Used for testing - * - * @private - */ - static _clearCache(): void; + attributes: { + [key: string]: any; + }; + _escapedAttributes: { + [key: string]: any; + }; + constructor(); + /** + * Gets the value of an attribute. + * + * @param {string} attr The name of an attribute. + * @returns {*} + */ + get(attr: string): any; + /** + * Gets the HTML-escaped value of an attribute. + * + * @param {string} attr The name of an attribute. + * @returns {string} + */ + escape(attr: string): string; + /** + * Retrieves the most recently-fetched configuration object, either from + * memory or from local storage if necessary. + * + * @static + * @returns {Parse.Config} The most recently-fetched Parse.Config if it + * exists, else an empty Parse.Config. + */ + static current(): ParseConfig | Promise; + /** + * Gets a new configuration object from the server. + * + * @static + * @param {object} options + * Valid options are:
    + *
  • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
+ * @returns {Promise} A promise that is resolved with a newly-created + * configuration object when the get completes. + */ + static get(options?: RequestOptions): Promise; + /** + * Save value keys to the server. + * + * @static + * @param {object} attrs The config parameters and values. + * @param {object} masterKeyOnlyFlags The flags that define whether config parameters listed + * in `attrs` should be retrievable only by using the master key. + * For example: `param1: true` makes `param1` only retrievable by using the master key. + * If a parameter is not provided or set to `false`, it can be retrieved without + * using the master key. + * @returns {Promise} A promise that is resolved with a newly-created + * configuration object or with the current with the update. + */ + static save(attrs: { + [key: string]: any; + }, masterKeyOnlyFlags: { + [key: string]: any; + }): Promise; + /** + * Used for testing + * + * @private + */ + static _clearCache(): void; } export default ParseConfig; diff --git a/types/ParseError.d.ts b/types/ParseError.d.ts index 5147fd681..f6bbb073f 100644 --- a/types/ParseError.d.ts +++ b/types/ParseError.d.ts @@ -7,470 +7,470 @@ import type ParseObject from './ParseObject'; * @alias Parse.Error */ declare class ParseError extends Error { - code: number; - message: string; - object?: ParseObject; - errors?: Error[]; - /** - * @param {number} code An error code constant from Parse.Error. - * @param {string} message A detailed description of the error. - */ - constructor(code: number, message?: string); - toString(): string; - /** - * Error code indicating some error other than those enumerated here. - * - * @property {number} OTHER_CAUSE - * @static - */ - static OTHER_CAUSE: number; - /** - * Error code indicating that something has gone wrong with the server. - * - * @property {number} INTERNAL_SERVER_ERROR - * @static - */ - static INTERNAL_SERVER_ERROR: number; - /** - * Error code indicating the connection to the Parse servers failed. - * - * @property {number} CONNECTION_FAILED - * @static - */ - static CONNECTION_FAILED: number; - /** - * Error code indicating the specified object doesn't exist. - * - * @property {number} OBJECT_NOT_FOUND - * @static - */ - static OBJECT_NOT_FOUND: number; - /** - * Error code indicating you tried to query with a datatype that doesn't - * support it, like exact matching an array or object. - * - * @property {number} INVALID_QUERY - * @static - */ - static INVALID_QUERY: number; - /** - * 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. - * - * @property {number} INVALID_CLASS_NAME - * @static - */ - static INVALID_CLASS_NAME: number; - /** - * Error code indicating an unspecified object id. - * - * @property {number} MISSING_OBJECT_ID - * @static - */ - static MISSING_OBJECT_ID: number; - /** - * 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. - * - * @property {number} INVALID_KEY_NAME - * @static - */ - static INVALID_KEY_NAME: number; - /** - * Error code indicating a malformed pointer. You should not see this unless - * you have been mucking about changing internal Parse code. - * - * @property {number} INVALID_POINTER - * @static - */ - static INVALID_POINTER: number; - /** - * 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. - * - * @property {number} INVALID_JSON - * @static - */ - static INVALID_JSON: number; - /** - * Error code indicating that the feature you tried to access is only - * available internally for testing purposes. - * - * @property {number} COMMAND_UNAVAILABLE - * @static - */ - static COMMAND_UNAVAILABLE: number; - /** - * You must call Parse.initialize before using the Parse library. - * - * @property {number} NOT_INITIALIZED - * @static - */ - static NOT_INITIALIZED: number; - /** - * Error code indicating that a field was set to an inconsistent type. - * - * @property {number} INCORRECT_TYPE - * @static - */ - static INCORRECT_TYPE: number; - /** - * 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. - * - * @property {number} INVALID_CHANNEL_NAME - * @static - */ - static INVALID_CHANNEL_NAME: number; - /** - * Error code indicating that push is misconfigured. - * - * @property {number} PUSH_MISCONFIGURED - * @static - */ - static PUSH_MISCONFIGURED: number; - /** - * Error code indicating that the object is too large. - * - * @property {number} OBJECT_TOO_LARGE - * @static - */ - static OBJECT_TOO_LARGE: number; - /** - * Error code indicating that the operation isn't allowed for clients. - * - * @property {number} OPERATION_FORBIDDEN - * @static - */ - static OPERATION_FORBIDDEN: number; - /** - * Error code indicating the result was not found in the cache. - * - * @property {number} CACHE_MISS - * @static - */ - static CACHE_MISS: number; - /** - * Error code indicating that an invalid key was used in a nested - * JSONObject. - * - * @property {number} INVALID_NESTED_KEY - * @static - */ - static INVALID_NESTED_KEY: number; - /** - * 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. - * - * @property {number} INVALID_FILE_NAME - * @static - */ - static INVALID_FILE_NAME: number; - /** - * Error code indicating an invalid ACL was provided. - * - * @property {number} INVALID_ACL - * @static - */ - static INVALID_ACL: number; - /** - * Error code indicating that the request timed out on the server. Typically - * this indicates that the request is too expensive to run. - * - * @property {number} TIMEOUT - * @static - */ - static TIMEOUT: number; - /** - * Error code indicating that the email address was invalid. - * - * @property {number} INVALID_EMAIL_ADDRESS - * @static - */ - static INVALID_EMAIL_ADDRESS: number; - /** - * Error code indicating a missing content type. - * - * @property {number} MISSING_CONTENT_TYPE - * @static - */ - static MISSING_CONTENT_TYPE: number; - /** - * Error code indicating a missing content length. - * - * @property {number} MISSING_CONTENT_LENGTH - * @static - */ - static MISSING_CONTENT_LENGTH: number; - /** - * Error code indicating an invalid content length. - * - * @property {number} INVALID_CONTENT_LENGTH - * @static - */ - static INVALID_CONTENT_LENGTH: number; - /** - * Error code indicating a file that was too large. - * - * @property {number} FILE_TOO_LARGE - * @static - */ - static FILE_TOO_LARGE: number; - /** - * Error code indicating an error saving a file. - * - * @property {number} FILE_SAVE_ERROR - * @static - */ - static FILE_SAVE_ERROR: number; - /** - * Error code indicating that a unique field was given a value that is - * already taken. - * - * @property {number} DUPLICATE_VALUE - * @static - */ - static DUPLICATE_VALUE: number; - /** - * Error code indicating that a role's name is invalid. - * - * @property {number} INVALID_ROLE_NAME - * @static - */ - static INVALID_ROLE_NAME: number; - /** - * Error code indicating that an application quota was exceeded. Upgrade to - * resolve. - * - * @property {number} EXCEEDED_QUOTA - * @static - */ - static EXCEEDED_QUOTA: number; - /** - * Error code indicating that a Cloud Code script failed. - * - * @property {number} SCRIPT_FAILED - * @static - */ - static SCRIPT_FAILED: number; - /** - * Error code indicating that a Cloud Code validation failed. - * - * @property {number} VALIDATION_ERROR - * @static - */ - static VALIDATION_ERROR: number; - /** - * Error code indicating that invalid image data was provided. - * - * @property {number} INVALID_IMAGE_DATA - * @static - */ - static INVALID_IMAGE_DATA: number; - /** - * Error code indicating an unsaved file. - * - * @property {number} UNSAVED_FILE_ERROR - * @static - */ - static UNSAVED_FILE_ERROR: number; - /** - * Error code indicating an invalid push time. - * - * @property {number} INVALID_PUSH_TIME_ERROR - * @static - */ - static INVALID_PUSH_TIME_ERROR: number; - /** - * Error code indicating an error deleting a file. - * - * @property {number} FILE_DELETE_ERROR - * @static - */ - static FILE_DELETE_ERROR: number; - /** - * Error code indicating an error deleting an unnamed file. - * - * @property {number} FILE_DELETE_UNNAMED_ERROR - * @static - */ - static FILE_DELETE_UNNAMED_ERROR: number; - /** - * Error code indicating that the application has exceeded its request - * limit. - * - * @property {number} REQUEST_LIMIT_EXCEEDED - * @static - */ - static REQUEST_LIMIT_EXCEEDED: number; - /** - * Error code indicating that the request was a duplicate and has been discarded due to - * idempotency rules. - * - * @property {number} DUPLICATE_REQUEST - * @static - */ - static DUPLICATE_REQUEST: number; - /** - * Error code indicating an invalid event name. - * - * @property {number} INVALID_EVENT_NAME - * @static - */ - static INVALID_EVENT_NAME: number; - /** - * Error code indicating that a field had an invalid value. - * - * @property {number} INVALID_VALUE - * @static - */ - static INVALID_VALUE: number; - /** - * Error code indicating that the username is missing or empty. - * - * @property {number} USERNAME_MISSING - * @static - */ - static USERNAME_MISSING: number; - /** - * Error code indicating that the password is missing or empty. - * - * @property {number} PASSWORD_MISSING - * @static - */ - static PASSWORD_MISSING: number; - /** - * Error code indicating that the username has already been taken. - * - * @property {number} USERNAME_TAKEN - * @static - */ - static USERNAME_TAKEN: number; - /** - * Error code indicating that the email has already been taken. - * - * @property {number} EMAIL_TAKEN - * @static - */ - static EMAIL_TAKEN: number; - /** - * Error code indicating that the email is missing, but must be specified. - * - * @property {number} EMAIL_MISSING - * @static - */ - static EMAIL_MISSING: number; - /** - * Error code indicating that a user with the specified email was not found. - * - * @property {number} EMAIL_NOT_FOUND - * @static - */ - static EMAIL_NOT_FOUND: number; - /** - * Error code indicating that a user object without a valid session could - * not be altered. - * - * @property {number} SESSION_MISSING - * @static - */ - static SESSION_MISSING: number; - /** - * Error code indicating that a user can only be created through signup. - * - * @property {number} MUST_CREATE_USER_THROUGH_SIGNUP - * @static - */ - static MUST_CREATE_USER_THROUGH_SIGNUP: number; - /** - * Error code indicating that an an account being linked is already linked - * to another user. - * - * @property {number} ACCOUNT_ALREADY_LINKED - * @static - */ - static ACCOUNT_ALREADY_LINKED: number; - /** - * Error code indicating that the current session token is invalid. - * - * @property {number} INVALID_SESSION_TOKEN - * @static - */ - static INVALID_SESSION_TOKEN: number; - /** - * Error code indicating an error enabling or verifying MFA - * - * @property {number} MFA_ERROR - * @static - */ - static MFA_ERROR: number; - /** - * Error code indicating that a valid MFA token must be provided - * - * @property {number} MFA_TOKEN_REQUIRED - * @static - */ - static MFA_TOKEN_REQUIRED: number; - /** - * Error code indicating that a user cannot be linked to an account because - * that account's id could not be found. - * - * @property {number} LINKED_ID_MISSING - * @static - */ - static LINKED_ID_MISSING: number; - /** - * Error code indicating that a user with a linked (e.g. Facebook) account - * has an invalid session. - * - * @property {number} INVALID_LINKED_SESSION - * @static - */ - static INVALID_LINKED_SESSION: number; - /** - * Error code indicating that a service being linked (e.g. Facebook or - * Twitter) is unsupported. - * - * @property {number} UNSUPPORTED_SERVICE - * @static - */ - static UNSUPPORTED_SERVICE: number; - /** - * Error code indicating an invalid operation occured on schema - * - * @property {number} INVALID_SCHEMA_OPERATION - * @static - */ - static INVALID_SCHEMA_OPERATION: number; - /** - * 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. - * - * @property {number} AGGREGATE_ERROR - * @static - */ - static AGGREGATE_ERROR: number; - /** - * Error code indicating the client was unable to read an input file. - * - * @property {number} FILE_READ_ERROR - * @static - */ - static FILE_READ_ERROR: number; - /** - * 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. - * - * @property {number} X_DOMAIN_REQUEST - * @static - */ - static X_DOMAIN_REQUEST: number; + code: number; + message: string; + object?: ParseObject; + errors?: Error[]; + /** + * @param {number} code An error code constant from Parse.Error. + * @param {string} message A detailed description of the error. + */ + constructor(code: number, message?: string); + toString(): string; + /** + * Error code indicating some error other than those enumerated here. + * + * @property {number} OTHER_CAUSE + * @static + */ + static OTHER_CAUSE: number; + /** + * Error code indicating that something has gone wrong with the server. + * + * @property {number} INTERNAL_SERVER_ERROR + * @static + */ + static INTERNAL_SERVER_ERROR: number; + /** + * Error code indicating the connection to the Parse servers failed. + * + * @property {number} CONNECTION_FAILED + * @static + */ + static CONNECTION_FAILED: number; + /** + * Error code indicating the specified object doesn't exist. + * + * @property {number} OBJECT_NOT_FOUND + * @static + */ + static OBJECT_NOT_FOUND: number; + /** + * Error code indicating you tried to query with a datatype that doesn't + * support it, like exact matching an array or object. + * + * @property {number} INVALID_QUERY + * @static + */ + static INVALID_QUERY: number; + /** + * 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. + * + * @property {number} INVALID_CLASS_NAME + * @static + */ + static INVALID_CLASS_NAME: number; + /** + * Error code indicating an unspecified object id. + * + * @property {number} MISSING_OBJECT_ID + * @static + */ + static MISSING_OBJECT_ID: number; + /** + * 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. + * + * @property {number} INVALID_KEY_NAME + * @static + */ + static INVALID_KEY_NAME: number; + /** + * Error code indicating a malformed pointer. You should not see this unless + * you have been mucking about changing internal Parse code. + * + * @property {number} INVALID_POINTER + * @static + */ + static INVALID_POINTER: number; + /** + * 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. + * + * @property {number} INVALID_JSON + * @static + */ + static INVALID_JSON: number; + /** + * Error code indicating that the feature you tried to access is only + * available internally for testing purposes. + * + * @property {number} COMMAND_UNAVAILABLE + * @static + */ + static COMMAND_UNAVAILABLE: number; + /** + * You must call Parse.initialize before using the Parse library. + * + * @property {number} NOT_INITIALIZED + * @static + */ + static NOT_INITIALIZED: number; + /** + * Error code indicating that a field was set to an inconsistent type. + * + * @property {number} INCORRECT_TYPE + * @static + */ + static INCORRECT_TYPE: number; + /** + * 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. + * + * @property {number} INVALID_CHANNEL_NAME + * @static + */ + static INVALID_CHANNEL_NAME: number; + /** + * Error code indicating that push is misconfigured. + * + * @property {number} PUSH_MISCONFIGURED + * @static + */ + static PUSH_MISCONFIGURED: number; + /** + * Error code indicating that the object is too large. + * + * @property {number} OBJECT_TOO_LARGE + * @static + */ + static OBJECT_TOO_LARGE: number; + /** + * Error code indicating that the operation isn't allowed for clients. + * + * @property {number} OPERATION_FORBIDDEN + * @static + */ + static OPERATION_FORBIDDEN: number; + /** + * Error code indicating the result was not found in the cache. + * + * @property {number} CACHE_MISS + * @static + */ + static CACHE_MISS: number; + /** + * Error code indicating that an invalid key was used in a nested + * JSONObject. + * + * @property {number} INVALID_NESTED_KEY + * @static + */ + static INVALID_NESTED_KEY: number; + /** + * 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. + * + * @property {number} INVALID_FILE_NAME + * @static + */ + static INVALID_FILE_NAME: number; + /** + * Error code indicating an invalid ACL was provided. + * + * @property {number} INVALID_ACL + * @static + */ + static INVALID_ACL: number; + /** + * Error code indicating that the request timed out on the server. Typically + * this indicates that the request is too expensive to run. + * + * @property {number} TIMEOUT + * @static + */ + static TIMEOUT: number; + /** + * Error code indicating that the email address was invalid. + * + * @property {number} INVALID_EMAIL_ADDRESS + * @static + */ + static INVALID_EMAIL_ADDRESS: number; + /** + * Error code indicating a missing content type. + * + * @property {number} MISSING_CONTENT_TYPE + * @static + */ + static MISSING_CONTENT_TYPE: number; + /** + * Error code indicating a missing content length. + * + * @property {number} MISSING_CONTENT_LENGTH + * @static + */ + static MISSING_CONTENT_LENGTH: number; + /** + * Error code indicating an invalid content length. + * + * @property {number} INVALID_CONTENT_LENGTH + * @static + */ + static INVALID_CONTENT_LENGTH: number; + /** + * Error code indicating a file that was too large. + * + * @property {number} FILE_TOO_LARGE + * @static + */ + static FILE_TOO_LARGE: number; + /** + * Error code indicating an error saving a file. + * + * @property {number} FILE_SAVE_ERROR + * @static + */ + static FILE_SAVE_ERROR: number; + /** + * Error code indicating that a unique field was given a value that is + * already taken. + * + * @property {number} DUPLICATE_VALUE + * @static + */ + static DUPLICATE_VALUE: number; + /** + * Error code indicating that a role's name is invalid. + * + * @property {number} INVALID_ROLE_NAME + * @static + */ + static INVALID_ROLE_NAME: number; + /** + * Error code indicating that an application quota was exceeded. Upgrade to + * resolve. + * + * @property {number} EXCEEDED_QUOTA + * @static + */ + static EXCEEDED_QUOTA: number; + /** + * Error code indicating that a Cloud Code script failed. + * + * @property {number} SCRIPT_FAILED + * @static + */ + static SCRIPT_FAILED: number; + /** + * Error code indicating that a Cloud Code validation failed. + * + * @property {number} VALIDATION_ERROR + * @static + */ + static VALIDATION_ERROR: number; + /** + * Error code indicating that invalid image data was provided. + * + * @property {number} INVALID_IMAGE_DATA + * @static + */ + static INVALID_IMAGE_DATA: number; + /** + * Error code indicating an unsaved file. + * + * @property {number} UNSAVED_FILE_ERROR + * @static + */ + static UNSAVED_FILE_ERROR: number; + /** + * Error code indicating an invalid push time. + * + * @property {number} INVALID_PUSH_TIME_ERROR + * @static + */ + static INVALID_PUSH_TIME_ERROR: number; + /** + * Error code indicating an error deleting a file. + * + * @property {number} FILE_DELETE_ERROR + * @static + */ + static FILE_DELETE_ERROR: number; + /** + * Error code indicating an error deleting an unnamed file. + * + * @property {number} FILE_DELETE_UNNAMED_ERROR + * @static + */ + static FILE_DELETE_UNNAMED_ERROR: number; + /** + * Error code indicating that the application has exceeded its request + * limit. + * + * @property {number} REQUEST_LIMIT_EXCEEDED + * @static + */ + static REQUEST_LIMIT_EXCEEDED: number; + /** + * Error code indicating that the request was a duplicate and has been discarded due to + * idempotency rules. + * + * @property {number} DUPLICATE_REQUEST + * @static + */ + static DUPLICATE_REQUEST: number; + /** + * Error code indicating an invalid event name. + * + * @property {number} INVALID_EVENT_NAME + * @static + */ + static INVALID_EVENT_NAME: number; + /** + * Error code indicating that a field had an invalid value. + * + * @property {number} INVALID_VALUE + * @static + */ + static INVALID_VALUE: number; + /** + * Error code indicating that the username is missing or empty. + * + * @property {number} USERNAME_MISSING + * @static + */ + static USERNAME_MISSING: number; + /** + * Error code indicating that the password is missing or empty. + * + * @property {number} PASSWORD_MISSING + * @static + */ + static PASSWORD_MISSING: number; + /** + * Error code indicating that the username has already been taken. + * + * @property {number} USERNAME_TAKEN + * @static + */ + static USERNAME_TAKEN: number; + /** + * Error code indicating that the email has already been taken. + * + * @property {number} EMAIL_TAKEN + * @static + */ + static EMAIL_TAKEN: number; + /** + * Error code indicating that the email is missing, but must be specified. + * + * @property {number} EMAIL_MISSING + * @static + */ + static EMAIL_MISSING: number; + /** + * Error code indicating that a user with the specified email was not found. + * + * @property {number} EMAIL_NOT_FOUND + * @static + */ + static EMAIL_NOT_FOUND: number; + /** + * Error code indicating that a user object without a valid session could + * not be altered. + * + * @property {number} SESSION_MISSING + * @static + */ + static SESSION_MISSING: number; + /** + * Error code indicating that a user can only be created through signup. + * + * @property {number} MUST_CREATE_USER_THROUGH_SIGNUP + * @static + */ + static MUST_CREATE_USER_THROUGH_SIGNUP: number; + /** + * Error code indicating that an an account being linked is already linked + * to another user. + * + * @property {number} ACCOUNT_ALREADY_LINKED + * @static + */ + static ACCOUNT_ALREADY_LINKED: number; + /** + * Error code indicating that the current session token is invalid. + * + * @property {number} INVALID_SESSION_TOKEN + * @static + */ + static INVALID_SESSION_TOKEN: number; + /** + * Error code indicating an error enabling or verifying MFA + * + * @property {number} MFA_ERROR + * @static + */ + static MFA_ERROR: number; + /** + * Error code indicating that a valid MFA token must be provided + * + * @property {number} MFA_TOKEN_REQUIRED + * @static + */ + static MFA_TOKEN_REQUIRED: number; + /** + * Error code indicating that a user cannot be linked to an account because + * that account's id could not be found. + * + * @property {number} LINKED_ID_MISSING + * @static + */ + static LINKED_ID_MISSING: number; + /** + * Error code indicating that a user with a linked (e.g. Facebook) account + * has an invalid session. + * + * @property {number} INVALID_LINKED_SESSION + * @static + */ + static INVALID_LINKED_SESSION: number; + /** + * Error code indicating that a service being linked (e.g. Facebook or + * Twitter) is unsupported. + * + * @property {number} UNSUPPORTED_SERVICE + * @static + */ + static UNSUPPORTED_SERVICE: number; + /** + * Error code indicating an invalid operation occured on schema + * + * @property {number} INVALID_SCHEMA_OPERATION + * @static + */ + static INVALID_SCHEMA_OPERATION: number; + /** + * 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. + * + * @property {number} AGGREGATE_ERROR + * @static + */ + static AGGREGATE_ERROR: number; + /** + * Error code indicating the client was unable to read an input file. + * + * @property {number} FILE_READ_ERROR + * @static + */ + static FILE_READ_ERROR: number; + /** + * 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. + * + * @property {number} X_DOMAIN_REQUEST + * @static + */ + static X_DOMAIN_REQUEST: number; } export default ParseError; diff --git a/types/ParseFile.d.ts b/types/ParseFile.d.ts index d7eab6ba3..da9c7e48e 100644 --- a/types/ParseFile.d.ts +++ b/types/ParseFile.d.ts @@ -1,35 +1,32 @@ import type { FullOptions } from './RESTController'; type Base64 = { - base64: string; + base64: string; }; type Uri = { - uri: string; + uri: string; }; type FileData = Array | Base64 | Blob | Uri; export type FileSaveOptions = FullOptions & { - metadata?: { - [key: string]: any; - }; - tags?: { - [key: string]: any; - }; -}; -export type FileSource = - | { - format: 'file'; - file: Blob; - type: string | undefined; - } - | { - format: 'base64'; - base64: string; - type: string | undefined; - } - | { - format: 'uri'; - uri: string; - type: string | undefined; + metadata?: { + [key: string]: any; + }; + tags?: { + [key: string]: any; }; +}; +export type FileSource = { + format: 'file'; + file: Blob; + type: string | undefined; +} | { + format: 'base64'; + base64: string; + type: string | undefined; +} | { + format: 'uri'; + uri: string; + type: string | undefined; +}; /** * A Parse.File is a local representation of a file that is saved to the Parse * cloud. @@ -37,159 +34,159 @@ export type FileSource = * @alias Parse.File */ declare class ParseFile { - _name: string; - _url?: string; - _source: FileSource; - _previousSave?: Promise; - _data?: string; - _requestTask?: any; - _metadata?: object; - _tags?: object; - /** - * @param name {String} 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 {Array} 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. an Object like { uri: "..." } with a uri String. - * 4. 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 {String} Optional Content-Type header to use for the file. If - * this is omitted, the content type will be inferred from the name's - * extension. - * @param metadata {object} Optional key value pairs to be stored with file object - * @param tags {object} Optional key value pairs to be stored with file object - */ - constructor(name: string, data?: FileData, type?: string, metadata?: object, tags?: object); - /** - * 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} Promise that is resolve with base64 data - */ - getData(): Promise; - /** - * Gets the name of the file. Before save is called, this is the filename - * given by the user. After save is called, that name gets prefixed with a - * unique identifier. - * - * @returns {string} - */ - name(): string; - /** - * Gets the url of the file. It is only available after you save the file or - * after you get the file from a Parse.Object. - * - * @param {object} options An object to specify url options - * @param {boolean} [options.forceSecure] force the url to be secure - * @returns {string | undefined} - */ - url(options?: { forceSecure?: boolean }): string | undefined; - /** - * Gets the metadata of the file. - * - * @returns {object} - */ - metadata(): object; - /** - * Gets the tags of the file. - * - * @returns {object} - */ - tags(): object; - /** - * Saves the file to the Parse cloud. - * - * @param {object} options - * Valid options are:
    - *
  • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
  • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
  • progress: In Browser only, callback for upload progress. For example: - *
    -   * let parseFile = new Parse.File(name, file);
    -   * parseFile.save({
    -   *   progress: (progressValue, loaded, total, { type }) => {
    -   *     if (type === "upload" && progressValue !== null) {
    -   *       // Update the UI using progressValue
    -   *     }
    -   *   }
    -   * });
    -   * 
    - *
- * @returns {Promise | undefined} Promise that is resolved when the save finishes. - */ - save( - options?: FileSaveOptions & { - requestTask?: any; - } - ): Promise | undefined; - /** - * Aborts the request if it has already been sent. - */ - cancel(): void; - /** - * Deletes the file from the Parse cloud. - * In Cloud Code and Node only with Master Key. - * - * @param {object} options - * Valid options are:
    - *
  • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    -   * @returns {Promise} Promise that is resolved when the delete finishes.
    -   */
    -  destroy(options?: FullOptions): Promise;
    -  toJSON(): {
    -    __type: 'File';
    -    name?: string;
    -    url?: string;
    -  };
    -  equals(other: any): boolean;
    -  /**
    -   * Sets metadata to be saved with file object. Overwrites existing metadata
    -   *
    -   * @param {object} metadata Key value pairs to be stored with file object
    -   */
    -  setMetadata(metadata: any): void;
    -  /**
    -   * Sets metadata to be saved with file object. Adds to existing metadata.
    -   *
    -   * @param {string} key key to store the metadata
    -   * @param {*} value metadata
    -   */
    -  addMetadata(key: string, value: any): void;
    -  /**
    -   * Sets tags to be saved with file object. Overwrites existing tags
    -   *
    -   * @param {object} tags Key value pairs to be stored with file object
    -   */
    -  setTags(tags: any): void;
    -  /**
    -   * Sets tags to be saved with file object. Adds to existing tags.
    -   *
    -   * @param {string} key key to store tags
    -   * @param {*} value tag
    -   */
    -  addTag(key: string, value: string): void;
    -  static fromJSON(obj: any): ParseFile;
    -  static encodeBase64(bytes: Array | Uint8Array): string;
    +    _name: string;
    +    _url?: string;
    +    _source: FileSource;
    +    _previousSave?: Promise;
    +    _data?: string;
    +    _requestTask?: any;
    +    _metadata?: Record;
    +    _tags?: Record;
    +    /**
    +     * @param name {String} 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 {Array} 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. an Object like { uri: "..." } with a uri String.
    +     *     4. 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 {String} Optional Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + * @param metadata {object} Optional key value pairs to be stored with file object + * @param tags {object} Optional key value pairs to be stored with file object + */ + constructor(name: string, data?: FileData, type?: string, metadata?: object, tags?: object); + /** + * 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} Promise that is resolve with base64 data + */ + getData(): Promise; + /** + * Gets the name of the file. Before save is called, this is the filename + * given by the user. After save is called, that name gets prefixed with a + * unique identifier. + * + * @returns {string} + */ + name(): string; + /** + * Gets the url of the file. It is only available after you save the file or + * after you get the file from a Parse.Object. + * + * @param {object} options An object to specify url options + * @param {boolean} [options.forceSecure] force the url to be secure + * @returns {string | undefined} + */ + url(options?: { + forceSecure?: boolean; + }): string | undefined; + /** + * Gets the metadata of the file. + * + * @returns {object} + */ + metadata(): Record; + /** + * Gets the tags of the file. + * + * @returns {object} + */ + tags(): Record; + /** + * Saves the file to the Parse cloud. + * + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • progress: In Browser only, callback for upload progress. For example: + *
      +     * let parseFile = new Parse.File(name, file);
      +     * parseFile.save({
      +     *   progress: (progressValue, loaded, total, { type }) => {
      +     *     if (type === "upload" && progressValue !== null) {
      +     *       // Update the UI using progressValue
      +     *     }
      +     *   }
      +     * });
      +     * 
      + *
    + * @returns {Promise | undefined} Promise that is resolved when the save finishes. + */ + save(options?: FileSaveOptions & { + requestTask?: any; + }): Promise | undefined; + /** + * Aborts the request if it has already been sent. + */ + cancel(): void; + /** + * Deletes the file from the Parse cloud. + * In Cloud Code and Node only with Master Key. + * + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
      +     * @returns {Promise} Promise that is resolved when the delete finishes.
      +     */
      +    destroy(options?: FullOptions): Promise;
      +    toJSON(): {
      +        __type: 'File';
      +        name?: string;
      +        url?: string;
      +    };
      +    equals(other: any): boolean;
      +    /**
      +     * Sets metadata to be saved with file object. Overwrites existing metadata
      +     *
      +     * @param {object} metadata Key value pairs to be stored with file object
      +     */
      +    setMetadata(metadata: Record): void;
      +    /**
      +     * Sets metadata to be saved with file object. Adds to existing metadata.
      +     *
      +     * @param {string} key key to store the metadata
      +     * @param {*} value metadata
      +     */
      +    addMetadata(key: string, value: any): void;
      +    /**
      +     * Sets tags to be saved with file object. Overwrites existing tags
      +     *
      +     * @param {object} tags Key value pairs to be stored with file object
      +     */
      +    setTags(tags: Record): void;
      +    /**
      +     * Sets tags to be saved with file object. Adds to existing tags.
      +     *
      +     * @param {string} key key to store tags
      +     * @param {*} value tag
      +     */
      +    addTag(key: string, value: string): void;
      +    static fromJSON(obj: any): ParseFile;
      +    static encodeBase64(bytes: Array | Uint8Array): string;
       }
       export default ParseFile;
      diff --git a/types/ParseGeoPoint.d.ts b/types/ParseGeoPoint.d.ts
      index 7c2c6b432..5fc86688b 100644
      --- a/types/ParseGeoPoint.d.ts
      +++ b/types/ParseGeoPoint.d.ts
      @@ -22,89 +22,83 @@
        * @alias Parse.GeoPoint
        */
       declare class ParseGeoPoint {
      -  _latitude: number;
      -  _longitude: number;
      -  /**
      -   * @param {(number[] | object | number)} arg1 Either a list of coordinate pairs, an object with `latitude`, `longitude`, or the latitude or the point.
      -   * @param {number} arg2 The longitude of the GeoPoint
      -   */
      -  constructor(
      -    arg1:
      -      | Array
      -      | {
      -          latitude: number;
      -          longitude: number;
      -        }
      -      | number,
      -    arg2?: number
      -  );
      -  /**
      -   * North-south portion of the coordinate, in range [-90, 90].
      -   * Throws an exception if set out of range in a modern browser.
      -   *
      -   * @property {number} latitude
      -   * @returns {number}
      -   */
      -  get latitude(): number;
      -  set latitude(val: number);
      -  /**
      -   * East-west portion of the coordinate, in range [-180, 180].
      -   * Throws if set out of range in a modern browser.
      -   *
      -   * @property {number} longitude
      -   * @returns {number}
      -   */
      -  get longitude(): number;
      -  set longitude(val: number);
      -  /**
      -   * Returns a JSON representation of the GeoPoint, suitable for Parse.
      -   *
      -   * @returns {object}
      -   */
      -  toJSON(): {
      -    __type: string;
      -    latitude: number;
      -    longitude: number;
      -  };
      -  equals(other: any): boolean;
      -  /**
      -   * Returns the distance from this GeoPoint to another in radians.
      -   *
      -   * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
      -   * @returns {number}
      -   */
      -  radiansTo(point: ParseGeoPoint): number;
      -  /**
      -   * Returns the distance from this GeoPoint to another in kilometers.
      -   *
      -   * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
      -   * @returns {number}
      -   */
      -  kilometersTo(point: ParseGeoPoint): number;
      -  /**
      -   * Returns the distance from this GeoPoint to another in miles.
      -   *
      -   * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
      -   * @returns {number}
      -   */
      -  milesTo(point: ParseGeoPoint): number;
      -  static _validate(latitude: number, longitude: number): void;
      -  /**
      -   * Creates a GeoPoint with the user's current location, if available.
      -   *
      -   * @param {object} options The options.
      -   * @param {boolean} [options.enableHighAccuracy] A boolean value that indicates the application would like to receive the best possible results.
      -   *  If true and if the device is able to provide a more accurate position, it will do so.
      -   *  Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example).
      -   *  On the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power. Default: false.
      -   * @param {number} [options.timeout] A positive long value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position.
      -   *  The default value is Infinity, meaning that getCurrentPosition() won't return until the position is available.
      -   * @param {number} [options.maximumAge] A positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return.
      -   *  If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position.
      -   *  If set to Infinity the device must return a cached position regardless of its age. Default: 0.
      -   * @static
      -   * @returns {Promise} User's current location
      -   */
      -  static current(options: any): Promise;
      +    _latitude: number;
      +    _longitude: number;
      +    /**
      +     * @param {(number[] | object | number)} arg1 Either a list of coordinate pairs, an object with `latitude`, `longitude`, or the latitude or the point.
      +     * @param {number} arg2 The longitude of the GeoPoint
      +     */
      +    constructor(arg1?: [number, number] | {
      +        latitude: number;
      +        longitude: number;
      +    } | number, arg2?: number);
      +    /**
      +     * North-south portion of the coordinate, in range [-90, 90].
      +     * Throws an exception if set out of range in a modern browser.
      +     *
      +     * @property {number} latitude
      +     * @returns {number}
      +     */
      +    get latitude(): number;
      +    set latitude(val: number);
      +    /**
      +     * East-west portion of the coordinate, in range [-180, 180].
      +     * Throws if set out of range in a modern browser.
      +     *
      +     * @property {number} longitude
      +     * @returns {number}
      +     */
      +    get longitude(): number;
      +    set longitude(val: number);
      +    /**
      +     * Returns a JSON representation of the GeoPoint, suitable for Parse.
      +     *
      +     * @returns {object}
      +     */
      +    toJSON(): {
      +        __type: string;
      +        latitude: number;
      +        longitude: number;
      +    };
      +    equals(other: any): boolean;
      +    /**
      +     * Returns the distance from this GeoPoint to another in radians.
      +     *
      +     * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
      +     * @returns {number}
      +     */
      +    radiansTo(point: ParseGeoPoint): number;
      +    /**
      +     * Returns the distance from this GeoPoint to another in kilometers.
      +     *
      +     * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
      +     * @returns {number}
      +     */
      +    kilometersTo(point: ParseGeoPoint): number;
      +    /**
      +     * Returns the distance from this GeoPoint to another in miles.
      +     *
      +     * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
      +     * @returns {number}
      +     */
      +    milesTo(point: ParseGeoPoint): number;
      +    static _validate(latitude: number, longitude: number): void;
      +    /**
      +     * Creates a GeoPoint with the user's current location, if available.
      +     *
      +     * @param {object} options The options.
      +     * @param {boolean} [options.enableHighAccuracy] A boolean value that indicates the application would like to receive the best possible results.
      +     *  If true and if the device is able to provide a more accurate position, it will do so.
      +     *  Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example).
      +     *  On the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power. Default: false.
      +     * @param {number} [options.timeout] A positive long value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position.
      +     *  The default value is Infinity, meaning that getCurrentPosition() won't return until the position is available.
      +     * @param {number} [options.maximumAge] A positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return.
      +     *  If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position.
      +     *  If set to Infinity the device must return a cached position regardless of its age. Default: 0.
      +     * @static
      +     * @returns {Promise} User's current location
      +     */
      +    static current(options: any): Promise;
       }
       export default ParseGeoPoint;
      diff --git a/types/ParseHooks.d.ts b/types/ParseHooks.d.ts
      index 525af90dc..e854b0d76 100644
      --- a/types/ParseHooks.d.ts
      +++ b/types/ParseHooks.d.ts
      @@ -1,38 +1,26 @@
      -export type HookDeclaration =
      -  | {
      -      functionName: string;
      -      url: string;
      -    }
      -  | {
      -      className: string;
      -      triggerName: string;
      -      url: string;
      -    };
      -export type HookDeleteArg =
      -  | {
      -      functionName: string;
      -    }
      -  | {
      -      className: string;
      -      triggerName: string;
      -    };
      +export type HookDeclaration = {
      +    functionName: string;
      +    url: string;
      +} | {
      +    className: string;
      +    triggerName: string;
      +    url: string;
      +};
      +export type HookDeleteArg = {
      +    functionName: string;
      +} | {
      +    className: string;
      +    triggerName: string;
      +};
       export declare function getFunctions(): Promise;
       export declare function getTriggers(): Promise;
       export declare function getFunction(name: string): Promise;
       export declare function getTrigger(className: string, triggerName: string): Promise;
       export declare function createFunction(functionName: string, url: string): Promise;
      -export declare function createTrigger(
      -  className: string,
      -  triggerName: string,
      -  url: string
      -): Promise;
      +export declare function createTrigger(className: string, triggerName: string, url: string): Promise;
       export declare function create(hook: HookDeclaration): Promise;
       export declare function updateFunction(functionName: string, url: string): Promise;
      -export declare function updateTrigger(
      -  className: string,
      -  triggerName: string,
      -  url: string
      -): Promise;
      +export declare function updateTrigger(className: string, triggerName: string, url: string): Promise;
       export declare function update(hook: HookDeclaration): Promise;
       export declare function removeFunction(functionName: string): Promise;
       export declare function removeTrigger(className: string, triggerName: string): Promise;
      diff --git a/types/ParseInstallation.d.ts b/types/ParseInstallation.d.ts
      index 1743dce1d..402245a50 100644
      --- a/types/ParseInstallation.d.ts
      +++ b/types/ParseInstallation.d.ts
      @@ -1,12 +1,11 @@
      -import ParseObject from './ParseObject';
      -import type { AttributeMap } from './ObjectStateMutations';
      +import ParseObject, { Attributes } from './ParseObject';
       type DeviceInterface = {
      -  IOS: string;
      -  MACOS: string;
      -  TVOS: string;
      -  FCM: string;
      -  ANDROID: string;
      -  WEB: string;
      +    IOS: string;
      +    MACOS: string;
      +    TVOS: string;
      +    FCM: string;
      +    ANDROID: string;
      +    WEB: string;
       };
       /**
        * Parse.Installation is a local representation of installation data that can be saved and retrieved from the Parse cloud.
      @@ -19,162 +18,162 @@ type DeviceInterface = {
        *
        * @alias Parse.Installation
        */
      -declare class ParseInstallation extends ParseObject {
      -  /**
      -   * @param {object} attributes The initial set of data to store in the object.
      -   */
      -  constructor(attributes?: AttributeMap);
      -  /**
      -   * A unique identifier for this installation’s client application. In iOS, this is the Bundle Identifier.
      -   *
      -   * @property {string} appIdentifier
      -   * @static
      -   * @returns {string}
      -   */
      -  get appIdentifier(): any;
      -  /**
      -   * The version string of the client application to which this installation belongs.
      -   *
      -   * @property {string} appVersion
      -   * @static
      -   * @returns {string}
      -   */
      -  get appVersion(): any;
      -  /**
      -   * The display name of the client application to which this installation belongs.
      -   *
      -   * @property {string} appName
      -   * @static
      -   * @returns {string}
      -   */
      -  get appName(): any;
      -  /**
      -   * The current value of the icon badge for iOS apps.
      -   * Changes to this value on the server will be used
      -   * for future badge-increment push notifications.
      -   *
      -   * @property {number} badge
      -   * @static
      -   * @returns {number}
      -   */
      -  get badge(): any;
      -  /**
      -   * An array of the channels to which a device is currently subscribed.
      -   *
      -   * @property {string[]} channels
      -   * @static
      -   * @returns {string[]}
      -   */
      -  get channels(): any;
      -  /**
      -   * Token used to deliver push notifications to the device.
      -   *
      -   * @property {string} deviceToken
      -   * @static
      -   * @returns {string}
      -   */
      -  get deviceToken(): any;
      -  /**
      -   * The type of device, “ios”, “android”, “web”, etc.
      -   *
      -   * @property {string} deviceType
      -   * @static
      -   * @returns {string}
      -   */
      -  get deviceType(): any;
      -  /**
      -   * Gets the GCM sender identifier for this installation
      -   *
      -   * @property {string} GCMSenderId
      -   * @static
      -   * @returns {string}
      -   */
      -  get GCMSenderId(): any;
      -  /**
      -   * Universally Unique Identifier (UUID) for the device used by Parse. It must be unique across all of an app’s installations.
      -   *
      -   * @property {string} installationId
      -   * @static
      -   * @returns {string}
      -   */
      -  get installationId(): any;
      -  /**
      -   * Gets the local identifier for this installation
      -   *
      -   * @property {string} localeIdentifier
      -   * @static
      -   * @returns {string}
      -   */
      -  get localeIdentifier(): any;
      -  /**
      -   * Gets the parse server version for this installation
      -   *
      -   * @property {string} parseVersion
      -   * @static
      -   * @returns {string}
      -   */
      -  get parseVersion(): any;
      -  /**
      -   * This field is reserved for directing Parse to the push delivery network to be used.
      -   *
      -   * @property {string} pushType
      -   * @static
      -   * @returns {string}
      -   */
      -  get pushType(): any;
      -  /**
      -   * Gets the time zone for this installation
      -   *
      -   * @property {string} timeZone
      -   * @static
      -   * @returns {string}
      -   */
      -  get timeZone(): any;
      -  /**
      -   * Returns the device types for used for Push Notifications.
      -   *
      -   * 
      -   * Parse.Installation.DEVICE_TYPES.IOS
      -   * Parse.Installation.DEVICE_TYPES.MACOS
      -   * Parse.Installation.DEVICE_TYPES.TVOS
      -   * Parse.Installation.DEVICE_TYPES.FCM
      -   * Parse.Installation.DEVICE_TYPES.ANDROID
      -   * Parse.Installation.DEVICE_TYPES.WEB
      -   * 
      ): Promise; - /** - * Wrap the default save behavior with functionality to update the local storage. - * If the installation is deleted on the server, retry saving a new installation. - * - * @param {...any} args - * @returns {Promise} - */ - save(...args: Array): Promise; - _markAllFieldsDirty(): void; - /** - * Get the current Parse.Installation from disk. If doesn't exists, create an new installation. - * - *
      -   * const installation = await Parse.Installation.currentInstallation();
      -   * installation.set('deviceToken', '123');
      -   * await installation.save();
      -   * 
      - * - * @returns {Promise} A promise that resolves to the local installation object. - */ - static currentInstallation(): Promise; +declare class ParseInstallation extends ParseObject { + /** + * @param {object} attributes The initial set of data to store in the object. + */ + constructor(attributes?: T); + /** + * A unique identifier for this installation’s client application. In iOS, this is the Bundle Identifier. + * + * @property {string} appIdentifier + * @static + * @returns {string} + */ + get appIdentifier(): T[Extract]; + /** + * The version string of the client application to which this installation belongs. + * + * @property {string} appVersion + * @static + * @returns {string} + */ + get appVersion(): T[Extract]; + /** + * The display name of the client application to which this installation belongs. + * + * @property {string} appName + * @static + * @returns {string} + */ + get appName(): T[Extract]; + /** + * The current value of the icon badge for iOS apps. + * Changes to this value on the server will be used + * for future badge-increment push notifications. + * + * @property {number} badge + * @static + * @returns {number} + */ + get badge(): T[Extract]; + /** + * An array of the channels to which a device is currently subscribed. + * + * @property {string[]} channels + * @static + * @returns {string[]} + */ + get channels(): T[Extract]; + /** + * Token used to deliver push notifications to the device. + * + * @property {string} deviceToken + * @static + * @returns {string} + */ + get deviceToken(): T[Extract]; + /** + * The type of device, “ios”, “android”, “web”, etc. + * + * @property {string} deviceType + * @static + * @returns {string} + */ + get deviceType(): T[Extract]; + /** + * Gets the GCM sender identifier for this installation + * + * @property {string} GCMSenderId + * @static + * @returns {string} + */ + get GCMSenderId(): T[Extract]; + /** + * Universally Unique Identifier (UUID) for the device used by Parse. It must be unique across all of an app’s installations. + * + * @property {string} installationId + * @static + * @returns {string} + */ + get installationId(): T[Extract]; + /** + * Gets the local identifier for this installation + * + * @property {string} localeIdentifier + * @static + * @returns {string} + */ + get localeIdentifier(): T[Extract]; + /** + * Gets the parse server version for this installation + * + * @property {string} parseVersion + * @static + * @returns {string} + */ + get parseVersion(): T[Extract]; + /** + * This field is reserved for directing Parse to the push delivery network to be used. + * + * @property {string} pushType + * @static + * @returns {string} + */ + get pushType(): T[Extract]; + /** + * Gets the time zone for this installation + * + * @property {string} timeZone + * @static + * @returns {string} + */ + get timeZone(): T[Extract]; + /** + * Returns the device types for used for Push Notifications. + * + *
      +     * Parse.Installation.DEVICE_TYPES.IOS
      +     * Parse.Installation.DEVICE_TYPES.MACOS
      +     * Parse.Installation.DEVICE_TYPES.TVOS
      +     * Parse.Installation.DEVICE_TYPES.FCM
      +     * Parse.Installation.DEVICE_TYPES.ANDROID
      +     * Parse.Installation.DEVICE_TYPES.WEB
      +     * 
      ): Promise; + /** + * Wrap the default save behavior with functionality to update the local storage. + * If the installation is deleted on the server, retry saving a new installation. + * + * @param {...any} args + * @returns {Promise} + */ + save(...args: Array): Promise; + _markAllFieldsDirty(): void; + /** + * Get the current Parse.Installation from disk. If doesn't exists, create an new installation. + * + *
      +     * const installation = await Parse.Installation.currentInstallation();
      +     * installation.set('deviceToken', '123');
      +     * await installation.save();
      +     * 
      + * + * @returns {Promise} A promise that resolves to the local installation object. + */ + static currentInstallation(): Promise; } export default ParseInstallation; diff --git a/types/ParseLiveQuery.d.ts b/types/ParseLiveQuery.d.ts index ac9aa3495..fc678cbf1 100644 --- a/types/ParseLiveQuery.d.ts +++ b/types/ParseLiveQuery.d.ts @@ -1,3 +1,4 @@ +import type { EventEmitter } from 'events'; /** * We expose three events to help you monitor the status of the WebSocket connection: * @@ -26,22 +27,22 @@ * @static */ declare class LiveQuery { - emitter: any; - on: any; - emit: any; - constructor(); - /** - * After open is called, the LiveQuery will try to send a connect request - * to the LiveQuery server. - */ - open(): Promise; - /** - * When you're done using LiveQuery, you can call Parse.LiveQuery.close(). - * This function will close the WebSocket connection to the LiveQuery server, - * cancel the auto reconnect, and unsubscribe all subscriptions based on it. - * If you call query.subscribe() after this, we'll create a new WebSocket - * connection to the LiveQuery server. - */ - close(): Promise; + emitter: EventEmitter; + on: EventEmitter['on']; + emit: EventEmitter['emit']; + constructor(); + /** + * After open is called, the LiveQuery will try to send a connect request + * to the LiveQuery server. + */ + open(): Promise; + /** + * When you're done using LiveQuery, you can call Parse.LiveQuery.close(). + * This function will close the WebSocket connection to the LiveQuery server, + * cancel the auto reconnect, and unsubscribe all subscriptions based on it. + * If you call query.subscribe() after this, we'll create a new WebSocket + * connection to the LiveQuery server. + */ + close(): Promise; } export default LiveQuery; diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts index 7b49bfce2..a81cdbd2f 100644 --- a/types/ParseObject.d.ts +++ b/types/ParseObject.d.ts @@ -5,28 +5,56 @@ import { Op } from './ParseOp'; import ParseRelation from './ParseRelation'; import type { AttributeMap, OpsMap } from './ObjectStateMutations'; import type { RequestOptions, FullOptions } from './RESTController'; +import type ParseGeoPoint from './ParseGeoPoint'; +import type ParsePolygon from './ParsePolygon'; export type Pointer = { - __type: string; - className: string; - objectId?: string; - _localId?: string; + __type: string; + className: string; + objectId?: string; + _localId?: string; }; type SaveParams = { - method: string; - path: string; - body: AttributeMap; + method: string; + path: string; + body: AttributeMap; }; export type SaveOptions = FullOptions & { - cascadeSave?: boolean; - context?: AttributeMap; - batchSize?: number; - transaction?: boolean; + cascadeSave?: boolean; + context?: AttributeMap; + batchSize?: number; + transaction?: boolean; }; type FetchOptions = { - useMasterKey?: boolean; - sessionToken?: string; - include?: string | string[]; - context?: AttributeMap; + useMasterKey?: boolean; + sessionToken?: string; + include?: string | string[]; + context?: AttributeMap; +}; +export type SetOptions = { + ignoreValidation?: boolean; + unset?: boolean; +}; +export type AttributeKey = Extract; +export interface Attributes { + [key: string]: any; +} +interface JSONBaseAttributes { + objectId: string; + createdAt: string; + updatedAt: string; +} +interface CommonAttributes { + ACL: ParseACL; +} +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 ? { + __type: 'Date'; + iso: string; +} : T extends RegExp ? string : T extends Array ? Array> : T extends object ? ToJSON : T; +type ToJSON = { + [K in keyof T]: Encode; }; /** * Creates a new model with defined attributes. @@ -46,1051 +74,999 @@ type FetchOptions = { * * @alias Parse.Object */ -declare class ParseObject { - /** - * @param {string} className The class name for the object - * @param {object} attributes The initial set of data to store in the object. - * @param {object} options The options for this object instance. - * @param {boolean} [options.ignoreValidation] Set to `true` ignore any attribute validation errors. - */ - constructor( - className?: - | string - | { - className: string; - [attr: string]: any; - }, - attributes?: { - [attr: string]: any; - }, - options?: { - ignoreValidation: boolean; - } - ); - /** - * The ID of this object, unique within its class. - * - * @property {string} id - */ - id?: string; - _localId?: string; - _objCount: number; - className: string; - get attributes(): AttributeMap; - /** - * The first time this object was saved on the server. - * - * @property {Date} createdAt - * @returns {Date} - */ - get createdAt(): Date | undefined; - /** - * The last time this object was updated on the server. - * - * @property {Date} updatedAt - * @returns {Date} - */ - get updatedAt(): Date | undefined; - /** - * Returns a local or server Id used uniquely identify this object - * - * @returns {string} - */ - _getId(): string; - /** - * Returns a unique identifier used to pull data from the State Controller. - * - * @returns {Parse.Object|object} - */ - _getStateIdentifier(): - | ParseObject - | { +declare class ParseObject { + /** + * @param {string} className The class name for the object + * @param {object} attributes The initial set of data to store in the object. + * @param {object} options The options for this object instance. + * @param {boolean} [options.ignoreValidation] Set to `true` ignore any attribute validation errors. + */ + constructor(className?: string | { + className: string; + [attr: string]: any; + }, attributes?: T, options?: SetOptions); + /** + * The ID of this object, unique within its class. + * + * @property {string} id + */ + id?: string; + _localId?: string; + _objCount: number; + className: string; + get attributes(): T; + /** + * The first time this object was saved on the server. + * + * @property {Date} createdAt + * @returns {Date} + */ + get createdAt(): Date | undefined; + /** + * The last time this object was updated on the server. + * + * @property {Date} updatedAt + * @returns {Date} + */ + get updatedAt(): Date | undefined; + /** + * Returns a local or server Id used uniquely identify this object + * + * @returns {string} + */ + _getId(): string; + /** + * Returns a unique identifier used to pull data from the State Controller. + * + * @returns {Parse.Object|object} + */ + _getStateIdentifier(): ParseObject | { id: string; className: string; - }; - _getServerData(): AttributeMap; - _clearServerData(): void; - _getPendingOps(): Array; - /** - * @param {Array} [keysToClear] - if specified, only ops matching - * these fields will be cleared - */ - _clearPendingOps(keysToClear?: Array): void; - _getDirtyObjectAttributes(): AttributeMap; - _toFullJSON(seen?: Array, offline?: boolean): AttributeMap; - _getSaveJSON(): AttributeMap; - _getSaveParams(): SaveParams; - _finishFetch(serverData: AttributeMap): void; - _setExisted(existed: boolean): void; - _migrateId(serverId: string): void; - _handleSaveResponse(response: AttributeMap, status: number): void; - _handleSaveError(): void; - static _getClassMap(): AttributeMap; - static _getRequestOptions( - options?: RequestOptions & - FullOptions & { + }; + _getServerData(): Attributes; + _clearServerData(): void; + _getPendingOps(): Array; + /** + * @param {Array} [keysToClear] - if specified, only ops matching + * these fields will be cleared + */ + _clearPendingOps(keysToClear?: Array): void; + _getDirtyObjectAttributes(): Attributes; + _toFullJSON(seen?: Array, offline?: boolean): Attributes; + _getSaveJSON(): Attributes; + _getSaveParams(): SaveParams; + _finishFetch(serverData: Attributes): void; + _setExisted(existed: boolean): void; + _migrateId(serverId: string): void; + _handleSaveResponse(response: Attributes, status: number): void; + _handleSaveError(): void; + static _getClassMap(): AttributeMap; + static _getRequestOptions(options?: RequestOptions & FullOptions & { + json?: boolean; + }): RequestOptions & FullOptions & { json?: boolean; - } - ): RequestOptions & - FullOptions & { - json?: boolean; }; - initialize(): void; - /** - * Returns a JSON version of the object suitable for saving to Parse. - * - * @param seen - * @param offline - * @returns {object} - */ - toJSON(seen: Array | void, offline?: boolean): AttributeMap; - /** - * Determines whether this ParseObject is equal to another ParseObject - * - * @param {object} other - An other object ot compare - * @returns {boolean} - */ - equals(other: any): boolean; - /** - * Returns true if this object has been modified since its last - * save/refresh. If an attribute is specified, it returns true only if that - * particular attribute has been modified since the last save/refresh. - * - * @param {string} attr An attribute name (optional). - * @returns {boolean} - */ - dirty(attr?: string): boolean; - /** - * Returns an array of keys that have been modified since last save/refresh - * - * @returns {string[]} - */ - dirtyKeys(): Array; - /** - * Returns true if the object has been fetched. - * - * @returns {boolean} - */ - isDataAvailable(): boolean; - /** - * Gets a Pointer referencing this Object. - * - * @returns {Pointer} - */ - toPointer(): Pointer; - /** - * Gets a Pointer referencing this Object. - * - * @returns {Pointer} - */ - toOfflinePointer(): Pointer; - /** - * Gets the value of an attribute. - * - * @param {string} attr The string name of an attribute. - * @returns {*} - */ - get(attr: string): any; - /** - * Gets a relation on the given class for the attribute. - * - * @param {string} attr The attribute to get the relation for. - * @returns {Parse.Relation} - */ - relation(attr: string): ParseRelation; - /** - * Gets the HTML-escaped value of an attribute. - * - * @param {string} attr The string name of an attribute. - * @returns {string} - */ - escape(attr: string): string; - /** - * Returns true if the attribute contains a value that is not - * null or undefined. - * - * @param {string} attr The string name of the attribute. - * @returns {boolean} - */ - has(attr: string): boolean; - /** - * Sets a hash of model attributes on the object. - * - *

      You can call it with an object containing keys and values, with one - * key and value, or dot notation. For example:

      -   *   gameTurn.set({
      -   *     player: player1,
      -   *     diceRoll: 2
      -   *   }, {
      -   *     error: function(gameTurnAgain, error) {
      -   *       // The set failed validation.
      -   *     }
      -   *   });
      -   *
      -   *   game.set("currentPlayer", player2, {
      -   *     error: function(gameTurnAgain, error) {
      -   *       // The set failed validation.
      -   *     }
      -   *   });
      -   *
      -   *   game.set("finished", true);

      - * - * game.set("player.score", 10);

      - * - * @param {(string|object)} key The key to set. - * @param {(string|object)} value The value to give it. - * @param {object} options A set of options for the set. - * The only supported option is error. - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - set(key: any, value?: any, options?: any): this; - /** - * Remove an attribute from the model. This is a noop if the attribute doesn't - * exist. - * - * @param {string} attr The string name of an attribute. - * @param options - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - unset( - attr: string, - options?: { - [opt: string]: any; - } - ): this; - /** - * Atomically increments the value of the given attribute the next time the - * object is saved. If no amount is specified, 1 is used by default. - * - * @param attr {String} The key. - * @param amount {Number} The amount to increment by (optional). - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - increment(attr: string, amount?: number): this; - /** - * Atomically decrements the value of the given attribute the next time the - * object is saved. If no amount is specified, 1 is used by default. - * - * @param attr {String} The key. - * @param amount {Number} The amount to decrement by (optional). - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - decrement(attr: string, amount?: number): this; - /** - * Atomically add an object to the end of the array associated with a given - * key. - * - * @param attr {String} The key. - * @param item {} The item to add. - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - add(attr: string, item: any): this; - /** - * Atomically add the objects to the end of the array associated with a given - * key. - * - * @param attr {String} The key. - * @param items {Object[]} The items to add. - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - addAll(attr: string, items: Array): this; - /** - * Atomically add an object to the array associated with a given key, only - * if it is not already present in the array. The position of the insert is - * not guaranteed. - * - * @param attr {String} The key. - * @param item {} The object to add. - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - addUnique(attr: string, item: any): this; - /** - * Atomically add the objects to the array associated with a given key, only - * if it is not already present in the array. The position of the insert is - * not guaranteed. - * - * @param attr {String} The key. - * @param items {Object[]} The objects to add. - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - addAllUnique(attr: string, items: Array): this; - /** - * Atomically remove all instances of an object from the array associated - * with a given key. - * - * @param attr {String} The key. - * @param item {} The object to remove. - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - remove(attr: string, item: any): this; - /** - * Atomically remove all instances of the objects from the array associated - * with a given key. - * - * @param attr {String} The key. - * @param items {Object[]} The object to remove. - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - removeAll(attr: string, items: Array): this; - /** - * Returns an instance of a subclass of Parse.Op describing what kind of - * modification has been performed on this field since the last time it was - * saved. For example, after calling object.increment("x"), calling - * object.op("x") would return an instance of Parse.Op.Increment. - * - * @param attr {String} The key. - * @returns {Parse.Op | undefined} The operation, or undefined if none. - */ - op(attr: string): Op | undefined; - /** - * Creates a new model with identical attributes to this one. - * - * @returns {Parse.Object} - */ - clone(): any; - /** - * Creates a new instance of this object. Not to be confused with clone() - * - * @returns {Parse.Object} - */ - newInstance(): any; - /** - * Returns true if this object has never been saved to Parse. - * - * @returns {boolean} - */ - isNew(): boolean; - /** - * Returns true if this object was created by the Parse server when the - * object might have already been there (e.g. in the case of a Facebook - * login) - * - * @returns {boolean} - */ - existed(): boolean; - /** - * Returns true if this object exists on the Server - * - * @param {object} options - * Valid options are:
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      - * @returns {Promise} A boolean promise that is fulfilled if object exists. - */ - exists(options?: RequestOptions): Promise; - /** - * Checks if the model is currently in a valid state. - * - * @returns {boolean} - */ - isValid(): boolean; - /** - * You should not call this function directly unless you subclass - * Parse.Object, in which case you can override this method - * to provide additional validation on set and - * save. Your implementation should return - * - * @param {object} attrs The current data to validate. - * @returns {Parse.Error|boolean} False if the data is valid. An error object otherwise. - * @see Parse.Object#set - */ - validate(attrs: AttributeMap): ParseError | boolean; - /** - * Returns the ACL for this object. - * - * @returns {Parse.ACL|null} An instance of Parse.ACL. - * @see Parse.Object#get - */ - getACL(): ParseACL | null; - /** - * Sets the ACL to be used for this object. - * - * @param {Parse.ACL} acl An instance of Parse.ACL. - * @param {object} options - * @returns {Parse.Object} Returns the object, so you can chain this call. - * @see Parse.Object#set - */ - setACL(acl: ParseACL, options?: any): this; - /** - * Clears any (or specific) changes to this object made since the last call to save() - * - * @param {string} [keys] - specify which fields to revert - */ - revert(...keys: Array): void; - /** - * Clears all attributes on a model - * - * @returns {Parse.Object} Returns the object, so you can chain this call. - */ - clear(): this; - /** - * Fetch the model from the server. If the server's representation of the - * model differs from its current attributes, they will be overriden. - * - * @param {object} options - * Valid options are:
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      • include: The name(s) of the key(s) to include. Can be a string, an array of strings, - * or an array of array of strings. - *
      • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. - *
      - * @returns {Promise} A promise that is fulfilled when the fetch - * completes. - */ - fetch(options: FetchOptions): Promise; - /** - * Fetch the model from the server. If the server's representation of the - * model differs from its current attributes, they will be overriden. - * - * Includes nested Parse.Objects for the provided key. You can use dot - * notation to specify which fields in the included object are also fetched. - * - * @param {string | Array>} keys The name(s) of the key(s) to include. - * @param {object} options - * Valid options are:
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      - * @returns {Promise} A promise that is fulfilled when the fetch - * completes. - */ - fetchWithInclude( - keys: string | Array>, - options: RequestOptions - ): Promise; - /** - * Saves this object to the server at some unspecified time in the future, - * even if Parse is currently inaccessible. - * - * Use this when you may not have a solid network connection, and don't need to know when the save completes. - * If there is some problem with the object such that it can't be saved, it will be silently discarded. - * - * Objects saved with this method will be stored locally in an on-disk cache until they can be delivered to Parse. - * They will be sent immediately if possible. Otherwise, they will be sent the next time a network connection is - * available. Objects saved this way will persist even after the app is closed, in which case they will be sent the - * next time the app is opened. - * - * @param {object} [options] - * Used to pass option parameters to method if arg1 and arg2 were both passed as strings. - * Valid options are: - *
        - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      • cascadeSave: If `false`, nested objects will not be saved (default is `true`). - *
      • context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers. - *
      - * @returns {Promise} A promise that is fulfilled when the save - * completes. - */ - saveEventually(options: SaveOptions): Promise; - /** - * Set a hash of model attributes, and save the model to the server. - * updatedAt will be updated when the request returns. - * You can either call it as:
      -   * object.save();
      - * or
      -   * object.save(attrs);
      - * or
      -   * object.save(null, options);
      - * or
      -   * object.save(attrs, options);
      - * or
      -   * object.save(key, value);
      - * or
      -   * object.save(key, value, options);
      - * - * Example 1:
      -   * gameTurn.save({
      -   * player: "Jake Cutter",
      -   * diceRoll: 2
      -   * }).then(function(gameTurnAgain) {
      -   * // The save was successful.
      -   * }, function(error) {
      -   * // The save failed.  Error is an instance of Parse.Error.
      -   * });
      - * - * Example 2:
      -   * gameTurn.save("player", "Jake Cutter");
      - * - * @param {string | object | null} [arg1] - * Valid options are:
        - *
      • `Object` - Key/value pairs to update on the object.
      • - *
      • `String` Key - Key of attribute to update (requires arg2 to also be string)
      • - *
      • `null` - Passing null for arg1 allows you to save the object with options passed in arg2.
      • - *
      - * @param {string | object} [arg2] - *
        - *
      • `String` Value - If arg1 was passed as a key, arg2 is the value that should be set on that key.
      • - *
      • `Object` Options - Valid options are: - *
          - *
        • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
        • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
        • cascadeSave: If `false`, nested objects will not be saved (default is `true`). - *
        • context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers. - *
        - *
      • - *
      - * @param {object} [arg3] - * Used to pass option parameters to method if arg1 and arg2 were both passed as strings. - * Valid options are: - *
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      • cascadeSave: If `false`, nested objects will not be saved (default is `true`). - *
      • context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers. - *
      - * @returns {Promise} A promise that is fulfilled when the save - * completes. - */ - save( - arg1: - | undefined - | string - | { - [attr: string]: any; - } - | null, - arg2: SaveOptions | any, - arg3?: SaveOptions - ): Promise; - /** - * Deletes this object from the server at some unspecified time in the future, - * even if Parse is currently inaccessible. - * - * Use this when you may not have a solid network connection, - * and don't need to know when the delete completes. If there is some problem with the object - * such that it can't be deleted, the request will be silently discarded. - * - * Delete instructions made with this method will be stored locally in an on-disk cache until they can be transmitted - * to Parse. They will be sent immediately if possible. Otherwise, they will be sent the next time a network connection - * is available. Delete requests will persist even after the app is closed, in which case they will be sent the - * next time the app is opened. - * - * @param {object} [options] - * Valid options are:
        - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      • context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. - *
      - * @returns {Promise} A promise that is fulfilled when the destroy - * completes. - */ - destroyEventually(options: RequestOptions): Promise; - /** - * Destroy this model on the server if it was already persisted. - * - * @param {object} options - * Valid options are:
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      • context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. - *
      - * @returns {Promise} A promise that is fulfilled when the destroy - * completes. - */ - destroy(options: RequestOptions): Promise; - /** - * Asynchronously stores the object and every object it points to in the local datastore, - * recursively, using a default pin name: _default. - * - * If those other objects have not been fetched from Parse, they will not be stored. - * However, if they have changed data, all the changes will be retained. - * - *
      -   * await object.pin();
      -   * 
      - * - * To retrieve object: - * query.fromLocalDatastore() or query.fromPin() - * - * @returns {Promise} A promise that is fulfilled when the pin completes. - */ - pin(): Promise; - /** - * Asynchronously removes the object and every object it points to in the local datastore, - * recursively, using a default pin name: _default. - * - *
      -   * await object.unPin();
      -   * 
      - * - * @returns {Promise} A promise that is fulfilled when the unPin completes. - */ - unPin(): Promise; - /** - * Asynchronously returns if the object is pinned - * - *
      -   * const isPinned = await object.isPinned();
      -   * 
      - * - * @returns {Promise} A boolean promise that is fulfilled if object is pinned. - */ - isPinned(): Promise; - /** - * Asynchronously stores the objects and every object they point to in the local datastore, recursively. - * - * If those other objects have not been fetched from Parse, they will not be stored. - * However, if they have changed data, all the changes will be retained. - * - *
      -   * await object.pinWithName(name);
      -   * 
      - * - * To retrieve object: - * query.fromLocalDatastore() or query.fromPinWithName(name) - * - * @param {string} name Name of Pin. - * @returns {Promise} A promise that is fulfilled when the pin completes. - */ - pinWithName(name: string): Promise; - /** - * Asynchronously removes the object and every object it points to in the local datastore, recursively. - * - *
      -   * await object.unPinWithName(name);
      -   * 
      - * - * @param {string} name Name of Pin. - * @returns {Promise} A promise that is fulfilled when the unPin completes. - */ - unPinWithName(name: string): Promise; - /** - * Asynchronously loads data from the local datastore into this object. - * - *
      -   * await object.fetchFromLocalDatastore();
      -   * 
      - * - * You can create an unfetched pointer with Parse.Object.createWithoutData() - * and then call fetchFromLocalDatastore() on it. - * - * @returns {Promise} A promise that is fulfilled when the fetch completes. - */ - fetchFromLocalDatastore(): Promise; - static _clearAllState(): void; - /** - * Fetches the given list of Parse.Object. - * If any error is encountered, stops and calls the error handler. - * - *
      -   *   Parse.Object.fetchAll([object1, object2, ...])
      -   *    .then((list) => {
      -   *      // All the objects were fetched.
      -   *    }, (error) => {
      -   *      // An error occurred while fetching one of the objects.
      -   *    });
      -   * 
      - * - * @param {Array} list A list of Parse.Object. - * @param {object} options - * Valid options are:
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      • include: The name(s) of the key(s) to include. Can be a string, an array of strings, - * or an array of array of strings. - *
      - * @static - * @returns {Parse.Object[]} - */ - static fetchAll( - list: Array, - options?: RequestOptions - ): Promise; - /** - * Fetches the given list of Parse.Object. - * - * Includes nested Parse.Objects for the provided key. You can use dot - * notation to specify which fields in the included object are also fetched. - * - * If any error is encountered, stops and calls the error handler. - * - *
      -   *   Parse.Object.fetchAllWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
      -   *    .then((list) => {
      -   *      // All the objects were fetched.
      -   *    }, (error) => {
      -   *      // An error occurred while fetching one of the objects.
      -   *    });
      -   * 
      - * - * @param {Array} list A list of Parse.Object. - * @param {string | Array>} keys The name(s) of the key(s) to include. - * @param {object} options - * Valid options are:
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      - * @static - * @returns {Parse.Object[]} - */ - static fetchAllWithInclude( - list: Array, - keys: string | Array>, - options: RequestOptions - ): Promise; - /** - * Fetches the given list of Parse.Object if needed. - * If any error is encountered, stops and calls the error handler. - * - * Includes nested Parse.Objects for the provided key. You can use dot - * notation to specify which fields in the included object are also fetched. - * - * If any error is encountered, stops and calls the error handler. - * - *
      -   *   Parse.Object.fetchAllIfNeededWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
      -   *    .then((list) => {
      -   *      // All the objects were fetched.
      -   *    }, (error) => {
      -   *      // An error occurred while fetching one of the objects.
      -   *    });
      -   * 
      - * - * @param {Array} list A list of Parse.Object. - * @param {string | Array>} keys The name(s) of the key(s) to include. - * @param {object} options - * Valid options are:
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      - * @static - * @returns {Parse.Object[]} - */ - static fetchAllIfNeededWithInclude( - list: Array, - keys: string | Array>, - options: RequestOptions - ): Promise; - /** - * Fetches the given list of Parse.Object if needed. - * If any error is encountered, stops and calls the error handler. - * - *
      -   *   Parse.Object.fetchAllIfNeeded([object1, ...])
      -   *    .then((list) => {
      -   *      // Objects were fetched and updated.
      -   *    }, (error) => {
      -   *      // An error occurred while fetching one of the objects.
      -   *    });
      -   * 
      - * - * @param {Array} list A list of Parse.Object. - * @param {object} options - * Valid options are:
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      • include: The name(s) of the key(s) to include. Can be a string, an array of strings, - * or an array of array of strings. - *
      • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. - *
      - * @static - * @returns {Parse.Object[]} - */ - static fetchAllIfNeeded( - list: Array, - options: FetchOptions - ): Promise; - static handleIncludeOptions(options: { include?: string | string[] }): any[]; - /** - * Destroy the given list of models on the server if it was already persisted. - * - *

      Unlike saveAll, if an error occurs while deleting an individual model, - * this method will continue trying to delete the rest of the models if - * possible, except in the case of a fatal error like a connection error. - * - *

      In particular, the Parse.Error object returned in the case of error may - * be one of two types: - * - *

        - *
      • A Parse.Error.AGGREGATE_ERROR. This object's "errors" property is an - * array of other Parse.Error objects. Each error object in this array - * has an "object" property that references the object that could not be - * deleted (for instance, because that object could not be found).
      • - *
      • A non-aggregate Parse.Error. This indicates a serious error that - * caused the delete operation to be aborted partway through (for - * instance, a connection failure in the middle of the delete).
      • - *
      - * - *
      -   * Parse.Object.destroyAll([object1, object2, ...])
      -   * .then((list) => {
      -   * // All the objects were deleted.
      -   * }, (error) => {
      -   * // An error occurred while deleting one or more of the objects.
      -   * // If this is an aggregate error, then we can inspect each error
      -   * // object individually to determine the reason why a particular
      -   * // object was not deleted.
      -   * if (error.code === Parse.Error.AGGREGATE_ERROR) {
      -   * for (var i = 0; i < error.errors.length; i++) {
      -   * console.log("Couldn't delete " + error.errors[i].object.id +
      -   * "due to " + error.errors[i].message);
      -   * }
      -   * } else {
      -   * console.log("Delete aborted because of " + error.message);
      -   * }
      -   * });
      -   * 
      - * - * @param {Array} list A list of Parse.Object. - * @param {object} options - * Valid options are:
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      • context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. - *
      • transaction: Set to true to enable transactions - *
      • batchSize: How many objects to yield in each batch (default: 20) - *
      - * @static - * @returns {Promise} A promise that is fulfilled when the destroyAll - * completes. - */ - static destroyAll( - list: Array, - options?: SaveOptions - ): Promise; - /** - * Saves the given list of Parse.Object. - * If any error is encountered, stops and calls the error handler. - * - *
      -   * Parse.Object.saveAll([object1, object2, ...])
      -   * .then((list) => {
      -   * // All the objects were saved.
      -   * }, (error) => {
      -   * // An error occurred while saving one of the objects.
      -   * });
      -   * 
      - * - * @param {Array} list A list of Parse.Object. - * @param {object} options - * Valid options are: - *
        - *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
      • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
      • cascadeSave: If `false`, nested objects will not be saved (default is `true`). - *
      • context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers. - *
      • transaction: Set to true to enable transactions - *
      • batchSize: How many objects to yield in each batch (default: 20) - *
      - * @static - * @returns {Parse.Object[]} - */ - static saveAll( - list: Array, - options?: SaveOptions - ): Promise; - /** - * Creates a reference to a subclass of Parse.Object with the given id. This - * does not exist on Parse.Object, only on subclasses. - * - *

      A shortcut for:

      -   *  var Foo = Parse.Object.extend("Foo");
      -   *  var pointerToFoo = new Foo();
      -   *  pointerToFoo.id = "myObjectId";
      -   * 
      - * - * @param {string} id The ID of the object to create a reference to. - * @static - * @returns {Parse.Object} A Parse.Object reference. - */ - static createWithoutData(id: string): ParseObject; - /** - * Creates a new instance of a Parse Object from a JSON representation. - * - * @param {object} json The JSON map of the Object's data - * @param {boolean} override In single instance mode, all old server data - * is overwritten if this is set to true - * @param {boolean} dirty Whether the Parse.Object should set JSON keys to dirty - * @static - * @returns {Parse.Object} A Parse.Object reference - */ - static fromJSON(json: any, override?: boolean, dirty?: boolean): ParseObject; - /** - * Registers a subclass of Parse.Object with a specific class name. - * When objects of that class are retrieved from a query, they will be - * instantiated with this subclass. - * This is only necessary when using ES6 subclassing. - * - * @param {string} className The class name of the subclass - * @param {Function} constructor The subclass - */ - static registerSubclass(className: string, constructor: any): void; - /** - * Unegisters a subclass of Parse.Object with a specific class name. - * - * @param {string} className The class name of the subclass - */ - static unregisterSubclass(className: string): void; - /** - * Creates a new subclass of Parse.Object for the given Parse class name. - * - *

      Every extension of a Parse class will inherit from the most recent - * previous extension of that class. When a Parse.Object is automatically - * created by parsing JSON, it will use the most recent extension of that - * class.

      - * - *

      You should call either:

      -   *     var MyClass = Parse.Object.extend("MyClass", {
      -   *         Instance methods,
      -   *         initialize: function(attrs, options) {
      -   *             this.someInstanceProperty = [],
      -   *             Other instance properties
      -   *         }
      -   *     }, {
      -   *         Class properties
      -   *     });
      - * or, for Backbone compatibility:
      -   *     var MyClass = Parse.Object.extend({
      -   *         className: "MyClass",
      -   *         Instance methods,
      -   *         initialize: function(attrs, options) {
      -   *             this.someInstanceProperty = [],
      -   *             Other instance properties
      -   *         }
      -   *     }, {
      -   *         Class properties
      -   *     });

      - * - * @param {string} className The name of the Parse class backing this model. - * @param {object} [protoProps] Instance properties to add to instances of the - * class returned from this method. - * @param {object} [classProps] Class properties to add the class returned from - * this method. - * @returns {Parse.Object} A new subclass of Parse.Object. - */ - static extend(className: any, protoProps?: any, classProps?: any): any; - /** - * Enable single instance objects, where any local objects with the same Id - * share the same attributes, and stay synchronized with each other. - * This is disabled by default in server environments, since it can lead to - * security issues. - * - * @static - */ - static enableSingleInstance(): void; - /** - * Disable single instance objects, where any local objects with the same Id - * share the same attributes, and stay synchronized with each other. - * When disabled, you can have two instances of the same object in memory - * without them sharing attributes. - * - * @static - */ - static disableSingleInstance(): void; - /** - * Asynchronously stores the objects and every object they point to in the local datastore, - * recursively, using a default pin name: _default. - * - * If those other objects have not been fetched from Parse, they will not be stored. - * However, if they have changed data, all the changes will be retained. - * - *
      -   * await Parse.Object.pinAll([...]);
      -   * 
      - * - * To retrieve object: - * query.fromLocalDatastore() or query.fromPin() - * - * @param {Array} objects A list of Parse.Object. - * @returns {Promise} A promise that is fulfilled when the pin completes. - * @static - */ - static pinAll(objects: Array): Promise; - /** - * Asynchronously stores the objects and every object they point to in the local datastore, recursively. - * - * If those other objects have not been fetched from Parse, they will not be stored. - * However, if they have changed data, all the changes will be retained. - * - *
      -   * await Parse.Object.pinAllWithName(name, [obj1, obj2, ...]);
      -   * 
      - * - * To retrieve object: - * query.fromLocalDatastore() or query.fromPinWithName(name) - * - * @param {string} name Name of Pin. - * @param {Array} objects A list of Parse.Object. - * @returns {Promise} A promise that is fulfilled when the pin completes. - * @static - */ - static pinAllWithName(name: string, objects: Array): Promise; - /** - * Asynchronously removes the objects and every object they point to in the local datastore, - * recursively, using a default pin name: _default. - * - *
      -   * await Parse.Object.unPinAll([...]);
      -   * 
      - * - * @param {Array} objects A list of Parse.Object. - * @returns {Promise} A promise that is fulfilled when the unPin completes. - * @static - */ - static unPinAll(objects: Array): Promise; - /** - * Asynchronously removes the objects and every object they point to in the local datastore, recursively. - * - *
      -   * await Parse.Object.unPinAllWithName(name, [obj1, obj2, ...]);
      -   * 
      - * - * @param {string} name Name of Pin. - * @param {Array} objects A list of Parse.Object. - * @returns {Promise} A promise that is fulfilled when the unPin completes. - * @static - */ - static unPinAllWithName(name: string, objects: Array): Promise; - /** - * Asynchronously removes all objects in the local datastore using a default pin name: _default. - * - *
      -   * await Parse.Object.unPinAllObjects();
      -   * 
      - * - * @returns {Promise} A promise that is fulfilled when the unPin completes. - * @static - */ - static unPinAllObjects(): Promise; - /** - * Asynchronously removes all objects with the specified pin name. - * Deletes the pin name also. - * - *
      -   * await Parse.Object.unPinAllObjectsWithName(name);
      -   * 
      - * - * @param {string} name Name of Pin. - * @returns {Promise} A promise that is fulfilled when the unPin completes. - * @static - */ - static unPinAllObjectsWithName(name: string): Promise; + initialize(): void; + /** + * Returns a JSON version of the object suitable for saving to Parse. + * + * @param seen + * @param offline + * @returns {object} + */ + toJSON(seen: Array | void, offline?: boolean): ToJSON & JSONBaseAttributes; + /** + * Determines whether this ParseObject is equal to another ParseObject + * + * @param {object} other - An other object ot compare + * @returns {boolean} + */ + equals(other: T): boolean; + /** + * Returns true if this object has been modified since its last + * save/refresh. If an attribute is specified, it returns true only if that + * particular attribute has been modified since the last save/refresh. + * + * @param {string} attr An attribute name (optional). + * @returns {boolean} + */ + dirty>(attr?: K): boolean; + /** + * Returns an array of keys that have been modified since last save/refresh + * + * @returns {string[]} + */ + dirtyKeys(): string[]; + /** + * Returns true if the object has been fetched. + * + * @returns {boolean} + */ + isDataAvailable(): boolean; + /** + * Gets a Pointer referencing this Object. + * + * @returns {Pointer} + */ + toPointer(): Pointer; + /** + * Gets a Pointer referencing this Object. + * + * @returns {Pointer} + */ + toOfflinePointer(): Pointer; + /** + * Gets the value of an attribute. + * + * @param {string} attr The string name of an attribute. + * @returns {*} + */ + get>(attr: K): T[K]; + /** + * Gets a relation on the given class for the attribute. + * + * @param {string} attr The attribute to get the relation for. + * @returns {Parse.Relation} + */ + relation = AttributeKey>(attr: T[K] extends ParseRelation ? K : never): ParseRelation; + /** + * Gets the HTML-escaped value of an attribute. + * + * @param {string} attr The string name of an attribute. + * @returns {string} + */ + escape>(attr: K): string; + /** + * Returns true if the attribute contains a value that is not + * null or undefined. + * + * @param {string} attr The string name of the attribute. + * @returns {boolean} + */ + has>(attr: K): boolean; + /** + * Sets a hash of model attributes on the object. + * + *

      You can call it with an object containing keys and values, with one + * key and value, or dot notation. For example:

      +     *   gameTurn.set({
      +     *     player: player1,
      +     *     diceRoll: 2
      +     *   }, {
      +     *     error: function(gameTurnAgain, error) {
      +     *       // The set failed validation.
      +     *     }
      +     *   });
      +     *
      +     *   game.set("currentPlayer", player2, {
      +     *     error: function(gameTurnAgain, error) {
      +     *       // The set failed validation.
      +     *     }
      +     *   });
      +     *
      +     *   game.set("finished", true);

      + * + * game.set("player.score", 10);

    + * + * @param {(string|object)} key The key to set. + * @param {(string|object)} value The value to give it. + * @param {object} options A set of options for the set. + * The only supported option is error. + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + set>(key: K | (Pick | T), value?: SetOptions | (T[K] extends undefined ? never : T[K]), options?: SetOptions): this; + /** + * Remove an attribute from the model. This is a noop if the attribute doesn't + * exist. + * + * @param {string} attr The string name of an attribute. + * @param options + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + unset>(attr: K, options?: SetOptions): this; + /** + * Atomically increments the value of the given attribute the next time the + * object is saved. If no amount is specified, 1 is used by default. + * + * @param attr {String} The key. + * @param amount {Number} The amount to increment by (optional). + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + increment>(attr: K, amount?: number): this; + /** + * Atomically decrements the value of the given attribute the next time the + * object is saved. If no amount is specified, 1 is used by default. + * + * @param attr {String} The key. + * @param amount {Number} The amount to decrement by (optional). + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + decrement>(attr: K, amount?: number): this; + /** + * Atomically add an object to the end of the array associated with a given + * key. + * + * @param attr {String} The key. + * @param item {} The item to add. + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + add[keyof T]>(attr: K, item: NonNullable[number]): this; + /** + * Atomically add the objects to the end of the array associated with a given + * key. + * + * @param attr {String} The key. + * @param items {Object[]} The items to add. + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + addAll[keyof T]>(attr: K, items: NonNullable): this; + /** + * Atomically add an object to the array associated with a given key, only + * if it is not already present in the array. The position of the insert is + * not guaranteed. + * + * @param attr {String} The key. + * @param item {} The object to add. + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + addUnique[keyof T]>(attr: K, item: NonNullable[number]): this; + /** + * Atomically add the objects to the array associated with a given key, only + * if it is not already present in the array. The position of the insert is + * not guaranteed. + * + * @param attr {String} The key. + * @param items {Object[]} The objects to add. + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + addAllUnique[keyof T]>(attr: K, items: NonNullable): this; + /** + * Atomically remove all instances of an object from the array associated + * with a given key. + * + * @param attr {String} The key. + * @param item {} The object to remove. + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + remove[keyof T]>(attr: K, item: NonNullable[number]): this; + /** + * Atomically remove all instances of the objects from the array associated + * with a given key. + * + * @param attr {String} The key. + * @param items {Object[]} The object to remove. + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + removeAll[keyof T]>(attr: K, items: NonNullable): this; + /** + * Returns an instance of a subclass of Parse.Op describing what kind of + * modification has been performed on this field since the last time it was + * saved. For example, after calling object.increment("x"), calling + * object.op("x") would return an instance of Parse.Op.Increment. + * + * @param attr {String} The key. + * @returns {Parse.Op | undefined} The operation, or undefined if none. + */ + op>(attr: K): Op | undefined; + /** + * Creates a new model with identical attributes to this one. + * + * @returns {Parse.Object} + */ + clone(): any; + /** + * Creates a new instance of this object. Not to be confused with clone() + * + * @returns {Parse.Object} + */ + newInstance(): this; + /** + * Returns true if this object has never been saved to Parse. + * + * @returns {boolean} + */ + isNew(): boolean; + /** + * Returns true if this object was created by the Parse server when the + * object might have already been there (e.g. in the case of a Facebook + * login) + * + * @returns {boolean} + */ + existed(): boolean; + /** + * Returns true if this object exists on the Server + * + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    + * @returns {Promise} A boolean promise that is fulfilled if object exists. + */ + exists(options?: RequestOptions): Promise; + /** + * Checks if the model is currently in a valid state. + * + * @returns {boolean} + */ + isValid(): boolean; + /** + * You should not call this function directly unless you subclass + * Parse.Object, in which case you can override this method + * to provide additional validation on set and + * save. Your implementation should return + * + * @param {object} attrs The current data to validate. + * @returns {Parse.Error|boolean} False if the data is valid. An error object otherwise. + * @see Parse.Object#set + */ + validate(attrs: Attributes): ParseError | boolean; + /** + * Returns the ACL for this object. + * + * @returns {Parse.ACL|null} An instance of Parse.ACL. + * @see Parse.Object#get + */ + getACL(): ParseACL | null; + /** + * Sets the ACL to be used for this object. + * + * @param {Parse.ACL} acl An instance of Parse.ACL. + * @param {object} options + * @returns {Parse.Object} Returns the object, so you can chain this call. + * @see Parse.Object#set + */ + setACL(acl: ParseACL, options?: any): this; + /** + * Clears any (or specific) changes to this object made since the last call to save() + * + * @param {string} [keys] - specify which fields to revert + */ + revert(...keys: Array>): void; + /** + * Clears all attributes on a model + * + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + clear(): this; + /** + * Fetch the model from the server. If the server's representation of the + * model differs from its current attributes, they will be overriden. + * + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • include: The name(s) of the key(s) to include. Can be a string, an array of strings, + * or an array of array of strings. + *
    • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. + *
    + * @returns {Promise} A promise that is fulfilled when the fetch + * completes. + */ + fetch(options: FetchOptions): Promise; + /** + * Fetch the model from the server. If the server's representation of the + * model differs from its current attributes, they will be overriden. + * + * Includes nested Parse.Objects for the provided key. You can use dot + * notation to specify which fields in the included object are also fetched. + * + * @param {string | Array>} keys The name(s) of the key(s) to include. + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    + * @returns {Promise} A promise that is fulfilled when the fetch + * completes. + */ + fetchWithInclude(keys: string | Array>, options?: RequestOptions): Promise; + /** + * Saves this object to the server at some unspecified time in the future, + * even if Parse is currently inaccessible. + * + * Use this when you may not have a solid network connection, and don't need to know when the save completes. + * If there is some problem with the object such that it can't be saved, it will be silently discarded. + * + * Objects saved with this method will be stored locally in an on-disk cache until they can be delivered to Parse. + * They will be sent immediately if possible. Otherwise, they will be sent the next time a network connection is + * available. Objects saved this way will persist even after the app is closed, in which case they will be sent the + * next time the app is opened. + * + * @param {object} [options] + * Used to pass option parameters to method if arg1 and arg2 were both passed as strings. + * Valid options are: + *
      + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • cascadeSave: If `false`, nested objects will not be saved (default is `true`). + *
    • context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers. + *
    + * @returns {Promise} A promise that is fulfilled when the save + * completes. + */ + saveEventually(options?: SaveOptions): Promise; + /** + * Set a hash of model attributes, and save the model to the server. + * updatedAt will be updated when the request returns. + * You can either call it as:
    +     * object.save();
    + * or
    +     * object.save(attrs);
    + * or
    +     * object.save(null, options);
    + * or
    +     * object.save(attrs, options);
    + * or
    +     * object.save(key, value);
    + * or
    +     * object.save(key, value, options);
    + * + * Example 1:
    +     * gameTurn.save({
    +     * player: "Jake Cutter",
    +     * diceRoll: 2
    +     * }).then(function(gameTurnAgain) {
    +     * // The save was successful.
    +     * }, function(error) {
    +     * // The save failed.  Error is an instance of Parse.Error.
    +     * });
    + * + * Example 2:
    +     * gameTurn.save("player", "Jake Cutter");
    + * + * @param {string | object | null} [arg1] + * Valid options are:
      + *
    • `Object` - Key/value pairs to update on the object.
    • + *
    • `String` Key - Key of attribute to update (requires arg2 to also be string)
    • + *
    • `null` - Passing null for arg1 allows you to save the object with options passed in arg2.
    • + *
    + * @param {string | object} [arg2] + *
      + *
    • `String` Value - If arg1 was passed as a key, arg2 is the value that should be set on that key.
    • + *
    • `Object` Options - Valid options are: + *
        + *
      • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
      • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
      • cascadeSave: If `false`, nested objects will not be saved (default is `true`). + *
      • context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers. + *
      + *
    • + *
    + * @param {object} [arg3] + * Used to pass option parameters to method if arg1 and arg2 were both passed as strings. + * Valid options are: + *
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • cascadeSave: If `false`, nested objects will not be saved (default is `true`). + *
    • context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers. + *
    + * @returns {Promise} A promise that is fulfilled when the save + * completes. + */ + save>(arg1?: Pick | T | null, arg2?: SaveOptions): Promise; + /** + * Deletes this object from the server at some unspecified time in the future, + * even if Parse is currently inaccessible. + * + * Use this when you may not have a solid network connection, + * and don't need to know when the delete completes. If there is some problem with the object + * such that it can't be deleted, the request will be silently discarded. + * + * Delete instructions made with this method will be stored locally in an on-disk cache until they can be transmitted + * to Parse. They will be sent immediately if possible. Otherwise, they will be sent the next time a network connection + * is available. Delete requests will persist even after the app is closed, in which case they will be sent the + * next time the app is opened. + * + * @param {object} [options] + * Valid options are:
      + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. + *
    + * @returns {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroyEventually(options?: RequestOptions): Promise; + /** + * Destroy this model on the server if it was already persisted. + * + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. + *
    + * @returns {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy(options?: RequestOptions): Promise; + /** + * Asynchronously stores the object and every object it points to in the local datastore, + * recursively, using a default pin name: _default. + * + * If those other objects have not been fetched from Parse, they will not be stored. + * However, if they have changed data, all the changes will be retained. + * + *
    +     * await object.pin();
    +     * 
    + * + * To retrieve object: + * query.fromLocalDatastore() or query.fromPin() + * + * @returns {Promise} A promise that is fulfilled when the pin completes. + */ + pin(): Promise; + /** + * Asynchronously removes the object and every object it points to in the local datastore, + * recursively, using a default pin name: _default. + * + *
    +     * await object.unPin();
    +     * 
    + * + * @returns {Promise} A promise that is fulfilled when the unPin completes. + */ + unPin(): Promise; + /** + * Asynchronously returns if the object is pinned + * + *
    +     * const isPinned = await object.isPinned();
    +     * 
    + * + * @returns {Promise} A boolean promise that is fulfilled if object is pinned. + */ + isPinned(): Promise; + /** + * Asynchronously stores the objects and every object they point to in the local datastore, recursively. + * + * If those other objects have not been fetched from Parse, they will not be stored. + * However, if they have changed data, all the changes will be retained. + * + *
    +     * await object.pinWithName(name);
    +     * 
    + * + * To retrieve object: + * query.fromLocalDatastore() or query.fromPinWithName(name) + * + * @param {string} name Name of Pin. + * @returns {Promise} A promise that is fulfilled when the pin completes. + */ + pinWithName(name: string): Promise; + /** + * Asynchronously removes the object and every object it points to in the local datastore, recursively. + * + *
    +     * await object.unPinWithName(name);
    +     * 
    + * + * @param {string} name Name of Pin. + * @returns {Promise} A promise that is fulfilled when the unPin completes. + */ + unPinWithName(name: string): Promise; + /** + * Asynchronously loads data from the local datastore into this object. + * + *
    +     * await object.fetchFromLocalDatastore();
    +     * 
    + * + * You can create an unfetched pointer with Parse.Object.createWithoutData() + * and then call fetchFromLocalDatastore() on it. + * + * @returns {Promise} A promise that is fulfilled when the fetch completes. + */ + fetchFromLocalDatastore(): Promise; + static _clearAllState(): void; + /** + * Fetches the given list of Parse.Object. + * If any error is encountered, stops and calls the error handler. + * + *
    +     *   Parse.Object.fetchAll([object1, object2, ...])
    +     *    .then((list) => {
    +     *      // All the objects were fetched.
    +     *    }, (error) => {
    +     *      // An error occurred while fetching one of the objects.
    +     *    });
    +     * 
    + * + * @param {Array} list A list of Parse.Object. + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • include: The name(s) of the key(s) to include. Can be a string, an array of strings, + * or an array of array of strings. + *
    + * @static + * @returns {Parse.Object[]} + */ + static fetchAll(list: T[], options?: RequestOptions): Promise; + /** + * Fetches the given list of Parse.Object. + * + * Includes nested Parse.Objects for the provided key. You can use dot + * notation to specify which fields in the included object are also fetched. + * + * If any error is encountered, stops and calls the error handler. + * + *
    +     *   Parse.Object.fetchAllWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
    +     *    .then((list) => {
    +     *      // All the objects were fetched.
    +     *    }, (error) => {
    +     *      // An error occurred while fetching one of the objects.
    +     *    });
    +     * 
    + * + * @param {Array} list A list of Parse.Object. + * @param {string | Array>} keys The name(s) of the key(s) to include. + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    + * @static + * @returns {Parse.Object[]} + */ + static fetchAllWithInclude(list: T[], keys: keyof T['attributes'] | Array, options?: RequestOptions): Promise; + /** + * Fetches the given list of Parse.Object if needed. + * If any error is encountered, stops and calls the error handler. + * + * Includes nested Parse.Objects for the provided key. You can use dot + * notation to specify which fields in the included object are also fetched. + * + * If any error is encountered, stops and calls the error handler. + * + *
    +     *   Parse.Object.fetchAllIfNeededWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
    +     *    .then((list) => {
    +     *      // All the objects were fetched.
    +     *    }, (error) => {
    +     *      // An error occurred while fetching one of the objects.
    +     *    });
    +     * 
    + * + * @param {Array} list A list of Parse.Object. + * @param {string | Array>} keys The name(s) of the key(s) to include. + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    + * @static + * @returns {Parse.Object[]} + */ + static fetchAllIfNeededWithInclude(list: T[], keys: keyof T['attributes'] | Array, options?: RequestOptions): Promise; + /** + * Fetches the given list of Parse.Object if needed. + * If any error is encountered, stops and calls the error handler. + * + *
    +     *   Parse.Object.fetchAllIfNeeded([object1, ...])
    +     *    .then((list) => {
    +     *      // Objects were fetched and updated.
    +     *    }, (error) => {
    +     *      // An error occurred while fetching one of the objects.
    +     *    });
    +     * 
    + * + * @param {Array} list A list of Parse.Object. + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • include: The name(s) of the key(s) to include. Can be a string, an array of strings, + * or an array of array of strings. + *
    • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. + *
    + * @static + * @returns {Parse.Object[]} + */ + static fetchAllIfNeeded(list: T[], options?: FetchOptions): Promise; + static handleIncludeOptions(options: { + include?: string | string[]; + }): any[]; + /** + * Destroy the given list of models on the server if it was already persisted. + * + *

    Unlike saveAll, if an error occurs while deleting an individual model, + * this method will continue trying to delete the rest of the models if + * possible, except in the case of a fatal error like a connection error. + * + *

    In particular, the Parse.Error object returned in the case of error may + * be one of two types: + * + *

      + *
    • A Parse.Error.AGGREGATE_ERROR. This object's "errors" property is an + * array of other Parse.Error objects. Each error object in this array + * has an "object" property that references the object that could not be + * deleted (for instance, because that object could not be found).
    • + *
    • A non-aggregate Parse.Error. This indicates a serious error that + * caused the delete operation to be aborted partway through (for + * instance, a connection failure in the middle of the delete).
    • + *
    + * + *
    +     * Parse.Object.destroyAll([object1, object2, ...])
    +     * .then((list) => {
    +     * // All the objects were deleted.
    +     * }, (error) => {
    +     * // An error occurred while deleting one or more of the objects.
    +     * // If this is an aggregate error, then we can inspect each error
    +     * // object individually to determine the reason why a particular
    +     * // object was not deleted.
    +     * if (error.code === Parse.Error.AGGREGATE_ERROR) {
    +     * for (var i = 0; i < error.errors.length; i++) {
    +     * console.log("Couldn't delete " + error.errors[i].object.id +
    +     * "due to " + error.errors[i].message);
    +     * }
    +     * } else {
    +     * console.log("Delete aborted because of " + error.message);
    +     * }
    +     * });
    +     * 
    + * + * @param {Array} list A list of Parse.Object. + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers. + *
    • transaction: Set to true to enable transactions + *
    • batchSize: How many objects to yield in each batch (default: 20) + *
    + * @static + * @returns {Promise} A promise that is fulfilled when the destroyAll + * completes. + */ + static destroyAll(list: Array, options?: SaveOptions): Promise | ParseObject[]>; + /** + * Saves the given list of Parse.Object. + * If any error is encountered, stops and calls the error handler. + * + *
    +     * Parse.Object.saveAll([object1, object2, ...])
    +     * .then((list) => {
    +     * // All the objects were saved.
    +     * }, (error) => {
    +     * // An error occurred while saving one of the objects.
    +     * });
    +     * 
    + * + * @param {Array} list A list of Parse.Object. + * @param {object} options + * Valid options are: + *
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • cascadeSave: If `false`, nested objects will not be saved (default is `true`). + *
    • context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers. + *
    • transaction: Set to true to enable transactions + *
    • batchSize: How many objects to yield in each batch (default: 20) + *
    + * @static + * @returns {Parse.Object[]} + */ + static saveAll(list: T, options?: SaveOptions): Promise; + /** + * Creates a reference to a subclass of Parse.Object with the given id. This + * does not exist on Parse.Object, only on subclasses. + * + *

    A shortcut for:

    +     *  var Foo = Parse.Object.extend("Foo");
    +     *  var pointerToFoo = new Foo();
    +     *  pointerToFoo.id = "myObjectId";
    +     * 
    + * + * @param {string} id The ID of the object to create a reference to. + * @static + * @returns {Parse.Object} A Parse.Object reference. + */ + static createWithoutData(id: string): ParseObject; + /** + * Creates a new instance of a Parse Object from a JSON representation. + * + * @param {object} json The JSON map of the Object's data + * @param {boolean} override In single instance mode, all old server data + * is overwritten if this is set to true + * @param {boolean} dirty Whether the Parse.Object should set JSON keys to dirty + * @static + * @returns {Parse.Object} A Parse.Object reference + */ + static fromJSON(json: any, override?: boolean, dirty?: boolean): T; + /** + * Registers a subclass of Parse.Object with a specific class name. + * When objects of that class are retrieved from a query, they will be + * instantiated with this subclass. + * This is only necessary when using ES6 subclassing. + * + * @param {string} className The class name of the subclass + * @param {Function} constructor The subclass + */ + static registerSubclass(className: string, constructor: any): void; + /** + * Unegisters a subclass of Parse.Object with a specific class name. + * + * @param {string} className The class name of the subclass + */ + static unregisterSubclass(className: string): void; + /** + * Creates a new subclass of Parse.Object for the given Parse class name. + * + *

    Every extension of a Parse class will inherit from the most recent + * previous extension of that class. When a Parse.Object is automatically + * created by parsing JSON, it will use the most recent extension of that + * class.

    + * + *

    You should call either:

    +     *     var MyClass = Parse.Object.extend("MyClass", {
    +     *         Instance methods,
    +     *         initialize: function(attrs, options) {
    +     *             this.someInstanceProperty = [],
    +     *             Other instance properties
    +     *         }
    +     *     }, {
    +     *         Class properties
    +     *     });
    + * or, for Backbone compatibility:
    +     *     var MyClass = Parse.Object.extend({
    +     *         className: "MyClass",
    +     *         Instance methods,
    +     *         initialize: function(attrs, options) {
    +     *             this.someInstanceProperty = [],
    +     *             Other instance properties
    +     *         }
    +     *     }, {
    +     *         Class properties
    +     *     });

    + * + * @param {string} className The name of the Parse class backing this model. + * @param {object} [protoProps] Instance properties to add to instances of the + * class returned from this method. + * @param {object} [classProps] Class properties to add the class returned from + * this method. + * @returns {Parse.Object} A new subclass of Parse.Object. + */ + static extend(className: any, protoProps?: any, classProps?: any): any; + /** + * Enable single instance objects, where any local objects with the same Id + * share the same attributes, and stay synchronized with each other. + * This is disabled by default in server environments, since it can lead to + * security issues. + * + * @static + */ + static enableSingleInstance(): void; + /** + * Disable single instance objects, where any local objects with the same Id + * share the same attributes, and stay synchronized with each other. + * When disabled, you can have two instances of the same object in memory + * without them sharing attributes. + * + * @static + */ + static disableSingleInstance(): void; + /** + * Asynchronously stores the objects and every object they point to in the local datastore, + * recursively, using a default pin name: _default. + * + * If those other objects have not been fetched from Parse, they will not be stored. + * However, if they have changed data, all the changes will be retained. + * + *
    +     * await Parse.Object.pinAll([...]);
    +     * 
    + * + * To retrieve object: + * query.fromLocalDatastore() or query.fromPin() + * + * @param {Array} objects A list of Parse.Object. + * @returns {Promise} A promise that is fulfilled when the pin completes. + * @static + */ + static pinAll(objects: Array): Promise; + /** + * Asynchronously stores the objects and every object they point to in the local datastore, recursively. + * + * If those other objects have not been fetched from Parse, they will not be stored. + * However, if they have changed data, all the changes will be retained. + * + *
    +     * await Parse.Object.pinAllWithName(name, [obj1, obj2, ...]);
    +     * 
    + * + * To retrieve object: + * query.fromLocalDatastore() or query.fromPinWithName(name) + * + * @param {string} name Name of Pin. + * @param {Array} objects A list of Parse.Object. + * @returns {Promise} A promise that is fulfilled when the pin completes. + * @static + */ + static pinAllWithName(name: string, objects: Array): Promise; + /** + * Asynchronously removes the objects and every object they point to in the local datastore, + * recursively, using a default pin name: _default. + * + *
    +     * await Parse.Object.unPinAll([...]);
    +     * 
    + * + * @param {Array} objects A list of Parse.Object. + * @returns {Promise} A promise that is fulfilled when the unPin completes. + * @static + */ + static unPinAll(objects: Array): Promise; + /** + * Asynchronously removes the objects and every object they point to in the local datastore, recursively. + * + *
    +     * await Parse.Object.unPinAllWithName(name, [obj1, obj2, ...]);
    +     * 
    + * + * @param {string} name Name of Pin. + * @param {Array} objects A list of Parse.Object. + * @returns {Promise} A promise that is fulfilled when the unPin completes. + * @static + */ + static unPinAllWithName(name: string, objects: Array): Promise; + /** + * Asynchronously removes all objects in the local datastore using a default pin name: _default. + * + *
    +     * await Parse.Object.unPinAllObjects();
    +     * 
    + * + * @returns {Promise} A promise that is fulfilled when the unPin completes. + * @static + */ + static unPinAllObjects(): Promise; + /** + * Asynchronously removes all objects with the specified pin name. + * Deletes the pin name also. + * + *
    +     * await Parse.Object.unPinAllObjectsWithName(name);
    +     * 
    + * + * @param {string} name Name of Pin. + * @returns {Promise} A promise that is fulfilled when the unPin completes. + * @static + */ + static unPinAllObjectsWithName(name: string): Promise; } export default ParseObject; diff --git a/types/ParseOp.d.ts b/types/ParseOp.d.ts index a7ad4a411..1ffd8bbc8 100644 --- a/types/ParseOp.d.ts +++ b/types/ParseOp.d.ts @@ -1,76 +1,78 @@ import type ParseObject from './ParseObject'; import ParseRelation from './ParseRelation'; -export declare function opFromJSON(json: { [key: string]: any }): Op | null; +export declare function opFromJSON(json: { + [key: string]: any; +}): Op | null; export declare class Op { - applyTo(value: any): any; - mergeWith(previous: Op): Op | void; - toJSON(offline?: boolean): any; + applyTo(value: any): any; + mergeWith(previous: Op): Op | void; + toJSON(offline?: boolean): any; } export declare class SetOp extends Op { - _value: any; - constructor(value: any); - applyTo(): any; - mergeWith(): SetOp; - toJSON(offline?: boolean): any; + _value: any; + constructor(value: any); + applyTo(): any; + mergeWith(): SetOp; + toJSON(offline?: boolean): any; } export declare class UnsetOp extends Op { - applyTo(): any; - mergeWith(): UnsetOp; - toJSON(): { - __op: string; - }; + applyTo(): any; + mergeWith(): UnsetOp; + toJSON(): { + __op: string; + }; } export declare class IncrementOp extends Op { - _amount: number; - constructor(amount: number); - applyTo(value: any): number; - mergeWith(previous: Op): Op; - toJSON(): { - __op: string; - amount: number; - }; + _amount: number; + constructor(amount: number); + applyTo(value: any): number; + mergeWith(previous: Op): Op; + toJSON(): { + __op: string; + amount: number; + }; } export declare class AddOp extends Op { - _value: Array; - constructor(value: any | Array); - applyTo(value: any): Array; - mergeWith(previous: Op): Op; - toJSON(): { - __op: string; - objects: any; - }; + _value: Array; + constructor(value: any | Array); + applyTo(value: any): Array; + mergeWith(previous: Op): Op; + toJSON(): { + __op: string; + objects: any; + }; } export declare class AddUniqueOp extends Op { - _value: Array; - constructor(value: any | Array); - applyTo(value: any | Array): Array; - mergeWith(previous: Op): Op; - toJSON(): { - __op: string; - objects: any; - }; + _value: Array; + constructor(value: any | Array); + applyTo(value: any | Array): Array; + mergeWith(previous: Op): Op; + toJSON(): { + __op: string; + objects: any; + }; } export declare class RemoveOp extends Op { - _value: Array; - constructor(value: any | Array); - applyTo(value: any | Array): Array; - mergeWith(previous: Op): Op; - toJSON(): { - __op: string; - objects: any; - }; + _value: Array; + constructor(value: any | Array); + applyTo(value: any | Array): Array; + mergeWith(previous: Op): Op; + toJSON(): { + __op: string; + objects: any; + }; } export declare class RelationOp extends Op { - _targetClassName: string | null; - relationsToAdd: Array; - relationsToRemove: Array; - constructor(adds: Array, removes: Array); - _extractId(obj: string | ParseObject): string; - applyTo(value: any, parent?: ParseObject, key?: string): ParseRelation; - mergeWith(previous: Op): Op; - toJSON(): { - __op?: string; - objects?: any; - ops?: any; - }; + _targetClassName: string | null; + relationsToAdd: Array; + relationsToRemove: Array; + constructor(adds: Array, removes: Array); + _extractId(obj: string | ParseObject): string; + applyTo(value: any, parent?: ParseObject, key?: string): ParseRelation; + mergeWith(previous: Op): Op; + toJSON(): { + __op?: string; + objects?: any; + ops?: any; + }; } diff --git a/types/ParsePolygon.d.ts b/types/ParsePolygon.d.ts index 3baabb14c..28d4b07d2 100644 --- a/types/ParsePolygon.d.ts +++ b/types/ParsePolygon.d.ts @@ -21,49 +21,49 @@ type Coordinates = Coordinate[]; * @alias Parse.Polygon */ declare class ParsePolygon { - _coordinates: Coordinates; - /** - * @param {(Coordinates | Parse.GeoPoint[])} coordinates An Array of coordinate pairs - */ - constructor(coordinates: Coordinates | Array); - /** - * Coordinates value for this Polygon. - * Throws an exception if not valid type. - * - * @property {(Coordinates | Parse.GeoPoint[])} coordinates list of coordinates - * @returns {Coordinates} - */ - get coordinates(): Coordinates; - set coordinates(coords: Coordinates | Array); - /** - * Returns a JSON representation of the Polygon, suitable for Parse. - * - * @returns {object} - */ - toJSON(): { - __type: string; - coordinates: Coordinates; - }; - /** - * Checks if two polygons are equal - * - * @param {(Parse.Polygon | object)} other - * @returns {boolean} - */ - equals(other: ParsePolygon | any): boolean; - /** - * - * @param {Parse.GeoPoint} point - * @returns {boolean} Returns if the point is contained in the polygon - */ - containsPoint(point: ParseGeoPoint): boolean; - /** - * Validates that the list of coordinates can form a valid polygon - * - * @param {Array} coords the list of coordinates to validate as a polygon - * @throws {TypeError} - * @returns {number[][]} Array of coordinates if validated. - */ - static _validate(coords: Coordinates | Array): Coordinates; + _coordinates: Coordinates; + /** + * @param {(Coordinates | Parse.GeoPoint[])} coordinates An Array of coordinate pairs + */ + constructor(coordinates: Coordinates | Array); + /** + * Coordinates value for this Polygon. + * Throws an exception if not valid type. + * + * @property {(Coordinates | Parse.GeoPoint[])} coordinates list of coordinates + * @returns {Coordinates} + */ + get coordinates(): Coordinates; + set coordinates(coords: Coordinates | Array); + /** + * Returns a JSON representation of the Polygon, suitable for Parse. + * + * @returns {object} + */ + toJSON(): { + __type: string; + coordinates: Coordinates; + }; + /** + * Checks if two polygons are equal + * + * @param {(Parse.Polygon | object)} other + * @returns {boolean} + */ + equals(other: ParsePolygon | any): boolean; + /** + * + * @param {Parse.GeoPoint} point + * @returns {boolean} Returns if the point is contained in the polygon + */ + containsPoint(point: ParseGeoPoint): boolean; + /** + * Validates that the list of coordinates can form a valid polygon + * + * @param {Array} coords the list of coordinates to validate as a polygon + * @throws {TypeError} + * @returns {number[][]} Array of coordinates if validated. + */ + static _validate(coords: Coordinates | Array): Coordinates; } export default ParsePolygon; diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts index 968f13f80..6035c5167 100644 --- a/types/ParseQuery.d.ts +++ b/types/ParseQuery.d.ts @@ -2,49 +2,56 @@ import ParseGeoPoint from './ParseGeoPoint'; import ParseObject from './ParseObject'; import type LiveQuerySubscription from './LiveQuerySubscription'; import type { FullOptions } from './RESTController'; +import type { Pointer } from './ParseObject'; type BatchOptions = FullOptions & { - batchSize?: number; - useMasterKey?: boolean; - sessionToken?: string; - context?: { - [key: string]: any; - }; - json?: boolean; + batchSize?: number; + useMasterKey?: boolean; + useMaintenanceKey?: boolean; + sessionToken?: string; + context?: { + [key: string]: any; + }; + json?: boolean; }; export type WhereClause = { - [attr: string]: any; + [attr: string]: any; }; type QueryOptions = { - useMasterKey?: boolean; - sessionToken?: string; - context?: { - [key: string]: any; - }; - json?: boolean; + useMasterKey?: boolean; + sessionToken?: string; + context?: { + [key: string]: any; + }; + json?: boolean; }; type FullTextQueryOptions = { - language?: string; - caseSensitive?: boolean; - diacriticSensitive?: boolean; + language?: string; + caseSensitive?: boolean; + diacriticSensitive?: boolean; }; export type QueryJSON = { - where: WhereClause; - watch?: string; - include?: string; - excludeKeys?: string; - keys?: string; - limit?: number; - skip?: number; - order?: string; - className?: string; - count?: number; - hint?: any; - explain?: boolean; - readPreference?: string; - includeReadPreference?: string; - subqueryReadPreference?: string; - comment?: string; + where: WhereClause; + watch?: string; + include?: string; + excludeKeys?: string; + keys?: string; + limit?: number; + skip?: number; + order?: string; + className?: string; + count?: number; + hint?: any; + explain?: boolean; + readPreference?: string; + includeReadPreference?: string; + subqueryReadPreference?: string; + comment?: string; }; +interface BaseAttributes { + createdAt: Date; + objectId: string; + updatedAt: Date; +} /** * Creates a new parse Parse.Query for the given Parse.Object subclass. * @@ -88,908 +95,867 @@ export type QueryJSON = { * * @alias Parse.Query */ -declare class ParseQuery { - /** - * @property {string} className - */ - className: string; - _where: any; - _watch: Array; - _include: Array; - _exclude: Array; - _select: Array; - _limit: number; - _skip: number; - _count: boolean; - _order: Array; - _readPreference: string | null; - _includeReadPreference: string | null; - _subqueryReadPreference: string | null; - _queriesLocalDatastore: boolean; - _localDatastorePinName: any; - _extraOptions: { - [key: string]: any; - }; - _hint: any; - _explain: boolean; - _xhrRequest: any; - _comment: string; - /** - * @param {(string | Parse.Object)} objectClass An instance of a subclass of Parse.Object, or a Parse className string. - */ - constructor(objectClass: string | ParseObject); - /** - * Adds constraint that at least one of the passed in queries matches. - * - * @param {Array} queries - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - _orQuery(queries: Array): ParseQuery; - /** - * Adds constraint that all of the passed in queries match. - * - * @param {Array} queries - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - _andQuery(queries: Array): ParseQuery; - /** - * Adds constraint that none of the passed in queries match. - * - * @param {Array} queries - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - _norQuery(queries: Array): ParseQuery; - /** - * Helper for condition queries - * - * @param key - * @param condition - * @param value - * @returns {Parse.Query} - */ - _addCondition(key: string, condition: string, value: any): ParseQuery; - /** - * Converts string for regular expression at the beginning - * - * @param string - * @returns {string} - */ - _regexStartWith(string: string): string; - _handleOfflineQuery(params: QueryJSON): Promise; - /** - * Returns a JSON representation of this query. - * - * @returns {object} The JSON representation of the query. - */ - toJSON(): QueryJSON; - /** - * Return a query with conditions from json, can be useful to send query from server side to client - * Not static, all query conditions was set before calling this method will be deleted. - * For example on the server side we have - * var query = new Parse.Query("className"); - * query.equalTo(key: value); - * query.limit(100); - * ... (others queries) - * Create JSON representation of Query Object - * var jsonFromServer = query.fromJSON(); - * - * On client side getting query: - * var query = new Parse.Query("className"); - * query.fromJSON(jsonFromServer); - * - * and continue to query... - * query.skip(100).find().then(...); - * - * @param {QueryJSON} json from Parse.Query.toJSON() method - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - withJSON(json: QueryJSON): ParseQuery; - /** - * Static method to restore Parse.Query by json representation - * Internally calling Parse.Query.withJSON - * - * @param {string} className - * @param {QueryJSON} json from Parse.Query.toJSON() method - * @returns {Parse.Query} new created query - */ - static fromJSON(className: string, json: QueryJSON): ParseQuery; - /** - * Constructs a Parse.Object whose id is already known by fetching data from - * the server. Unlike the first method, it never returns undefined. - * - * @param {string} objectId The id of the object to be fetched. - * @param {object} options - * Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
    • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. - *
    • json: Return raw json without converting to Parse.Object - *
    - * @returns {Promise} A promise that is resolved with the result when - * the query completes. - */ - get(objectId: string, options?: QueryOptions): Promise; - /** - * Retrieves a list of ParseObjects that satisfy this query. - * - * @param {object} options Valid options - * are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
    • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. - *
    • json: Return raw json without converting to Parse.Object - *
    - * @returns {Promise} A promise that is resolved with the results when - * the query completes. - */ - find(options?: QueryOptions): Promise>; - /** - * Retrieves a complete list of ParseObjects that satisfy this query. - * Using `eachBatch` under the hood to fetch all the valid objects. - * - * @param {object} options Valid options are:
      - *
    • batchSize: How many objects to yield in each batch (default: 100) - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
    • json: Return raw JSON without converting to Parse.Object. - *
    - * @returns {Promise} A promise that is resolved with the results when - * the query completes. - */ - findAll(options?: BatchOptions): Promise>; - /** - * Counts the number of objects that match this query. - * - * @param {object} options - * @param {boolean} [options.useMasterKey] - * @param {string} [options.sessionToken] - * Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
    - * @returns {Promise} A promise that is resolved with the count when - * the query completes. - */ - count(options?: { useMasterKey?: boolean; sessionToken?: string }): Promise; - /** - * Executes a distinct query and returns unique values - * - * @param {string} key A field to find distinct values - * @param {object} options - * @param {string} [options.sessionToken] A valid session token, used for making a request on behalf of a specific user. - * @returns {Promise} A promise that is resolved with the query completes. - */ - distinct( - key: string, - options?: { - sessionToken?: string; - } - ): Promise>; - /** - * Executes an aggregate query and returns aggregate results - * - * @param {(Array|object)} pipeline Array or Object of stages to process query - * @param {object} options - * @param {string} [options.sessionToken] A valid session token, used for making a request on behalf of a specific user. - * @returns {Promise} A promise that is resolved with the query completes. - */ - aggregate( - pipeline: any, - options?: { - sessionToken?: string; - } - ): Promise>; - /** - * Retrieves at most one Parse.Object that satisfies this query. - * - * Returns the object if there is one, otherwise undefined. - * - * @param {object} options Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
    • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. - *
    • json: Return raw json without converting to Parse.Object - *
    - * @returns {Promise} A promise that is resolved with the object when - * the query completes. - */ - first(options?: QueryOptions): 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 - * that promise has been fulfilled. If the callback returns a rejected - * promise, then iteration will stop with that error. The items are processed - * in an unspecified order. The query may not have any sort order, and may - * not use limit or skip. - * - * @param {Function} callback Callback that will be called with each result - * of the query. - * @param {object} options Valid options are:
      - *
    • batchSize: How many objects to yield in each batch (default: 100) - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
    • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. - *
    - * @returns {Promise} A promise that will be fulfilled once the - * iteration has completed. - */ - eachBatch(callback: (objs: Array) => 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 - * that promise has been fulfilled. If the callback returns a rejected - * promise, then iteration will stop with that error. The items are - * processed in an unspecified order. The query may not have any sort order, - * and may not use limit or skip. - * - * @param {Function} callback Callback that will be called with each result - * of the query. - * @param {object} options Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
    • json: Return raw json without converting to Parse.Object - *
    - * @returns {Promise} A promise that will be fulfilled once the - * iteration has completed. - */ - each(callback: (obj: ParseObject) => any, options?: BatchOptions): Promise; - /** - * Adds a hint to force index selection. (https://docs.mongodb.com/manual/reference/operator/meta/hint/) - * - * @param {(string|object)} value String or Object of index that should be used when executing query - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - hint(value: any): ParseQuery; - /** - * Investigates the query execution plan. Useful for optimizing queries. (https://docs.mongodb.com/manual/reference/operator/meta/explain/) - * - * @param {boolean} explain Used to toggle the information on the query plan. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - explain(explain?: boolean): ParseQuery; - /** - * 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 - * that promise has been fulfilled. If the callback returns a rejected - * promise, then iteration will stop with that error. The items are - * processed in an unspecified order. The query may not have any sort order, - * and may not use limit or skip. - * - * @param {Function} callback Callback
      - *
    • currentObject: The current Parse.Object being processed in the array.
    • - *
    • index: The index of the current Parse.Object being processed in the array.
    • - *
    • query: The query map was called upon.
    • - *
    - * @param {object} options Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
    - * @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>; - /** - * 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 - * that promise has been fulfilled. If the callback returns a rejected - * promise, then iteration will stop with that error. The items are - * processed in an unspecified order. The query may not have any sort order, - * and may not use limit or skip. - * - * @param {Function} callback Callback
      - *
    • accumulator: The accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback.
    • - *
    • currentObject: The current Parse.Object being processed in the array.
    • - *
    • index: The index of the current Parse.Object being processed in the array.
    • - *
    - * @param {*} initialValue A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first object in the query will be used and skipped. - * @param {object} options Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
    - * @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>; - /** - * 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 - * that promise has been fulfilled. If the callback returns a rejected - * promise, then iteration will stop with that error. The items are - * processed in an unspecified order. The query may not have any sort order, - * and may not use limit or skip. - * - * @param {Function} callback Callback
      - *
    • currentObject: The current Parse.Object being processed in the array.
    • - *
    • index: The index of the current Parse.Object being processed in the array.
    • - *
    • query: The query filter was called upon.
    • - *
    - * @param {object} options Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • sessionToken: A valid session token, used for making a request on - * behalf of a specific user. - *
    - * @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>; - /** - * Adds a constraint to the query that requires a particular key's value to - * be equal to the provided value. - * - * @param {string} key The key to check. - * @param value The value that the Parse.Object must contain. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - equalTo( - key: - | string - | { - [key: string]: any; - }, - value?: any - ): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's value to - * be not equal to the provided value. - * - * @param {string} key The key to check. - * @param value The value that must not be equalled. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - notEqualTo( - key: - | string - | { - [key: string]: any; - }, - value?: any - ): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's value to - * be less than the provided value. - * - * @param {string} key The key to check. - * @param value The value that provides an upper bound. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - lessThan(key: string, value: any): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's value to - * be greater than the provided value. - * - * @param {string} key The key to check. - * @param value The value that provides an lower bound. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - greaterThan(key: string, value: any): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's value to - * be less than or equal to the provided value. - * - * @param {string} key The key to check. - * @param value The value that provides an upper bound. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - lessThanOrEqualTo(key: string, value: any): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's value to - * be greater than or equal to the provided value. - * - * @param {string} key The key to check. - * @param {*} value The value that provides an lower bound. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - greaterThanOrEqualTo(key: string, value: any): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's value to - * be contained in the provided list of values. - * - * @param {string} key The key to check. - * @param {Array<*>} value The values that will match. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - containedIn(key: string, value: Array): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's value to - * not be contained in the provided list of values. - * - * @param {string} key The key to check. - * @param {Array<*>} value The values that will not match. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - notContainedIn(key: string, value: Array): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's value to - * be contained by the provided list of values. Get objects where all array elements match. - * - * @param {string} key The key to check. - * @param {Array} values The values that will match. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - containedBy(key: string, values: Array): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's value to - * contain each one of the provided list of values. - * - * @param {string} key The key to check. This key's value must be an array. - * @param {Array} values The values that will match. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - containsAll(key: string, values: Array): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's value to - * contain each one of the provided list of values starting with given strings. - * - * @param {string} key The key to check. This key's value must be an array. - * @param {Array} values The string values that will match as starting string. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - containsAllStartingWith(key: string, values: Array): ParseQuery; - /** - * Adds a constraint for finding objects that contain the given key. - * - * @param {string} key The key that should exist. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - exists(key: string): ParseQuery; - /** - * Adds a constraint for finding objects that do not contain a given key. - * - * @param {string} key The key that should not exist - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - doesNotExist(key: string): ParseQuery; - /** - * Adds a regular expression constraint for finding string values that match - * the provided regular expression. - * This may be slow for large datasets. - * - * @param {string} key The key that the string to match is stored in. - * @param {RegExp | string} regex The regular expression pattern to match. - * @param {string} modifiers The regular expression mode. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - matches(key: string, regex: RegExp | string, modifiers: string): ParseQuery; - /** - * Adds a constraint that requires that a key's value matches a Parse.Query - * constraint. - * - * @param {string} key The key that the contains the object to match the - * query. - * @param {Parse.Query} query The query that should match. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - matchesQuery(key: string, query: ParseQuery): ParseQuery; - /** - * Adds a constraint that requires that a key's value not matches a - * Parse.Query constraint. - * - * @param {string} key The key that the contains the object to match the - * query. - * @param {Parse.Query} query The query that should not match. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - doesNotMatchQuery(key: string, query: ParseQuery): ParseQuery; - /** - * Adds a constraint that requires that a key's value matches a value in - * an object returned by a different Parse.Query. - * - * @param {string} key The key that contains the value that is being - * matched. - * @param {string} queryKey The key in the objects returned by the query to - * match against. - * @param {Parse.Query} query The query to run. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - matchesKeyInQuery(key: string, queryKey: string, query: ParseQuery): ParseQuery; - /** - * Adds a constraint that requires that a key's value not match a value in - * an object returned by a different Parse.Query. - * - * @param {string} key The key that contains the value that is being - * excluded. - * @param {string} queryKey The key in the objects returned by the query to - * match against. - * @param {Parse.Query} query The query to run. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - doesNotMatchKeyInQuery(key: string, queryKey: string, query: ParseQuery): ParseQuery; - /** - * Adds a constraint for finding string values that contain a provided - * string. This may be slow for large datasets. - * - * @param {string} key The key that the string to match is stored in. - * @param {string} substring The substring that the value must contain. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - contains(key: string, substring: string): ParseQuery; - /** - * Adds a constraint for finding string values that contain a provided - * string. This may be slow for large datasets. Requires Parse-Server > 2.5.0 - * - * In order to sort you must use select and ascending ($score is required) - *
    -   *   query.fullText('field', 'term');
    -   *   query.ascending('$score');
    -   *   query.select('$score');
    -   *  
    - * - * To retrieve the weight / rank - *
    -   *   object->get('score');
    -   *  
    - * - * You can define optionals by providing an object as a third parameter - *
    -   *   query.fullText('field', 'term', { language: 'es', diacriticSensitive: true });
    -   *  
    - * - * @param {string} key The key that the string to match is stored in. - * @param {string} value The string to search - * @param {object} options (Optional) - * @param {string} options.language The language that determines the list of stop words for the search and the rules for the stemmer and tokenizer. - * @param {boolean} options.caseSensitive A boolean flag to enable or disable case sensitive search. - * @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: string, value: string, options?: FullTextQueryOptions): ParseQuery; - /** - * Method to sort the full text search by text score - * - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - sortByTextScore(): this; - /** - * Adds a constraint for finding string values that start with a provided - * string. This query will use the backend index, so it will be fast even - * for large datasets. - * - * @param {string} key The key that the string to match is stored in. - * @param {string} prefix The substring that the value must start with. - * @param {string} modifiers The regular expression mode. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - startsWith(key: string, prefix: string, modifiers: string): ParseQuery; - /** - * Adds a constraint for finding string values that end with a provided - * string. This will be slow for large datasets. - * - * @param {string} key The key that the string to match is stored in. - * @param {string} suffix The substring that the value must end with. - * @param {string} modifiers The regular expression mode. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - endsWith(key: string, suffix: string, modifiers: string): ParseQuery; - /** - * Adds a proximity based constraint for finding objects with key point - * values near the point given. - * - * @param {string} key The key that the Parse.GeoPoint is stored in. - * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - near(key: string, point: ParseGeoPoint): ParseQuery; - /** - * Adds a proximity based constraint for finding objects with key point - * values near the point given and within the maximum distance given. - * - * @param {string} key The key that the Parse.GeoPoint is stored in. - * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. - * @param {number} maxDistance Maximum distance (in radians) of results to return. - * @param {boolean} sorted A Bool value that is true if results should be - * sorted by distance ascending, false is no sorting is required, - * defaults to true. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - withinRadians( - key: string, - point: ParseGeoPoint, - maxDistance: number, - sorted: boolean - ): ParseQuery; - /** - * Adds a proximity based constraint for finding objects with key point - * values near the point given and within the maximum distance given. - * Radius of earth used is 3958.8 miles. - * - * @param {string} key The key that the Parse.GeoPoint is stored in. - * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. - * @param {number} maxDistance Maximum distance (in miles) of results to return. - * @param {boolean} sorted A Bool value that is true if results should be - * sorted by distance ascending, false is no sorting is required, - * defaults to true. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - withinMiles(key: string, point: ParseGeoPoint, maxDistance: number, sorted: boolean): ParseQuery; - /** - * Adds a proximity based constraint for finding objects with key point - * values near the point given and within the maximum distance given. - * Radius of earth used is 6371.0 kilometers. - * - * @param {string} key The key that the Parse.GeoPoint is stored in. - * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. - * @param {number} maxDistance Maximum distance (in kilometers) of results to return. - * @param {boolean} sorted A Bool value that is true if results should be - * sorted by distance ascending, false is no sorting is required, - * defaults to true. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - withinKilometers( - key: string, - point: ParseGeoPoint, - maxDistance: number, - sorted: boolean - ): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's - * coordinates be contained within a given rectangular geographic bounding - * box. - * - * @param {string} key The key to be constrained. - * @param {Parse.GeoPoint} southwest - * The lower-left inclusive corner of the box. - * @param {Parse.GeoPoint} northeast - * The upper-right inclusive corner of the box. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - withinGeoBox(key: string, southwest: ParseGeoPoint, northeast: ParseGeoPoint): ParseQuery; - /** - * Adds a constraint to the query that requires a particular key's - * coordinates be contained within and on the bounds of a given polygon. - * Supports closed and open (last point is connected to first) paths - * - * Polygon must have at least 3 points - * - * @param {string} key The key to be constrained. - * @param {Array} points Array of Coordinates / GeoPoints - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - withinPolygon(key: string, points: Array>): ParseQuery; - /** - * Add a constraint to the query that requires a particular key's - * coordinates that contains a ParseGeoPoint - * - * @param {string} key The key to be constrained. - * @param {Parse.GeoPoint} point - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - polygonContains(key: string, point: ParseGeoPoint): ParseQuery; - /** - * Sorts the results in ascending order by the given key. - * - * @param {(string|string[])} keys The key to order by, which is a - * string of comma separated values, or an Array of keys, or multiple keys. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - ascending(...keys: Array): ParseQuery; - /** - * Sorts the results in ascending order by the given key, - * but can also add secondary sort descriptors without overwriting _order. - * - * @param {(string|string[])} keys The key to order by, which is a - * string of comma separated values, or an Array of keys, or multiple keys. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - addAscending(...keys: Array): ParseQuery; - /** - * Sorts the results in descending order by the given key. - * - * @param {(string|string[])} keys The key to order by, which is a - * string of comma separated values, or an Array of keys, or multiple keys. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - descending(...keys: Array): ParseQuery; - /** - * Sorts the results in descending order by the given key, - * but can also add secondary sort descriptors without overwriting _order. - * - * @param {(string|string[])} keys The key to order by, which is a - * string of comma separated values, or an Array of keys, or multiple keys. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - addDescending(...keys: Array): ParseQuery; - /** - * Sets the number of results to skip before returning any results. - * This is useful for pagination. - * Default is to skip zero results. - * - * @param {number} n the number of results to skip. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - skip(n: number): ParseQuery; - /** - * Sets the limit of the number of results to return. The default limit is 100. - * - * @param {number} n the number of results to limit to. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - limit(n: number): ParseQuery; - /** - * Sets the flag to include with response the total number of objects satisfying this query, - * despite limits/skip. Might be useful for pagination. - * Note that result of this query will be wrapped as an object with - * `results`: holding {ParseObject} array and `count`: integer holding total number - * - * @param {boolean} includeCount false - disable, true - enable. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - withCount(includeCount?: boolean): ParseQuery; - /** - * Includes nested Parse.Objects for the provided key. You can use dot - * notation to specify which fields in the included object are also fetched. - * - * You can include all nested Parse.Objects by passing in '*'. - * Requires Parse Server 3.0.0+ - *
    query.include('*');
    - * - * @param {...string|Array} keys The name(s) of the key(s) to include. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - include(...keys: Array>): ParseQuery; - /** - * Includes all nested Parse.Objects one level deep. - * - * Requires Parse Server 3.0.0+ - * - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - includeAll(): ParseQuery; - /** - * Restricts the fields of the returned Parse.Objects to include only the - * provided keys. If this is called multiple times, then all of the keys - * specified in each of the calls will be included. - * - * @param {...string|Array} keys The name(s) of the key(s) to include. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - select(...keys: Array>): ParseQuery; - /** - * Restricts the fields of the returned Parse.Objects to all keys except the - * provided keys. Exclude takes precedence over select and include. - * - * Requires Parse Server 3.6.0+ - * - * @param {...string|Array} keys The name(s) of the key(s) to exclude. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - exclude(...keys: Array>): ParseQuery; - /** - * Restricts live query to trigger only for watched fields. - * - * Requires Parse Server 6.0.0+ - * - * @param {...string|Array} keys The name(s) of the key(s) to watch. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - watch(...keys: Array>): ParseQuery; - /** - * Changes the read preference that the backend will use when performing the query to the database. - * - * @param {string} readPreference The read preference for the main query. - * @param {string} includeReadPreference The read preference for the queries to include pointers. - * @param {string} subqueryReadPreference The read preference for the sub queries. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - readPreference( - readPreference: string, - includeReadPreference?: string, - subqueryReadPreference?: string - ): ParseQuery; - /** - * Subscribe this query to get liveQuery updates - * - * @param {string} sessionToken (optional) Defaults to the currentUser - * @returns {Promise} Returns the liveQuerySubscription, it's an event emitter - * which can be used to get liveQuery updates. - */ - subscribe(sessionToken?: string): Promise; - /** - * Constructs a Parse.Query that is the OR of the passed in queries. For - * example: - *
    var compoundQuery = Parse.Query.or(query1, query2, query3);
    - * - * will create a compoundQuery that is an or of the query1, query2, and - * query3. - * - * @param {...Parse.Query} queries The list of queries to OR. - * @static - * @returns {Parse.Query} The query that is the OR of the passed in queries. - */ - static or(...queries: Array): ParseQuery; - /** - * Constructs a Parse.Query that is the AND of the passed in queries. For - * example: - *
    var compoundQuery = Parse.Query.and(query1, query2, query3);
    - * - * will create a compoundQuery that is an and of the query1, query2, and - * query3. - * - * @param {...Parse.Query} queries The list of queries to AND. - * @static - * @returns {Parse.Query} The query that is the AND of the passed in queries. - */ - static and(...queries: Array): ParseQuery; - /** - * Constructs a Parse.Query that is the NOR of the passed in queries. For - * example: - *
    const compoundQuery = Parse.Query.nor(query1, query2, query3);
    - * - * will create a compoundQuery that is a nor of the query1, query2, and - * query3. - * - * @param {...Parse.Query} queries The list of queries to NOR. - * @static - * @returns {Parse.Query} The query that is the NOR of the passed in queries. - */ - static nor(...queries: Array): ParseQuery; - /** - * Change the source of this query to the server. - * - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - fromNetwork(): ParseQuery; - /** - * Changes the source of this query to all pinned objects. - * - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - fromLocalDatastore(): ParseQuery; - /** - * Changes the source of this query to the default group of pinned objects. - * - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - fromPin(): ParseQuery; - /** - * Changes the source of this query to a specific group of pinned objects. - * - * @param {string} name The name of query source. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - fromPinWithName(name?: string | null): ParseQuery; - /** - * Cancels the current network request (if any is running). - * - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - cancel(): ParseQuery; - _setRequestTask(options: any): void; - /** - * Sets a comment to the query so that the query - * can be identified when using a the profiler for MongoDB. - * - * @param {string} value a comment can make your profile data easier to interpret and trace. - * @returns {Parse.Query} Returns the query, so you can chain this call. - */ - comment(value: string): ParseQuery; +declare class ParseQuery { + /** + * @property {string} className + */ + className: string; + _where: any; + _watch: Array; + _include: Array; + _exclude: Array; + _select: Array; + _limit: number; + _skip: number; + _count: boolean; + _order: Array; + _readPreference: string | null; + _includeReadPreference: string | null; + _subqueryReadPreference: string | null; + _queriesLocalDatastore: boolean; + _localDatastorePinName: any; + _extraOptions: { + [key: string]: any; + }; + _hint: any; + _explain: boolean; + _xhrRequest: any; + _comment: string; + /** + * @param {(string | Parse.Object)} objectClass An instance of a subclass of Parse.Object, or a Parse className string. + */ + constructor(objectClass: string | (new (...args: any[]) => T | ParseObject)); + /** + * Adds constraint that at least one of the passed in queries matches. + * + * @param {Array} queries + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + _orQuery(queries: Array): this; + /** + * Adds constraint that all of the passed in queries match. + * + * @param {Array} queries + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + _andQuery(queries: Array): this; + /** + * Adds constraint that none of the passed in queries match. + * + * @param {Array} queries + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + _norQuery(queries: Array): this; + /** + * Helper for condition queries + * + * @param key + * @param condition + * @param value + * @returns {Parse.Query} + */ + _addCondition(key: K, condition: string, value: any): this; + /** + * Converts string for regular expression at the beginning + * + * @param string + * @returns {string} + */ + _regexStartWith(string: string): string; + _handleOfflineQuery(params: QueryJSON): Promise; + /** + * Returns a JSON representation of this query. + * + * @returns {object} The JSON representation of the query. + */ + toJSON(): QueryJSON; + /** + * Return a query with conditions from json, can be useful to send query from server side to client + * Not static, all query conditions was set before calling this method will be deleted. + * For example on the server side we have + * var query = new Parse.Query("className"); + * query.equalTo(key: value); + * query.limit(100); + * ... (others queries) + * Create JSON representation of Query Object + * var jsonFromServer = query.fromJSON(); + * + * On client side getting query: + * var query = new Parse.Query("className"); + * query.fromJSON(jsonFromServer); + * + * and continue to query... + * query.skip(100).find().then(...); + * + * @param {QueryJSON} json from Parse.Query.toJSON() method + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + withJSON(json: QueryJSON): this; + /** + * Static method to restore Parse.Query by json representation + * Internally calling Parse.Query.withJSON + * + * @param {string} className + * @param {QueryJSON} json from Parse.Query.toJSON() method + * @returns {Parse.Query} new created query + */ + static fromJSON(className: string, json: QueryJSON): ParseQuery; + /** + * Constructs a Parse.Object whose id is already known by fetching data from + * the server. Unlike the first method, it never returns undefined. + * + * @param {string} objectId The id of the object to be fetched. + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. + *
    • json: Return raw json without converting to Parse.Object + *
    + * @returns {Promise} A promise that is resolved with the result when + * the query completes. + */ + get(objectId: string, options?: QueryOptions): Promise; + /** + * Retrieves a list of ParseObjects that satisfy this query. + * + * @param {object} options Valid options + * are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. + *
    • json: Return raw json without converting to Parse.Object + *
    + * @returns {Promise} A promise that is resolved with the results when + * the query completes. + */ + find(options?: QueryOptions): Promise; + /** + * Retrieves a complete list of ParseObjects that satisfy this query. + * Using `eachBatch` under the hood to fetch all the valid objects. + * + * @param {object} options Valid options are:
      + *
    • batchSize: How many objects to yield in each batch (default: 100) + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • json: Return raw JSON without converting to Parse.Object. + *
    + * @returns {Promise} A promise that is resolved with the results when + * the query completes. + */ + findAll(options?: BatchOptions): Promise; + /** + * Counts the number of objects that match this query. + * + * @param {object} options + * @param {boolean} [options.useMasterKey] + * @param {string} [options.sessionToken] + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    + * @returns {Promise} A promise that is resolved with the count when + * the query completes. + */ + count(options?: { + useMasterKey?: boolean; + sessionToken?: string; + }): Promise; + /** + * Executes a distinct query and returns unique values + * + * @param {string} key A field to find distinct values + * @param {object} options + * @param {string} [options.sessionToken] A valid session token, used for making a request on behalf of a specific user. + * @returns {Promise} A promise that is resolved with the query completes. + */ + distinct(key: K, options?: { + sessionToken?: string; + }): Promise; + /** + * Executes an aggregate query and returns aggregate results + * + * @param {(Array|object)} pipeline Array or Object of stages to process query + * @param {object} options + * @param {string} [options.sessionToken] A valid session token, used for making a request on behalf of a specific user. + * @returns {Promise} A promise that is resolved with the query completes. + */ + aggregate(pipeline: any, options?: { + sessionToken?: string; + }): Promise>; + /** + * Retrieves at most one Parse.Object that satisfies this query. + * + * Returns the object if there is one, otherwise undefined. + * + * @param {object} options Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. + *
    • json: Return raw json without converting to Parse.Object + *
    + * @returns {Promise} A promise that is resolved with the object when + * the query completes. + */ + first(options?: QueryOptions): 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 + * that promise has been fulfilled. If the callback returns a rejected + * promise, then iteration will stop with that error. The items are processed + * in an unspecified order. The query may not have any sort order, and may + * not use limit or skip. + * + * @param {Function} callback Callback that will be called with each result + * of the query. + * @param {object} options Valid options are:
      + *
    • batchSize: How many objects to yield in each batch (default: 100) + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • context: A dictionary that is accessible in Cloud Code `beforeFind` trigger. + *
    + * @returns {Promise} A promise that will be fulfilled once the + * iteration has completed. + */ + 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 + * that promise has been fulfilled. If the callback returns a rejected + * promise, then iteration will stop with that error. The items are + * processed in an unspecified order. The query may not have any sort order, + * and may not use limit or skip. + * + * @param {Function} callback Callback that will be called with each result + * of the query. + * @param {object} options Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    • json: Return raw json without converting to Parse.Object + *
    + * @returns {Promise} A promise that will be fulfilled once the + * iteration has completed. + */ + 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/) + * + * @param {(string|object)} value String or Object of index that should be used when executing query + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + hint(value: any): this; + /** + * Investigates the query execution plan. Useful for optimizing queries. (https://docs.mongodb.com/manual/reference/operator/meta/explain/) + * + * @param {boolean} explain Used to toggle the information on the query plan. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + explain(explain?: boolean): this; + /** + * 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 + * that promise has been fulfilled. If the callback returns a rejected + * promise, then iteration will stop with that error. The items are + * processed in an unspecified order. The query may not have any sort order, + * and may not use limit or skip. + * + * @param {Function} callback Callback
      + *
    • currentObject: The current Parse.Object being processed in the array.
    • + *
    • index: The index of the current Parse.Object being processed in the array.
    • + *
    • query: The query map was called upon.
    • + *
    + * @param {object} options Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    + * @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>; + /** + * 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 + * that promise has been fulfilled. If the callback returns a rejected + * promise, then iteration will stop with that error. The items are + * processed in an unspecified order. The query may not have any sort order, + * and may not use limit or skip. + * + * @param {Function} callback Callback
      + *
    • accumulator: The accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback.
    • + *
    • currentObject: The current Parse.Object being processed in the array.
    • + *
    • index: The index of the current Parse.Object being processed in the array.
    • + *
    + * @param {*} initialValue A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first object in the query will be used and skipped. + * @param {object} options Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    + * @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>; + /** + * 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 + * that promise has been fulfilled. If the callback returns a rejected + * promise, then iteration will stop with that error. The items are + * processed in an unspecified order. The query may not have any sort order, + * and may not use limit or skip. + * + * @param {Function} callback Callback
      + *
    • currentObject: The current Parse.Object being processed in the array.
    • + *
    • index: The index of the current Parse.Object being processed in the array.
    • + *
    • query: The query filter was called upon.
    • + *
    + * @param {object} options Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • sessionToken: A valid session token, used for making a request on + * behalf of a specific user. + *
    + * @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>; + /** + * Adds a constraint to the query that requires a particular key's value to + * be equal to the provided value. + * + * @param {string} key The key to check. + * @param value The value that the Parse.Object must contain. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + equalTo(key: K, value: T['attributes'][K] | (T['attributes'][K] extends ParseObject ? Pointer : T['attributes'][K] extends Array ? E : never)): this; + /** + * Adds a constraint to the query that requires a particular key's value to + * be not equal to the provided value. + * + * @param {string} key The key to check. + * @param value The value that must not be equalled. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + notEqualTo(key: K, value: T['attributes'][K] | (T['attributes'][K] extends ParseObject ? Pointer : T['attributes'][K] extends Array ? E : never)): this; + /** + * Adds a constraint to the query that requires a particular key's value to + * be less than the provided value. + * + * @param {string} key The key to check. + * @param value The value that provides an upper bound. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + lessThan(key: K, value: T['attributes'][K]): this; + /** + * Adds a constraint to the query that requires a particular key's value to + * be greater than the provided value. + * + * @param {string} key The key to check. + * @param value The value that provides an lower bound. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + greaterThan(key: K, value: T['attributes'][K]): this; + /** + * Adds a constraint to the query that requires a particular key's value to + * be less than or equal to the provided value. + * + * @param {string} key The key to check. + * @param value The value that provides an upper bound. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + lessThanOrEqualTo(key: K, value: T['attributes'][K]): this; + /** + * Adds a constraint to the query that requires a particular key's value to + * be greater than or equal to the provided value. + * + * @param {string} key The key to check. + * @param {*} value The value that provides an lower bound. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + greaterThanOrEqualTo(key: K, value: T['attributes'][K]): this; + /** + * Adds a constraint to the query that requires a particular key's value to + * be contained in the provided list of values. + * + * @param {string} key The key to check. + * @param {Array<*>} values The values that will match. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + containedIn(key: K, values: Array): this; + /** + * Adds a constraint to the query that requires a particular key's value to + * not be contained in the provided list of values. + * + * @param {string} key The key to check. + * @param {Array<*>} values The values that will not match. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + notContainedIn(key: K, values: Array): this; + /** + * Adds a constraint to the query that requires a particular key's value to + * be contained by the provided list of values. Get objects where all array elements match. + * + * @param {string} key The key to check. + * @param {Array} values The values that will match. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + containedBy(key: K, values: Array): this; + /** + * Adds a constraint to the query that requires a particular key's value to + * contain each one of the provided list of values. + * + * @param {string} key The key to check. This key's value must be an array. + * @param {Array} values The values that will match. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + containsAll(key: K, values: any[]): this; + /** + * Adds a constraint to the query that requires a particular key's value to + * contain each one of the provided list of values starting with given strings. + * + * @param {string} key The key to check. This key's value must be an array. + * @param {Array} values The string values that will match as starting string. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + containsAllStartingWith(key: K, values: any[]): this; + /** + * Adds a constraint for finding objects that contain the given key. + * + * @param {string} key The key that should exist. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + exists(key: K): this; + /** + * Adds a constraint for finding objects that do not contain a given key. + * + * @param {string} key The key that should not exist + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + doesNotExist(key: K): this; + /** + * Adds a regular expression constraint for finding string values that match + * the provided regular expression. + * This may be slow for large datasets. + * + * @param {string} key The key that the string to match is stored in. + * @param {RegExp | string} regex The regular expression pattern to match. + * @param {string} modifiers The regular expression mode. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + matches(key: K, regex: RegExp | string, modifiers?: string): this; + /** + * Adds a constraint that requires that a key's value matches a Parse.Query + * constraint. + * + * @param {string} key The key that the contains the object to match the + * query. + * @param {Parse.Query} query The query that should match. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + matchesQuery(key: K, query: ParseQuery): this; + /** + * Adds a constraint that requires that a key's value not matches a + * Parse.Query constraint. + * + * @param {string} key The key that the contains the object to match the + * query. + * @param {Parse.Query} query The query that should not match. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + doesNotMatchQuery(key: K, query: ParseQuery): this; + /** + * Adds a constraint that requires that a key's value matches a value in + * an object returned by a different Parse.Query. + * + * @param {string} key The key that contains the value that is being + * matched. + * @param {string} queryKey The key in the objects returned by the query to + * match against. + * @param {Parse.Query} query The query to run. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + matchesKeyInQuery>(key: K, queryKey: X, query: ParseQuery): this; + /** + * Adds a constraint that requires that a key's value not match a value in + * an object returned by a different Parse.Query. + * + * @param {string} key The key that contains the value that is being + * excluded. + * @param {string} queryKey The key in the objects returned by the query to + * match against. + * @param {Parse.Query} query The query to run. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + doesNotMatchKeyInQuery>(key: K, queryKey: X, query: ParseQuery): this; + /** + * Adds a constraint for finding string values that contain a provided + * string. This may be slow for large datasets. + * + * @param {string} key The key that the string to match is stored in. + * @param {string} substring The substring that the value must contain. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + contains(key: K, substring: string): this; + /** + * Adds a constraint for finding string values that contain a provided + * string. This may be slow for large datasets. Requires Parse-Server > 2.5.0 + * + * In order to sort you must use select and ascending ($score is required) + *
    +     *   query.fullText('field', 'term');
    +     *   query.ascending('$score');
    +     *   query.select('$score');
    +     *  
    + * + * To retrieve the weight / rank + *
    +     *   object->get('score');
    +     *  
    + * + * You can define optionals by providing an object as a third parameter + *
    +     *   query.fullText('field', 'term', { language: 'es', diacriticSensitive: true });
    +     *  
    + * + * @param {string} key The key that the string to match is stored in. + * @param {string} value The string to search + * @param {object} options (Optional) + * @param {string} options.language The language that determines the list of stop words for the search and the rules for the stemmer and tokenizer. + * @param {boolean} options.caseSensitive A boolean flag to enable or disable case sensitive search. + * @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; + /** + * Method to sort the full text search by text score + * + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + sortByTextScore(): this; + /** + * Adds a constraint for finding string values that start with a provided + * string. This query will use the backend index, so it will be fast even + * for large datasets. + * + * @param {string} key The key that the string to match is stored in. + * @param {string} prefix The substring that the value must start with. + * @param {string} modifiers The regular expression mode. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + startsWith(key: K, prefix: string, modifiers?: string): this; + /** + * Adds a constraint for finding string values that end with a provided + * string. This will be slow for large datasets. + * + * @param {string} key The key that the string to match is stored in. + * @param {string} suffix The substring that the value must end with. + * @param {string} modifiers The regular expression mode. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + endsWith(key: K, suffix: string, modifiers?: string): this; + /** + * Adds a proximity based constraint for finding objects with key point + * values near the point given. + * + * @param {string} key The key that the Parse.GeoPoint is stored in. + * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + near(key: K, point: ParseGeoPoint): this; + /** + * Adds a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * + * @param {string} key The key that the Parse.GeoPoint is stored in. + * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. + * @param {number} maxDistance Maximum distance (in radians) of results to return. + * @param {boolean} sorted A Bool value that is true if results should be + * sorted by distance ascending, false is no sorting is required, + * defaults to true. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + withinRadians(key: K, point: ParseGeoPoint, maxDistance: number, sorted?: boolean): this; + /** + * Adds a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 3958.8 miles. + * + * @param {string} key The key that the Parse.GeoPoint is stored in. + * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. + * @param {number} maxDistance Maximum distance (in miles) of results to return. + * @param {boolean} sorted A Bool value that is true if results should be + * sorted by distance ascending, false is no sorting is required, + * defaults to true. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + withinMiles(key: K, point: ParseGeoPoint, maxDistance: number, sorted?: boolean): this; + /** + * Adds a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 6371.0 kilometers. + * + * @param {string} key The key that the Parse.GeoPoint is stored in. + * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. + * @param {number} maxDistance Maximum distance (in kilometers) of results to return. + * @param {boolean} sorted A Bool value that is true if results should be + * sorted by distance ascending, false is no sorting is required, + * defaults to true. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + withinKilometers(key: K, point: ParseGeoPoint, maxDistance: number, sorted?: boolean): this; + /** + * Adds a constraint to the query that requires a particular key's + * coordinates be contained within a given rectangular geographic bounding + * box. + * + * @param {string} key The key to be constrained. + * @param {Parse.GeoPoint} southwest + * The lower-left inclusive corner of the box. + * @param {Parse.GeoPoint} northeast + * The upper-right inclusive corner of the box. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + withinGeoBox(key: K, southwest: ParseGeoPoint, northeast: ParseGeoPoint): this; + /** + * Adds a constraint to the query that requires a particular key's + * coordinates be contained within and on the bounds of a given polygon. + * Supports closed and open (last point is connected to first) paths + * + * Polygon must have at least 3 points + * + * @param {string} key The key to be constrained. + * @param {Array} points Array of Coordinates / GeoPoints + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + withinPolygon(key: K, points: number[][]): this; + /** + * Add a constraint to the query that requires a particular key's + * coordinates that contains a ParseGeoPoint + * + * @param {string} key The key to be constrained. + * @param {Parse.GeoPoint} point + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + polygonContains(key: K, point: ParseGeoPoint): this; + /** + * Sorts the results in ascending order by the given key. + * + * @param {(string|string[])} keys The key to order by, which is a + * string of comma separated values, or an Array of keys, or multiple keys. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + ascending(...keys: Array): this; + /** + * Sorts the results in ascending order by the given key, + * but can also add secondary sort descriptors without overwriting _order. + * + * @param {(string|string[])} keys The key to order by, which is a + * string of comma separated values, or an Array of keys, or multiple keys. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + addAscending(...keys: Array): this; + /** + * Sorts the results in descending order by the given key. + * + * @param {(string|string[])} keys The key to order by, which is a + * string of comma separated values, or an Array of keys, or multiple keys. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + descending(...keys: Array): this; + /** + * Sorts the results in descending order by the given key, + * but can also add secondary sort descriptors without overwriting _order. + * + * @param {(string|string[])} keys The key to order by, which is a + * string of comma separated values, or an Array of keys, or multiple keys. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + addDescending(...keys: Array): this; + /** + * Sets the number of results to skip before returning any results. + * This is useful for pagination. + * Default is to skip zero results. + * + * @param {number} n the number of results to skip. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + skip(n: number): this; + /** + * Sets the limit of the number of results to return. The default limit is 100. + * + * @param {number} n the number of results to limit to. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + limit(n: number): this; + /** + * Sets the flag to include with response the total number of objects satisfying this query, + * despite limits/skip. Might be useful for pagination. + * Note that result of this query will be wrapped as an object with + * `results`: holding {ParseObject} array and `count`: integer holding total number + * + * @param {boolean} includeCount false - disable, true - enable. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + withCount(includeCount?: boolean): this; + /** + * Includes nested Parse.Objects for the provided key. You can use dot + * notation to specify which fields in the included object are also fetched. + * + * You can include all nested Parse.Objects by passing in '*'. + * Requires Parse Server 3.0.0+ + *
    query.include('*');
    + * + * @param {...string|Array} keys The name(s) of the key(s) to include. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + include(...keys: Array>): this; + /** + * Includes all nested Parse.Objects one level deep. + * + * Requires Parse Server 3.0.0+ + * + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + includeAll(): this; + /** + * Restricts the fields of the returned Parse.Objects to include only the + * provided keys. If this is called multiple times, then all of the keys + * specified in each of the calls will be included. + * + * @param {...string|Array} keys The name(s) of the key(s) to include. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + select(...keys: Array>): this; + /** + * Restricts the fields of the returned Parse.Objects to all keys except the + * provided keys. Exclude takes precedence over select and include. + * + * Requires Parse Server 3.6.0+ + * + * @param {...string|Array} keys The name(s) of the key(s) to exclude. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + exclude(...keys: Array>): this; + /** + * Restricts live query to trigger only for watched fields. + * + * Requires Parse Server 6.0.0+ + * + * @param {...string|Array} keys The name(s) of the key(s) to watch. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + watch(...keys: Array>): this; + /** + * Changes the read preference that the backend will use when performing the query to the database. + * + * @param {string} readPreference The read preference for the main query. + * @param {string} includeReadPreference The read preference for the queries to include pointers. + * @param {string} subqueryReadPreference The read preference for the sub queries. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + readPreference(readPreference: string, includeReadPreference?: string, subqueryReadPreference?: string): this; + /** + * Subscribe this query to get liveQuery updates + * + * @param {string} sessionToken (optional) Defaults to the currentUser + * @returns {Promise} Returns the liveQuerySubscription, it's an event emitter + * which can be used to get liveQuery updates. + */ + subscribe(sessionToken?: string | null): Promise; + /** + * Constructs a Parse.Query that is the OR of the passed in queries. For + * example: + *
    var compoundQuery = Parse.Query.or(query1, query2, query3);
    + * + * will create a compoundQuery that is an or of the query1, query2, and + * query3. + * + * @param {...Parse.Query} queries The list of queries to OR. + * @static + * @returns {Parse.Query} The query that is the OR of the passed in queries. + */ + static or(...queries: Array): ParseQuery; + /** + * Constructs a Parse.Query that is the AND of the passed in queries. For + * example: + *
    var compoundQuery = Parse.Query.and(query1, query2, query3);
    + * + * will create a compoundQuery that is an and of the query1, query2, and + * query3. + * + * @param {...Parse.Query} queries The list of queries to AND. + * @static + * @returns {Parse.Query} The query that is the AND of the passed in queries. + */ + static and(...queries: Array): ParseQuery; + /** + * Constructs a Parse.Query that is the NOR of the passed in queries. For + * example: + *
    const compoundQuery = Parse.Query.nor(query1, query2, query3);
    + * + * will create a compoundQuery that is a nor of the query1, query2, and + * query3. + * + * @param {...Parse.Query} queries The list of queries to NOR. + * @static + * @returns {Parse.Query} The query that is the NOR of the passed in queries. + */ + static nor(...queries: Array): ParseQuery; + /** + * Change the source of this query to the server. + * + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + fromNetwork(): this; + /** + * Changes the source of this query to all pinned objects. + * + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + fromLocalDatastore(): this; + /** + * Changes the source of this query to the default group of pinned objects. + * + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + fromPin(): this; + /** + * Changes the source of this query to a specific group of pinned objects. + * + * @param {string} name The name of query source. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + fromPinWithName(name?: string | null): this; + /** + * Cancels the current network request (if any is running). + * + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + cancel(): this; + _setRequestTask(options: any): void; + /** + * Sets a comment to the query so that the query + * can be identified when using a the profiler for MongoDB. + * + * @param {string} value a comment can make your profile data easier to interpret and trace. + * @returns {Parse.Query} Returns the query, so you can chain this call. + */ + comment(value: string): this; } export default ParseQuery; diff --git a/types/ParseRelation.d.ts b/types/ParseRelation.d.ts index 5426f7c83..0279112c3 100644 --- a/types/ParseRelation.d.ts +++ b/types/ParseRelation.d.ts @@ -13,44 +13,44 @@ import type ParseQuery from './ParseQuery'; * * @alias Parse.Relation */ -declare class ParseRelation { - parent?: ParseObject; - key?: string; - targetClassName?: string | null; - /** - * @param {Parse.Object} parent The parent of this relation. - * @param {string} key The key for this relation on the parent. - */ - constructor(parent?: ParseObject, key?: string); - _ensureParentAndKey(parent: ParseObject, key: string): void; - /** - * Adds a Parse.Object or an array of Parse.Objects to the relation. - * - * @param {(Parse.Object|Array)} objects The item or items to add. - * @returns {Parse.Object} The parent of the relation. - */ - add(objects: ParseObject | Array): ParseObject; - /** - * Removes a Parse.Object or an array of Parse.Objects from this relation. - * - * @param {(Parse.Object|Array)} objects The item or items to remove. - */ - remove(objects: ParseObject | Array): void; - /** - * Returns a JSON version of the object suitable for saving to disk. - * - * @returns {object} JSON representation of Relation - */ - toJSON(): { - __type: 'Relation'; - className: string | null; - }; - /** - * Returns a Parse.Query that is limited to objects in this - * relation. - * - * @returns {Parse.Query} Relation Query - */ - query(): ParseQuery; +declare class ParseRelation { + parent?: S; + key?: string; + targetClassName?: string | null; + /** + * @param {Parse.Object} parent The parent of this relation. + * @param {string} key The key for this relation on the parent. + */ + constructor(parent?: S, key?: string); + _ensureParentAndKey(parent: S, key: string): void; + /** + * Adds a Parse.Object or an array of Parse.Objects to the relation. + * + * @param {(Parse.Object|Array)} objects The item or items to add. + * @returns {Parse.Object} The parent of the relation. + */ + add(objects: T | T[]): S; + /** + * Removes a Parse.Object or an array of Parse.Objects from this relation. + * + * @param {(Parse.Object|Array)} objects The item or items to remove. + */ + remove(objects: T | T[]): void; + /** + * Returns a JSON version of the object suitable for saving to disk. + * + * @returns {object} JSON representation of Relation + */ + toJSON(): { + __type: 'Relation'; + className: string | null; + }; + /** + * Returns a Parse.Query that is limited to objects in this + * relation. + * + * @returns {Parse.Query} Relation Query + */ + query(): ParseQuery; } export default ParseRelation; diff --git a/types/ParseRole.d.ts b/types/ParseRole.d.ts index 55b255279..9e349a90b 100644 --- a/types/ParseRole.d.ts +++ b/types/ParseRole.d.ts @@ -1,8 +1,9 @@ import ParseACL from './ParseACL'; import ParseError from './ParseError'; -import ParseObject from './ParseObject'; +import ParseObject, { Attributes, SetOptions } from './ParseObject'; import type { AttributeMap } from './ObjectStateMutations'; import type ParseRelation from './ParseRelation'; +import type ParseUser from './ParseUser'; /** * Represents a Role on the Parse server. Roles represent groupings of * Users for the purposes of granting permissions (e.g. specifying an ACL @@ -16,63 +17,63 @@ import type ParseRelation from './ParseRelation'; * @alias Parse.Role * @augments Parse.Object */ -declare class ParseRole extends ParseObject { - /** - * @param {string} name The name of the Role to create. - * @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL. - * A Parse.Role is a local representation of a role persisted to the Parse - * cloud. - */ - constructor(name: string, acl: ParseACL); - /** - * Gets the name of the role. You can alternatively call role.get("name") - * - * @returns {string} the name of the role. - */ - getName(): string | null; - /** - * Sets the name for a role. This value must be set before the role has - * been saved to the server, and cannot be set once the role has been - * saved. - * - *

    - * A role's name can only contain alphanumeric characters, _, -, and - * spaces. - *

    - * - *

    This is equivalent to calling role.set("name", name)

    - * - * @param {string} name The name of the role. - * @param {object} options Standard options object with success and error - * callbacks. - * @returns {(ParseObject|boolean)} true if the set succeeded. - */ - setName(name: string, options?: any): ParseObject | boolean; - /** - * Gets the Parse.Relation for the Parse.Users that are direct - * children of this role. These users are granted any privileges that this - * role has been granted (e.g. read or write access through ACLs). You can - * add or remove users from the role through this relation. - * - *

    This is equivalent to calling role.relation("users")

    - * - * @returns {Parse.Relation} the relation for the users belonging to this - * role. - */ - getUsers(): ParseRelation; - /** - * Gets the Parse.Relation for the Parse.Roles that are direct - * children of this role. These roles' users are granted any privileges that - * this role has been granted (e.g. read or write access through ACLs). You - * can add or remove child roles from this role through this relation. - * - *

    This is equivalent to calling role.relation("roles")

    - * - * @returns {Parse.Relation} the relation for the roles belonging to this - * role. - */ - getRoles(): ParseRelation; - _validateName(newName: any): void; - validate(attrs: AttributeMap, options?: any): ParseError | boolean; +declare class ParseRole extends ParseObject { + /** + * @param {string} name The name of the Role to create. + * @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL. + * A Parse.Role is a local representation of a role persisted to the Parse + * cloud. + */ + constructor(name: string, acl: ParseACL); + /** + * Gets the name of the role. You can alternatively call role.get("name") + * + * @returns {string} the name of the role. + */ + getName(): string | null; + /** + * Sets the name for a role. This value must be set before the role has + * been saved to the server, and cannot be set once the role has been + * saved. + * + *

    + * A role's name can only contain alphanumeric characters, _, -, and + * spaces. + *

    + * + *

    This is equivalent to calling role.set("name", name)

    + * + * @param {string} name The name of the role. + * @param {object} options Standard options object with success and error + * callbacks. + * @returns {Parse.Object} Returns the object, so you can chain this call. + */ + setName(name: string, options?: SetOptions): this; + /** + * Gets the Parse.Relation for the Parse.Users that are direct + * children of this role. These users are granted any privileges that this + * role has been granted (e.g. read or write access through ACLs). You can + * add or remove users from the role through this relation. + * + *

    This is equivalent to calling role.relation("users")

    + * + * @returns {Parse.Relation} the relation for the users belonging to this + * role. + */ + getUsers(): ParseRelation; + /** + * Gets the Parse.Relation for the Parse.Roles that are direct + * children of this role. These roles' users are granted any privileges that + * this role has been granted (e.g. read or write access through ACLs). You + * can add or remove child roles from this role through this relation. + * + *

    This is equivalent to calling role.relation("roles")

    + * + * @returns {Parse.Relation} the relation for the roles belonging to this + * role. + */ + getRoles(): ParseRelation; + _validateName(newName: any): void; + validate(attrs: AttributeMap, options?: any): ParseError | boolean; } export default ParseRole; diff --git a/types/ParseSchema.d.ts b/types/ParseSchema.d.ts index 8285acf4c..2742c599b 100644 --- a/types/ParseSchema.d.ts +++ b/types/ParseSchema.d.ts @@ -1,10 +1,60 @@ +import ParseObject from './ParseObject'; import ParseCLP from './ParseCLP'; +import type ParseGeoPoint from './ParseGeoPoint'; +import type ParseFile from './ParseFile'; +import type ParsePolygon from './ParsePolygon'; +import type ParseRelation from './ParseRelation'; import type { PermissionsMap } from './ParseCLP'; -type FieldOptions = { - required?: boolean; - defaultValue?: any; - targetClass?: string; -}; +import type { Pointer } from './ParseObject'; +type Bytes = string; +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>; +interface FieldOptions { + required?: boolean | undefined; + defaultValue?: T | undefined; + targetClass?: string | undefined; +} +interface Index { + [fieldName: string]: number | string; +} +interface CLPField { + '*'?: boolean | undefined; + requiresAuthentication?: boolean | undefined; + [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; + readUserFields?: string[] | undefined; + writeUserFields?: string[] | undefined; + protectedFields?: { + [userIdOrRoleName: string]: string[]; + }; +} +interface RestSchema { + className: string; + fields: { + [key: string]: { + type: string; + targetClass?: string; + required?: boolean; + defaultValue?: string; + }; + }; + classLevelPermissions: CLP; + indexes?: { + [key: string]: { + [key: string]: any; + }; + }; +} /** * A Parse.Schema object is for handling schema data from Parse. *

    All the schemas methods require MasterKey. @@ -22,217 +72,215 @@ type FieldOptions = { * * @alias Parse.Schema */ -declare class ParseSchema { - className: string; - _fields: { - [key: string]: any; - }; - _indexes: { - [key: string]: any; - }; - _clp: { - [key: string]: any; - }; - /** - * @param {string} className Parse Class string. - */ - constructor(className: string); - /** - * Static method to get all schemas - * - * @returns {Promise} A promise that is resolved with the result when - * the query completes. - */ - static all(): Promise; - /** - * Get the Schema from Parse - * - * @returns {Promise} A promise that is resolved with the result when - * the query completes. - */ - get(): Promise<{ - results: ParseSchema[]; - }>; - /** - * Create a new Schema on Parse - * - * @returns {Promise} A promise that is resolved with the result when - * the query completes. - */ - save(): Promise; - /** - * Update a Schema on Parse - * - * @returns {Promise} A promise that is resolved with the result when - * the query completes. - */ - update(): Promise; - /** - * Removing a Schema from Parse - * Can only be used on Schema without objects - * - * @returns {Promise} A promise that is resolved with the result when - * the query completes. - */ - delete(): Promise; - /** - * Removes all objects from a Schema (class) in Parse. - * EXERCISE CAUTION, running this will delete all objects for this schema and cannot be reversed - * - * @returns {Promise} A promise that is resolved with the result when - * the query completes. - */ - purge(): Promise; - /** - * Assert if ClassName has been filled - * - * @private - */ - assertClassName(): void; - /** - * Sets Class Level Permissions when creating / updating a Schema. - * EXERCISE CAUTION, running this may override CLP for this schema and cannot be reversed - * - * @param {object | Parse.CLP} clp Class Level Permissions - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - setCLP(clp: PermissionsMap | ParseCLP): this; - /** - * Adding a Field to Create / Update a Schema - * - * @param {string} name Name of the field that will be created on Parse - * @param {string} type Can be a (String|Number|Boolean|Date|Parse.File|Parse.GeoPoint|Array|Object|Pointer|Parse.Relation) - * @param {object} options - * Valid options are:

      - *
    • required: If field is not set, save operation fails (Requires Parse Server 3.7.0+) - *
    • defaultValue: If field is not set, a default value is selected (Requires Parse Server 3.7.0+) - *
    • targetClass: Required if type is Pointer or Parse.Relation - *
    - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addField(name: string, type: string, options?: FieldOptions): this; - /** - * Adding an Index to Create / Update a Schema - * - * @param {string} name Name of the index - * @param {object} index { field: value } - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - * - *
    -   * schema.addIndex('index_name', { 'field': 1 });
    -   * 
    - */ - addIndex(name: string, index: any): this; - /** - * Adding String Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addString(name: string, options: FieldOptions): this; - /** - * Adding Number Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addNumber(name: string, options: FieldOptions): this; - /** - * Adding Boolean Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addBoolean(name: string, options: FieldOptions): this; - /** - * Adding Bytes Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addBytes(name: string, options: FieldOptions): this; - /** - * Adding Date Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addDate(name: string, options: FieldOptions): this; - /** - * Adding File Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addFile(name: string, options: FieldOptions): this; - /** - * Adding GeoPoint Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addGeoPoint(name: string, options: FieldOptions): this; - /** - * Adding Polygon Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addPolygon(name: string, options: FieldOptions): this; - /** - * Adding Array Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addArray(name: string, options: FieldOptions): this; - /** - * Adding Object Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addObject(name: string, options: FieldOptions): this; - /** - * Adding Pointer Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {string} targetClass Name of the target Pointer Class - * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addPointer(name: string, targetClass: string, options?: FieldOptions): this; - /** - * Adding Relation Field - * - * @param {string} name Name of the field that will be created on Parse - * @param {string} targetClass Name of the target Pointer Class - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - addRelation(name: string, targetClass: string): this; - /** - * Deleting a Field to Update on a Schema - * - * @param {string} name Name of the field - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - deleteField(name: string): this; - /** - * Deleting an Index to Update on a Schema - * - * @param {string} name Name of the field - * @returns {Parse.Schema} Returns the schema, so you can chain this call. - */ - deleteIndex(name: string): this; +declare class ParseSchema { + className: string; + _fields: { + [key: string]: any; + }; + _indexes: { + [key: string]: any; + }; + _clp: { + [key: string]: any; + }; + /** + * @param {string} className Parse Class string. + */ + constructor(className: string); + /** + * Static method to get all schemas + * + * @returns {Promise} A promise that is resolved with the result when + * the query completes. + */ + static all(): Promise; + /** + * Get the Schema from Parse + * + * @returns {Promise} A promise that is resolved with the result when + * the query completes. + */ + get(): Promise; + /** + * Create a new Schema on Parse + * + * @returns {Promise} A promise that is resolved with the result when + * the query completes. + */ + save(): Promise; + /** + * Update a Schema on Parse + * + * @returns {Promise} A promise that is resolved with the result when + * the query completes. + */ + update(): Promise; + /** + * Removing a Schema from Parse + * Can only be used on Schema without objects + * + * @returns {Promise} A promise that is resolved with the result when + * the query completes. + */ + delete(): Promise; + /** + * Removes all objects from a Schema (class) in Parse. + * EXERCISE CAUTION, running this will delete all objects for this schema and cannot be reversed + * + * @returns {Promise} A promise that is resolved with the result when + * the query completes. + */ + purge(): Promise; + /** + * Assert if ClassName has been filled + * + * @private + */ + assertClassName(): void; + /** + * Sets Class Level Permissions when creating / updating a Schema. + * EXERCISE CAUTION, running this may override CLP for this schema and cannot be reversed + * + * @param {object | Parse.CLP} clp Class Level Permissions + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + setCLP(clp: PermissionsMap | ParseCLP): this; + /** + * Adding a Field to Create / Update a Schema + * + * @param {string} name Name of the field that will be created on Parse + * @param {string} type Can be a (String|Number|Boolean|Date|Parse.File|Parse.GeoPoint|Array|Object|Pointer|Parse.Relation) + * @param {object} options + * Valid options are:
      + *
    • required: If field is not set, save operation fails (Requires Parse Server 3.7.0+) + *
    • defaultValue: If field is not set, a default value is selected (Requires Parse Server 3.7.0+) + *
    • targetClass: Required if type is Pointer or Parse.Relation + *
    + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addField(name: string, type?: T, options?: FieldOptions): this; + /** + * Adding an Index to Create / Update a Schema + * + * @param {string} name Name of the index + * @param {object} index { field: value } + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + * + *
    +     * schema.addIndex('index_name', { 'field': 1 });
    +     * 
    + */ + addIndex(name: string, index: Index): this; + /** + * Adding String Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addString(name: AttrType, options?: FieldOptions): this; + /** + * Adding Number Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addNumber(name: AttrType, options?: FieldOptions): this; + /** + * Adding Boolean Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addBoolean(name: AttrType, options?: FieldOptions): this; + /** + * Adding Bytes Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addBytes(name: AttrType, options?: FieldOptions): this; + /** + * Adding Date Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addDate(name: AttrType, options?: FieldOptions): this; + /** + * Adding File Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addFile(name: AttrType, options?: FieldOptions): this; + /** + * Adding GeoPoint Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addGeoPoint(name: AttrType, options?: FieldOptions): this; + /** + * Adding Polygon Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addPolygon(name: AttrType, options?: FieldOptions): this; + /** + * Adding Array Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addArray(name: AttrType, options?: FieldOptions): this; + /** + * Adding Object Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addObject(name: AttrType, options?: FieldOptions): this; + /** + * Adding Pointer Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {string} targetClass Name of the target Pointer Class + * @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField} + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addPointer(name: AttrType, targetClass: string, options?: FieldOptions): this; + /** + * Adding Relation Field + * + * @param {string} name Name of the field that will be created on Parse + * @param {string} targetClass Name of the target Pointer Class + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + addRelation(name: AttrType, targetClass: string): this; + /** + * Deleting a Field to Update on a Schema + * + * @param {string} name Name of the field + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + deleteField(name: string): this; + /** + * Deleting an Index to Update on a Schema + * + * @param {string} name Name of the field + * @returns {Parse.Schema} Returns the schema, so you can chain this call. + */ + deleteIndex(name: string): this; } export default ParseSchema; diff --git a/types/ParseSession.d.ts b/types/ParseSession.d.ts index 307bac6cb..2ca37b979 100644 --- a/types/ParseSession.d.ts +++ b/types/ParseSession.d.ts @@ -1,4 +1,4 @@ -import ParseObject from './ParseObject'; +import ParseObject, { Attributes } from './ParseObject'; import type { FullOptions } from './RESTController'; /** *

    A Parse.Session object is a local representation of a revocable session. @@ -8,38 +8,38 @@ import type { FullOptions } from './RESTController'; * @alias Parse.Session * @augments Parse.Object */ -declare class ParseSession extends ParseObject { - /** - * @param {object} attributes The initial set of data to store in the user. - */ - constructor(attributes?: any); - /** - * Returns the session token string. - * - * @returns {string} - */ - getSessionToken(): string; - static readOnlyAttributes(): string[]; - /** - * Retrieves the Session object for the currently logged in session. - * - * @param {object} options useMasterKey - * @static - * @returns {Promise} A promise that is resolved with the Parse.Session - * object after it has been fetched. If there is no current user, the - * promise will be rejected. - */ - static current(options: FullOptions): Promise; - /** - * Determines whether the current session token is revocable. - * This method is useful for migrating Express.js or Node.js web apps to - * use revocable sessions. If you are migrating an app that uses the Parse - * SDK in the browser only, please use Parse.User.enableRevocableSession() - * instead, so that sessions can be automatically upgraded. - * - * @static - * @returns {boolean} - */ - static isCurrentSessionRevocable(): boolean; +declare class ParseSession extends ParseObject { + /** + * @param {object} attributes The initial set of data to store in the user. + */ + constructor(attributes?: T); + /** + * Returns the session token string. + * + * @returns {string} + */ + getSessionToken(): string; + static readOnlyAttributes(): string[]; + /** + * Retrieves the Session object for the currently logged in session. + * + * @param {object} options useMasterKey + * @static + * @returns {Promise} A promise that is resolved with the Parse.Session + * object after it has been fetched. If there is no current user, the + * promise will be rejected. + */ + static current(options?: FullOptions): Promise; + /** + * Determines whether the current session token is revocable. + * This method is useful for migrating Express.js or Node.js web apps to + * use revocable sessions. If you are migrating an app that uses the Parse + * SDK in the browser only, please use Parse.User.enableRevocableSession() + * instead, so that sessions can be automatically upgraded. + * + * @static + * @returns {boolean} + */ + static isCurrentSessionRevocable(): boolean; } export default ParseSession; diff --git a/types/ParseUser.d.ts b/types/ParseUser.d.ts index 98295d105..dab0212e4 100644 --- a/types/ParseUser.d.ts +++ b/types/ParseUser.d.ts @@ -1,17 +1,16 @@ -import ParseObject from './ParseObject'; -import type { AttributeMap } from './ObjectStateMutations'; +import ParseObject, { Attributes } from './ParseObject'; import type { RequestOptions, FullOptions } from './RESTController'; export type AuthData = { - [key: string]: any; + [key: string]: any; }; -export type AuthProviderType = { - authenticate?(options: { - error?: (provider: AuthProviderType, error: string | any) => void; - success?: (provider: AuthProviderType, result: AuthData) => void; - }): void; - restoreAuthentication(authData: any): boolean; - getAuthType(): string; - deauthenticate?(): void; +export type AuthProvider = { + authenticate?(options: { + error?: (provider: AuthProvider, error: string | any) => void; + success?: (provider: AuthProvider, result: AuthData) => void; + }): void; + restoreAuthentication(authData: any): boolean; + getAuthType(): string; + deauthenticate?(): void; }; /** *

    A Parse.User object is a local representation of a user persisted to the @@ -23,534 +22,496 @@ export type AuthProviderType = { * @alias Parse.User * @augments Parse.Object */ -declare class ParseUser extends ParseObject { - /** - * @param {object} attributes The initial set of data to store in the user. - */ - constructor(attributes?: AttributeMap); - /** - * Request a revocable session token to replace the older style of token. - * - * @param {object} options - * Valid options are:

      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    - * @returns {Promise} A promise that is resolved when the replacement - * token has been fetched. - */ - _upgradeToRevocableSession(options: RequestOptions): Promise; - /** - * Parse allows you to link your users with {@link https://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication 3rd party authentication}, enabling - * your users to sign up or log into your application using their existing identities. - * Since 2.9.0 - * - * @see {@link https://docs.parseplatform.org/js/guide/#linking-users Linking Users} - * @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider} - * @param {object} options - * @param {object} [options.authData] AuthData to link with - *
      - *
    • If provider is string, options is {@link http://docs.parseplatform.org/parse-server/guide/#supported-3rd-party-authentications authData} - *
    • If provider is AuthProvider, options is saveOpts - *
    - * @param {object} saveOpts useMasterKey / sessionToken - * @returns {Promise} A promise that is fulfilled with the user is linked - */ - linkWith( - provider: AuthProviderType, - options: { - authData?: AuthData; - }, - saveOpts?: FullOptions - ): Promise; - /** - * @param provider - * @param options - * @param {object} [options.authData] - * @param saveOpts - * @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} - * @returns {Promise} - */ - _linkWith( - provider: any, - options: { - authData?: AuthData; - }, - saveOpts?: FullOptions - ): Promise; - /** - * Synchronizes auth data for a provider (e.g. puts the access token in the - * right place to be used by the Facebook SDK). - * - * @param provider - */ - _synchronizeAuthData(provider: string | AuthProviderType): void; - /** - * Synchronizes authData for all providers. - */ - _synchronizeAllAuthData(): void; - /** - * Removes null values from authData (which exist temporarily for unlinking) - */ - _cleanupAuthData(): void; - /** - * Unlinks a user from a service. - * - * @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider} - * @param {object} options MasterKey / SessionToken - * @returns {Promise} A promise that is fulfilled when the unlinking - * finishes. - */ - _unlinkFrom(provider: any, options?: FullOptions): Promise; - /** - * Checks whether a user is linked to a service. - * - * @param {object} provider service to link to - * @returns {boolean} true if link was successful - */ - _isLinked(provider: any): boolean; - /** - * Deauthenticates all providers. - */ - _logOutWithAll(): void; - /** - * Deauthenticates a single provider (e.g. removing access tokens from the - * Facebook SDK). - * - * @param {object} provider service to logout of - */ - _logOutWith(provider: any): void; - /** - * Class instance method used to maintain specific keys when a fetch occurs. - * Used to ensure that the session token is not lost. - * - * @returns {object} sessionToken - */ - _preserveFieldsOnFetch(): AttributeMap; - /** - * Returns true if current would return this user. - * - * @returns {boolean} true if user is cached on disk - */ - isCurrent(): boolean; - /** - * Returns true if current would return this user. - * - * @returns {Promise} true if user is cached on disk - */ - isCurrentAsync(): Promise; - stripAnonymity(): void; - restoreAnonimity(anonymousData: any): void; - /** - * Returns get("username"). - * - * @returns {string} - */ - getUsername(): string | null; - /** - * Calls set("username", username, options) and returns the result. - * - * @param {string} username - */ - setUsername(username: string): void; - /** - * Calls set("password", password, options) and returns the result. - * - * @param {string} password User's Password - */ - setPassword(password: string): void; - /** - * Returns get("email"). - * - * @returns {string} User's Email - */ - getEmail(): string | null; - /** - * Calls set("email", email) and returns the result. - * - * @param {string} email - * @returns {boolean} - */ - setEmail(email: string): this; - /** - * Returns the session token for this user, if the user has been logged in, - * or if it is the result of a query with the master key. Otherwise, returns - * undefined. - * - * @returns {string} the session token, or undefined - */ - getSessionToken(): string | null; - /** - * Checks whether this user is the current user and has been authenticated. - * - * @returns {boolean} whether this user is the current user and is logged in. - */ - authenticated(): boolean; - /** - * Signs up a new user. You should call this instead of save for - * new Parse.Users. This will create a new Parse.User on the server, and - * also persist the session on disk so that you can access the user using - * current. - * - *

    A username and password must be set before calling signUp.

    - * - * @param {object} attrs Extra fields to set on the new user, or null. - * @param {object} options - * Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • installationId: the installationId which made the request - *
    • context: A dictionary that is accessible in Cloud Code `beforeLogin` and `afterLogin` triggers. - *
    - * @returns {Promise} A promise that is fulfilled when the signup - * finishes. - */ - signUp( - attrs: AttributeMap, - options?: FullOptions & { - context?: AttributeMap; - } - ): Promise; - /** - * Logs in a Parse.User. On success, this saves the session to disk, - * so you can retrieve the currently logged in user using - * current. - * - *

    A username and password must be set before calling logIn.

    - * - * @param {object} options - * Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    • usePost: Use POST method to make the request (default: true) - *
    • installationId: the installationId which made the request - *
    • context: A dictionary that is accessible in Cloud Code `beforeLogin` and `afterLogin` triggers. - *
    - * @returns {Promise} A promise that is fulfilled with the user when - * the login is complete. - */ - logIn( - options?: FullOptions & { - context?: AttributeMap; - } - ): Promise; - /** - * Wrap the default save behavior with functionality to save to local - * storage if this is current user. - * - * @param {...any} args - * @returns {Promise} - */ - save(...args: Array): Promise; - /** - * Wrap the default destroy behavior with functionality that logs out - * the current user when it is destroyed - * - * @param {...any} args - * @returns {Parse.User} - */ - destroy(...args: Array): Promise; - /** - * Wrap the default fetch behavior with functionality to save to local - * storage if this is current user. - * - * @param {...any} args - * @returns {Parse.User} - */ - fetch(...args: Array): Promise; - /** - * Wrap the default fetchWithInclude behavior with functionality to save to local - * storage if this is current user. - * - * @param {...any} args - * @returns {Parse.User} - */ - fetchWithInclude(...args: Array): Promise; - /** - * Verify whether a given password is the password of the current user. - * - * @param {string} password The password to be verified. - * @param {object} options The options. - * @param {boolean} [options.ignoreEmailVerification] Set to `true` to bypass email verification and verify - * the password regardless of whether the email has been verified. This requires the master key. - * @returns {Promise} A promise that is fulfilled with a user when the password is correct. - */ - verifyPassword(password: string, options?: RequestOptions): Promise; - static readOnlyAttributes(): string[]; - /** - * Adds functionality to the existing Parse.User class. - * - * @param {object} protoProps A set of properties to add to the prototype - * @param {object} classProps A set of static properties to add to the class - * @static - * @returns {Parse.User} The newly extended Parse.User class - */ - static extend( - protoProps: { - [prop: string]: any; - }, - classProps: { - [prop: string]: any; - } - ): typeof ParseUser; - /** - * Retrieves the currently logged in ParseUser with a valid session, - * either from memory or localStorage, if necessary. - * - * @static - * @returns {Parse.Object} The currently logged in Parse.User. - */ - static current(): ParseUser | null; - /** - * Retrieves the currently logged in ParseUser from asynchronous Storage. - * - * @static - * @returns {Promise} A Promise that is resolved with the currently - * logged in Parse User - */ - static currentAsync(): Promise; - /** - * Signs up a new user with a username (or email) and password. - * This will create a new Parse.User on the server, and also persist the - * session in localStorage so that you can access the user using - * {@link #current}. - * - * @param {string} username The username (or email) to sign up with. - * @param {string} password The password to sign up with. - * @param {object} attrs Extra fields to set on the new user. - * @param {object} options - * @static - * @returns {Promise} A promise that is fulfilled with the user when - * the signup completes. - */ - static signUp( - username: string, - password: string, - attrs: AttributeMap, - options?: FullOptions - ): Promise; - /** - * Logs in a user with a username (or email) and password. On success, this - * saves the session to disk, so you can retrieve the currently logged in - * user using current. - * - * @param {string} username The username (or email) to log in with. - * @param {string} password The password to log in with. - * @param {object} options - * @static - * @returns {Promise} A promise that is fulfilled with the user when - * the login completes. - */ - static logIn(username: string, password: string, options?: FullOptions): Promise; - /** - * Logs in a user with a username (or email) and password, and authData. On success, this - * saves the session to disk, so you can retrieve the currently logged in - * user using current. - * - * @param {string} username The username (or email) to log in with. - * @param {string} password The password to log in with. - * @param {object} authData The authData to log in with. - * @param {object} options - * @static - * @returns {Promise} A promise that is fulfilled with the user when - * the login completes. - */ - static logInWithAdditionalAuth( - username: string, - password: string, - authData: AuthData, - options?: FullOptions - ): Promise; - /** - * Logs in a user with an objectId. On success, this saves the session - * to disk, so you can retrieve the currently logged in user using - * current. - * - * @param {string} userId The objectId for the user. - * @static - * @returns {Promise} A promise that is fulfilled with the user when - * the login completes. - */ - static loginAs(userId: string): Promise; - /** - * Logs in a user with a session token. On success, this saves the session - * to disk, so you can retrieve the currently logged in user using - * current. - * - * @param {string} sessionToken The sessionToken to log in with. - * @param {object} options - * @param {boolean} [options.useMasterKey] - * @static - * @returns {Promise} A promise that is fulfilled with the user when - * the login completes. - */ - static become(sessionToken: string, options?: RequestOptions): Promise; - /** - * Retrieves a user with a session token. - * - * @param {string} sessionToken The sessionToken to get user with. - * @param {object} options - * @param {boolean} [options.useMasterKey] - * @static - * @returns {Promise} A promise that is fulfilled with the user is fetched. - */ - static me(sessionToken: string, options?: RequestOptions): Promise; - /** - * Logs in a user with a session token. On success, this saves the session - * to disk, so you can retrieve the currently logged in user using - * current. If there is no session token the user will not logged in. - * - * @param {object} userJSON The JSON map of the User's data - * @static - * @returns {Promise} A promise that is fulfilled with the user when - * the login completes. - */ - static hydrate(userJSON: AttributeMap): Promise; - /** - * Static version of {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} - * - * @param provider - * @param options - * @param {object} [options.authData] - * @param saveOpts - * @static - * @returns {Promise} - */ - static logInWith( - provider: any, - options: { - authData?: AuthData; - }, - saveOpts?: FullOptions - ): Promise; - /** - * Logs out the currently logged in user session. This will remove the - * session from disk, log out of linked services, and future calls to - * current will return null. - * - * @param {object} options - * @static - * @returns {Promise} A promise that is resolved when the session is - * destroyed on the server. - */ - static logOut(options?: RequestOptions): Promise; - /** - * Requests a password reset email to be sent to the specified email address - * associated with the user account. This email allows the user to securely - * reset their password on the Parse site. - * - * @param {string} email The email address associated with the user that - * forgot their password. - * @param {object} options - * Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    - * @static - * @returns {Promise} - */ - static requestPasswordReset(email: string, options?: RequestOptions): Promise; - /** - * Request an email verification. - * - * @param {string} email The email address associated with the user that - * needs to verify their email. - * @param {object} options - * Valid options are:
      - *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to - * be used for this request. - *
    - * @static - * @returns {Promise} - */ - static requestEmailVerification(email: string, options?: RequestOptions): Promise; - /** - * Verify whether a given password is the password of the current user. - * @static - * - * @param {string} username The username of the user whose password should be verified. - * @param {string} password The password to be verified. - * @param {object} options The options. - * @param {boolean} [options.ignoreEmailVerification] Set to `true` to bypass email verification and verify - * the password regardless of whether the email has been verified. This requires the master key. - * @returns {Promise} A promise that is fulfilled with a user when the password is correct. - */ - static verifyPassword( - username: string, - password: string, - options?: RequestOptions - ): Promise; - /** - * Allow someone to define a custom User class without className - * being rewritten to _User. The default behavior is to rewrite - * User to _User for legacy reasons. This allows developers to - * override that behavior. - * - * @param {boolean} isAllowed Whether or not to allow custom User class - * @static - */ - static allowCustomUserClass(isAllowed: boolean): void; - /** - * Allows a legacy application to start using revocable sessions. If the - * current session token is not revocable, a request will be made for a new, - * revocable session. - * It is not necessary to call this method from cloud code unless you are - * handling user signup or login from the server side. In a cloud code call, - * this function will not attempt to upgrade the current token. - * - * @param {object} options - * @static - * @returns {Promise} A promise that is resolved when the process has - * completed. If a replacement session token is requested, the promise - * will be resolved after a new token has been fetched. - */ - static enableRevocableSession(options?: RequestOptions): Promise; - /** - * Enables the use of become or the current user in a server - * environment. These features are disabled by default, since they depend on - * global objects that are not memory-safe for most servers. - * - * @static - */ - static enableUnsafeCurrentUser(): void; - /** - * Disables the use of become or the current user in any environment. - * These features are disabled on servers by default, since they depend on - * global objects that are not memory-safe for most servers. - * - * @static - */ - static disableUnsafeCurrentUser(): void; - /** - * When registering users with {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} a basic auth provider - * is automatically created for you. - * - * For advanced authentication, you can register an Auth provider to - * implement custom authentication, deauthentication. - * - * @param provider - * @see {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider} - * @see {@link https://docs.parseplatform.org/js/guide/#custom-authentication-module Custom Authentication Module} - * @static - */ - static _registerAuthenticationProvider(provider: any): void; - /** - * @param provider - * @param options - * @param {object} [options.authData] - * @param saveOpts - * @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#logInWith logInWith} - * @static - * @returns {Promise} - */ - static _logInWith( - provider: any, - options: { - authData?: AuthData; - }, - saveOpts?: FullOptions - ): Promise; - static _clearCache(): void; - static _setCurrentUserCache(user: ParseUser): void; +declare class ParseUser extends ParseObject { + /** + * @param {object} attributes The initial set of data to store in the user. + */ + constructor(attributes?: T); + /** + * Request a revocable session token to replace the older style of token. + * + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    + * @returns {Promise} A promise that is resolved when the replacement + * token has been fetched. + */ + _upgradeToRevocableSession(options?: RequestOptions): Promise; + /** + * Parse allows you to link your users with {@link https://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication 3rd party authentication}, enabling + * your users to sign up or log into your application using their existing identities. + * Since 2.9.0 + * + * @see {@link https://docs.parseplatform.org/js/guide/#linking-users Linking Users} + * @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider} + * @param {object} options + * @param {object} [options.authData] AuthData to link with + *
      + *
    • If provider is string, options is {@link http://docs.parseplatform.org/parse-server/guide/#supported-3rd-party-authentications authData} + *
    • If provider is AuthProvider, options is saveOpts + *
    + * @param {object} saveOpts useMasterKey / sessionToken + * @returns {Promise} A promise that is fulfilled with the user is linked + */ + linkWith(provider: string | AuthProvider, options: { + authData?: AuthData; + }, saveOpts?: FullOptions): Promise; + /** + * @param provider + * @param options + * @param {object} [options.authData] + * @param saveOpts + * @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} + * @returns {Promise} + */ + _linkWith(provider: any, options: { + authData?: AuthData; + }, saveOpts?: FullOptions): Promise; + /** + * Synchronizes auth data for a provider (e.g. puts the access token in the + * right place to be used by the Facebook SDK). + * + * @param provider + */ + _synchronizeAuthData(provider: string | AuthProvider): void; + /** + * Synchronizes authData for all providers. + */ + _synchronizeAllAuthData(): void; + /** + * Removes null values from authData (which exist temporarily for unlinking) + */ + _cleanupAuthData(): void; + /** + * Unlinks a user from a service. + * + * @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider} + * @param {object} options MasterKey / SessionToken + * @returns {Promise} A promise that is fulfilled when the unlinking + * finishes. + */ + _unlinkFrom(provider: any, options?: FullOptions): Promise; + /** + * Checks whether a user is linked to a service. + * + * @param {object} provider service to link to + * @returns {boolean} true if link was successful + */ + _isLinked(provider: any): boolean; + /** + * Deauthenticates all providers. + */ + _logOutWithAll(): void; + /** + * Deauthenticates a single provider (e.g. removing access tokens from the + * Facebook SDK). + * + * @param {object} provider service to logout of + */ + _logOutWith(provider: any): void; + /** + * Class instance method used to maintain specific keys when a fetch occurs. + * Used to ensure that the session token is not lost. + * + * @returns {object} sessionToken + */ + _preserveFieldsOnFetch(): Attributes; + /** + * Returns true if current would return this user. + * + * @returns {boolean} true if user is cached on disk + */ + isCurrent(): boolean; + /** + * Returns true if current would return this user. + * + * @returns {Promise} true if user is cached on disk + */ + isCurrentAsync(): Promise; + stripAnonymity(): void; + restoreAnonimity(anonymousData: any): void; + /** + * Returns get("username"). + * + * @returns {string} + */ + getUsername(): string | null; + /** + * Calls set("username", username, options) and returns the result. + * + * @param {string} username + */ + setUsername(username: string): void; + /** + * Calls set("password", password, options) and returns the result. + * + * @param {string} password User's Password + */ + setPassword(password: string): void; + /** + * Returns get("email"). + * + * @returns {string} User's Email + */ + getEmail(): string | null; + /** + * Calls set("email", email) and returns the result. + * + * @param {string} email + * @returns {boolean} + */ + setEmail(email: string): this; + /** + * Returns the session token for this user, if the user has been logged in, + * or if it is the result of a query with the master key. Otherwise, returns + * undefined. + * + * @returns {string} the session token, or undefined + */ + getSessionToken(): string | null; + /** + * Checks whether this user is the current user and has been authenticated. + * + * @returns {boolean} whether this user is the current user and is logged in. + */ + authenticated(): boolean; + /** + * Signs up a new user. You should call this instead of save for + * new Parse.Users. This will create a new Parse.User on the server, and + * also persist the session on disk so that you can access the user using + * current. + * + *

    A username and password must be set before calling signUp.

    + * + * @param {object} attrs Extra fields to set on the new user, or null. + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • installationId: the installationId which made the request + *
    • context: A dictionary that is accessible in Cloud Code `beforeLogin` and `afterLogin` triggers. + *
    + * @returns {Promise} A promise that is fulfilled when the signup + * finishes. + */ + signUp(attrs?: Attributes | null, options?: FullOptions & { + context?: Attributes; + }): Promise; + /** + * Logs in a Parse.User. On success, this saves the session to disk, + * so you can retrieve the currently logged in user using + * current. + * + *

    A username and password must be set before calling logIn.

    + * + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    • usePost: Use POST method to make the request (default: true) + *
    • installationId: the installationId which made the request + *
    • context: A dictionary that is accessible in Cloud Code `beforeLogin` and `afterLogin` triggers. + *
    + * @returns {Promise} A promise that is fulfilled with the user when + * the login is complete. + */ + logIn(options?: FullOptions & { + context?: Attributes; + }): Promise; + /** + * Wrap the default save behavior with functionality to save to local + * storage if this is current user. + * + * @param {...any} args + * @returns {Promise} + */ + save(...args: Array): Promise; + /** + * Wrap the default destroy behavior with functionality that logs out + * the current user when it is destroyed + * + * @param {...any} args + * @returns {Parse.User} + */ + destroy(...args: Array): Promise; + /** + * Wrap the default fetch behavior with functionality to save to local + * storage if this is current user. + * + * @param {...any} args + * @returns {Parse.User} + */ + fetch(...args: Array): Promise; + /** + * Wrap the default fetchWithInclude behavior with functionality to save to local + * storage if this is current user. + * + * @param {...any} args + * @returns {Parse.User} + */ + fetchWithInclude(...args: Array): Promise; + /** + * Verify whether a given password is the password of the current user. + * + * @param {string} password The password to be verified. + * @param {object} options The options. + * @param {boolean} [options.ignoreEmailVerification] Set to `true` to bypass email verification and verify + * the password regardless of whether the email has been verified. This requires the master key. + * @returns {Promise} A promise that is fulfilled with a user when the password is correct. + */ + verifyPassword(password: string, options?: RequestOptions): Promise; + static readOnlyAttributes(): string[]; + /** + * Adds functionality to the existing Parse.User class. + * + * @param {object} protoProps A set of properties to add to the prototype + * @param {object} classProps A set of static properties to add to the class + * @static + * @returns {Parse.User} The newly extended Parse.User class + */ + static extend(protoProps: { + [prop: string]: any; + }, classProps: { + [prop: string]: any; + }): typeof ParseUser; + /** + * Retrieves the currently logged in ParseUser with a valid session, + * either from memory or localStorage, if necessary. + * + * @static + * @returns {Parse.User} The currently logged in Parse.User. + */ + static current(): T | null; + /** + * Retrieves the currently logged in ParseUser from asynchronous Storage. + * + * @static + * @returns {Promise} A Promise that is resolved with the currently + * logged in Parse User + */ + static currentAsync(): Promise; + /** + * Signs up a new user with a username (or email) and password. + * This will create a new Parse.User on the server, and also persist the + * session in localStorage so that you can access the user using + * {@link #current}. + * + * @param {string} username The username (or email) to sign up with. + * @param {string} password The password to sign up with. + * @param {object} attrs Extra fields to set on the new user. + * @param {object} options + * @static + * @returns {Promise} A promise that is fulfilled with the user when + * the signup completes. + */ + static signUp(username: string, password: string, attrs: Attributes, options?: FullOptions): Promise; + /** + * Logs in a user with a username (or email) and password. On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {string} username The username (or email) to log in with. + * @param {string} password The password to log in with. + * @param {object} options + * @static + * @returns {Promise} A promise that is fulfilled with the user when + * the login completes. + */ + static logIn(username: string, password: string, options?: FullOptions): Promise; + /** + * Logs in a user with a username (or email) and password, and authData. On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {string} username The username (or email) to log in with. + * @param {string} password The password to log in with. + * @param {object} authData The authData to log in with. + * @param {object} options + * @static + * @returns {Promise} A promise that is fulfilled with the user when + * the login completes. + */ + static logInWithAdditionalAuth(username: string, password: string, authData: AuthData, options?: FullOptions): Promise; + /** + * Logs in a user with an objectId. On success, this saves the session + * to disk, so you can retrieve the currently logged in user using + * current. + * + * @param {string} userId The objectId for the user. + * @static + * @returns {Promise} A promise that is fulfilled with the user when + * the login completes. + */ + static loginAs(userId: string): Promise; + /** + * Logs in a user with a session token. On success, this saves the session + * to disk, so you can retrieve the currently logged in user using + * current. + * + * @param {string} sessionToken The sessionToken to log in with. + * @param {object} options + * @param {boolean} [options.useMasterKey] + * @static + * @returns {Promise} A promise that is fulfilled with the user when + * the login completes. + */ + static become(sessionToken: string, options?: RequestOptions): Promise; + /** + * Retrieves a user with a session token. + * + * @param {string} sessionToken The sessionToken to get user with. + * @param {object} options + * @param {boolean} [options.useMasterKey] + * @static + * @returns {Promise} A promise that is fulfilled with the user is fetched. + */ + static me(sessionToken: string, options?: RequestOptions): Promise; + /** + * Logs in a user with a session token. On success, this saves the session + * to disk, so you can retrieve the currently logged in user using + * current. If there is no session token the user will not logged in. + * + * @param {object} userJSON The JSON map of the User's data + * @static + * @returns {Promise} A promise that is fulfilled with the user when + * the login completes. + */ + static hydrate(userJSON: Attributes): Promise; + /** + * Static version of {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} + * + * @param provider + * @param options + * @param {object} [options.authData] + * @param saveOpts + * @static + * @returns {Promise} + */ + static logInWith(provider: string | AuthProvider, options: { + authData?: AuthData; + }, saveOpts?: FullOptions): Promise; + /** + * Logs out the currently logged in user session. This will remove the + * session from disk, log out of linked services, and future calls to + * current will return null. + * + * @param {object} options + * @static + * @returns {Promise} A promise that is resolved when the session is + * destroyed on the server. + */ + static logOut(options?: RequestOptions): Promise; + /** + * Requests a password reset email to be sent to the specified email address + * associated with the user account. This email allows the user to securely + * reset their password on the Parse site. + * + * @param {string} email The email address associated with the user that + * forgot their password. + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    + * @static + * @returns {Promise} + */ + static requestPasswordReset(email: string, options?: RequestOptions): Promise; + /** + * Request an email verification. + * + * @param {string} email The email address associated with the user that + * needs to verify their email. + * @param {object} options + * Valid options are:
      + *
    • useMasterKey: In Cloud Code and Node only, causes the Master Key to + * be used for this request. + *
    + * @static + * @returns {Promise} + */ + static requestEmailVerification(email: string, options?: RequestOptions): Promise; + /** + * Verify whether a given password is the password of the current user. + * @static + * + * @param {string} username The username of the user whose password should be verified. + * @param {string} password The password to be verified. + * @param {object} options The options. + * @param {boolean} [options.ignoreEmailVerification] Set to `true` to bypass email verification and verify + * the password regardless of whether the email has been verified. This requires the master key. + * @returns {Promise} A promise that is fulfilled with a user when the password is correct. + */ + static verifyPassword(username: string, password: string, options?: RequestOptions): Promise; + /** + * Allow someone to define a custom User class without className + * being rewritten to _User. The default behavior is to rewrite + * User to _User for legacy reasons. This allows developers to + * override that behavior. + * + * @param {boolean} isAllowed Whether or not to allow custom User class + * @static + */ + static allowCustomUserClass(isAllowed: boolean): void; + /** + * Allows a legacy application to start using revocable sessions. If the + * current session token is not revocable, a request will be made for a new, + * revocable session. + * It is not necessary to call this method from cloud code unless you are + * handling user signup or login from the server side. In a cloud code call, + * this function will not attempt to upgrade the current token. + * + * @param {object} options + * @static + * @returns {Promise} A promise that is resolved when the process has + * completed. If a replacement session token is requested, the promise + * will be resolved after a new token has been fetched. + */ + static enableRevocableSession(options?: RequestOptions): Promise; + /** + * Enables the use of become or the current user in a server + * environment. These features are disabled by default, since they depend on + * global objects that are not memory-safe for most servers. + * + * @static + */ + static enableUnsafeCurrentUser(): void; + /** + * Disables the use of become or the current user in any environment. + * These features are disabled on servers by default, since they depend on + * global objects that are not memory-safe for most servers. + * + * @static + */ + static disableUnsafeCurrentUser(): void; + /** + * When registering users with {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} a basic auth provider + * is automatically created for you. + * + * For advanced authentication, you can register an Auth provider to + * implement custom authentication, deauthentication. + * + * @param provider + * @see {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider} + * @see {@link https://docs.parseplatform.org/js/guide/#custom-authentication-module Custom Authentication Module} + * @static + */ + static _registerAuthenticationProvider(provider: any): void; + /** + * @param provider + * @param options + * @param {object} [options.authData] + * @param saveOpts + * @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#logInWith logInWith} + * @static + * @returns {Promise} + */ + static _logInWith(provider: any, options: { + authData?: AuthData; + }, saveOpts?: FullOptions): Promise>; + static _clearCache(): void; + static _setCurrentUserCache(user: ParseUser): void; } export default ParseUser; diff --git a/types/Push.d.ts b/types/Push.d.ts index 24bf5214c..6c65516b6 100644 --- a/types/Push.d.ts +++ b/types/Push.d.ts @@ -3,10 +3,12 @@ import type ParseObject from './ParseObject'; import type { WhereClause } from './ParseQuery'; import type { FullOptions } from './RESTController'; export type PushData = { - where?: WhereClause | ParseQuery; - push_time?: Date | string; - expiration_time?: Date | string; - expiration_interval?: number; + where?: WhereClause | ParseQuery; + push_time?: Date | string; + expiration_time?: Date | string; + expiration_interval?: number; + data?: any; + channels?: string[]; }; /** * Contains functions to deal with Push in Parse. @@ -57,7 +59,4 @@ export declare function send(data: PushData, options?: FullOptions): Promise * @returns {Parse.Object} Status of Push. */ -export declare function getPushStatus( - pushStatusId: string, - options?: FullOptions -): Promise; +export declare function getPushStatus(pushStatusId: string, options?: FullOptions): Promise; diff --git a/types/RESTController.d.ts b/types/RESTController.d.ts index ad7416781..47863f391 100644 --- a/types/RESTController.d.ts +++ b/types/RESTController.d.ts @@ -1,41 +1,35 @@ export type RequestOptions = { - useMasterKey?: boolean; - sessionToken?: string; - installationId?: string; - returnStatus?: boolean; - batchSize?: number; - include?: any; - progress?: any; - context?: any; - usePost?: boolean; - ignoreEmailVerification?: boolean; - transaction?: boolean; + useMasterKey?: boolean; + useMaintenanceKey?: boolean; + sessionToken?: string; + installationId?: string; + returnStatus?: boolean; + batchSize?: number; + include?: any; + progress?: any; + context?: any; + usePost?: boolean; + ignoreEmailVerification?: boolean; + transaction?: boolean; }; export type FullOptions = { - success?: any; - error?: any; - useMasterKey?: boolean; - sessionToken?: string; - installationId?: string; - progress?: any; - usePost?: boolean; + success?: any; + error?: any; + useMasterKey?: boolean; + useMaintenanceKey?: boolean; + sessionToken?: string; + installationId?: string; + progress?: any; + usePost?: boolean; }; declare const RESTController: { - ajax( - method: string, - url: string, - data: any, - headers?: any, - options?: FullOptions - ): - | (Promise & { + ajax(method: string, url: string, data: any, headers?: any, options?: FullOptions): (Promise & { resolve: (res: any) => void; reject: (err: any) => void; - }) - | Promise; - request(method: string, path: string, data: any, options?: RequestOptions): Promise; - handleError(response: any): Promise; - _setXHR(xhr: any): void; - _getXHR(): any; + }) | Promise; + request(method: string, path: string, data: any, options?: RequestOptions): Promise; + handleError(response: any): Promise; + _setXHR(xhr: any): void; + _getXHR(): any; }; export default RESTController; diff --git a/types/SingleInstanceStateController.d.ts b/types/SingleInstanceStateController.d.ts index 1b93bff1f..09743b91e 100644 --- a/types/SingleInstanceStateController.d.ts +++ b/types/SingleInstanceStateController.d.ts @@ -17,11 +17,8 @@ export declare function estimateAttributes(obj: ParseObject): AttributeMap; export declare function commitServerChanges(obj: ParseObject, changes: AttributeMap): void; export declare function enqueueTask(obj: ParseObject, task: () => Promise): Promise; export declare function clearAllState(): void; -export declare function duplicateState( - source: { +export declare function duplicateState(source: { id: string; - }, - dest: { +}, dest: { id: string; - } -): void; +}): void; diff --git a/types/Socket.weapp.d.ts b/types/Socket.weapp.d.ts index de97ad385..c2d9d015f 100644 --- a/types/Socket.weapp.d.ts +++ b/types/Socket.weapp.d.ts @@ -1,10 +1,10 @@ declare class SocketWeapp { - onopen: () => void; - onmessage: () => void; - onclose: () => void; - onerror: () => void; - constructor(serverURL: any); - send(data: any): void; - close(): void; + onopen: () => void; + onmessage: () => void; + onclose: () => void; + onerror: () => void; + constructor(serverURL: any); + send(data: any): void; + close(): void; } export default SocketWeapp; diff --git a/types/Storage.d.ts b/types/Storage.d.ts index 4ecb4c2f2..08d6483df 100644 --- a/types/Storage.d.ts +++ b/types/Storage.d.ts @@ -1,14 +1,14 @@ declare const Storage: { - async(): boolean; - getItem(path: string): string | null; - getItemAsync(path: string): Promise; - setItem(path: string, value: string): void; - setItemAsync(path: string, value: string): Promise; - removeItem(path: string): void; - removeItemAsync(path: string): Promise; - getAllKeys(): Array; - getAllKeysAsync(): Promise>; - generatePath(path: string): string; - _clear(): void; + async(): boolean; + getItem(path: string): string | null; + getItemAsync(path: string): Promise; + setItem(path: string, value: string): void; + setItemAsync(path: string, value: string): Promise; + removeItem(path: string): void; + removeItemAsync(path: string): Promise; + getAllKeys(): Array; + getAllKeysAsync(): Promise>; + generatePath(path: string): string; + _clear(): void; }; export default Storage; diff --git a/types/StorageController.browser.d.ts b/types/StorageController.browser.d.ts index 1d736ba19..00976a894 100644 --- a/types/StorageController.browser.d.ts +++ b/types/StorageController.browser.d.ts @@ -1,9 +1,9 @@ declare const StorageController: { - async: number; - getItem(path: string): string | null; - setItem(path: string, value: string): void; - removeItem(path: string): void; - getAllKeys(): string[]; - clear(): void; + async: number; + getItem(path: string): string | null; + setItem(path: string, value: string): void; + removeItem(path: string): void; + getAllKeys(): string[]; + clear(): void; }; export default StorageController; diff --git a/types/StorageController.default.d.ts b/types/StorageController.default.d.ts index 1d736ba19..00976a894 100644 --- a/types/StorageController.default.d.ts +++ b/types/StorageController.default.d.ts @@ -1,9 +1,9 @@ declare const StorageController: { - async: number; - getItem(path: string): string | null; - setItem(path: string, value: string): void; - removeItem(path: string): void; - getAllKeys(): string[]; - clear(): void; + async: number; + getItem(path: string): string | null; + setItem(path: string, value: string): void; + removeItem(path: string): void; + getAllKeys(): string[]; + clear(): void; }; export default StorageController; diff --git a/types/StorageController.react-native.d.ts b/types/StorageController.react-native.d.ts index 538a3654a..a95ebbf73 100644 --- a/types/StorageController.react-native.d.ts +++ b/types/StorageController.react-native.d.ts @@ -1,11 +1,11 @@ declare const StorageController: { - async: number; - getItemAsync(path: string): Promise; - setItemAsync(path: string, value: string): Promise; - removeItemAsync(path: string): Promise; - getAllKeysAsync(): Promise; - multiGet(keys: Array): Promise; - multiRemove(keys: Array): Promise>; - clear(): Promise; + async: number; + getItemAsync(path: string): Promise; + setItemAsync(path: string, value: string): Promise; + removeItemAsync(path: string): Promise; + getAllKeysAsync(): Promise; + multiGet(keys: Array): Promise; + multiRemove(keys: Array): Promise>; + clear(): Promise; }; export default StorageController; diff --git a/types/StorageController.weapp.d.ts b/types/StorageController.weapp.d.ts index 267cbfe81..29408def5 100644 --- a/types/StorageController.weapp.d.ts +++ b/types/StorageController.weapp.d.ts @@ -1,9 +1,9 @@ declare const StorageController: { - async: number; - getItem(path: string): string | null; - setItem(path: string, value: string): void; - removeItem(path: string): void; - getAllKeys(): any; - clear(): void; + async: number; + getItem(path: string): string | null; + setItem(path: string, value: string): void; + removeItem(path: string): void; + getAllKeys(): any; + clear(): void; }; export default StorageController; diff --git a/types/TaskQueue.d.ts b/types/TaskQueue.d.ts index ff3eed61f..ae7e55fe9 100644 --- a/types/TaskQueue.d.ts +++ b/types/TaskQueue.d.ts @@ -1,11 +1,11 @@ type Task = { - task: () => Promise; - _completion: any; + task: () => Promise; + _completion: any; }; declare class TaskQueue { - queue: Array; - constructor(); - enqueue(task: () => Promise): Promise; - _dequeue(): void; + queue: Array; + constructor(); + enqueue(task: () => Promise): Promise; + _dequeue(): void; } export default TaskQueue; diff --git a/types/Xhr.weapp.d.ts b/types/Xhr.weapp.d.ts index c214a1677..c314abf06 100644 --- a/types/Xhr.weapp.d.ts +++ b/types/Xhr.weapp.d.ts @@ -1,29 +1,29 @@ declare class XhrWeapp { - UNSENT: number; - OPENED: number; - HEADERS_RECEIVED: number; - LOADING: number; - DONE: number; - header: any; - readyState: any; - status: number; - response: string | undefined; - responseType: string; - responseText: string; - responseHeader: any; - method: string; - url: string; - onabort: () => void; - onprogress: () => void; - onerror: () => void; - onreadystatechange: () => void; - requestTask: any; - constructor(); - getAllResponseHeaders(): string; - getResponseHeader(key: any): any; - setRequestHeader(key: any, value: any): void; - open(method: any, url: any): void; - abort(): void; - send(data: any): void; + UNSENT: number; + OPENED: number; + HEADERS_RECEIVED: number; + LOADING: number; + DONE: number; + header: any; + readyState: any; + status: number; + response: string | undefined; + responseType: string; + responseText: string; + responseHeader: any; + method: string; + url: string; + onabort: () => void; + onprogress: () => void; + onerror: () => void; + onreadystatechange: () => void; + requestTask: any; + constructor(); + getAllResponseHeaders(): string; + getResponseHeader(key: any): any; + setRequestHeader(key: any, value: any): void; + open(method: any, url: any): void; + abort(): void; + send(data: any): void; } export default XhrWeapp; diff --git a/types/encode.d.ts b/types/encode.d.ts index 943bcb39d..d63c1e75a 100644 --- a/types/encode.d.ts +++ b/types/encode.d.ts @@ -1,7 +1 @@ -export default function ( - value: any, - disallowObjects?: boolean, - forcePointers?: boolean, - seen?: Array, - offline?: boolean -): any; +export default function (value: any, disallowObjects?: boolean, forcePointers?: boolean, seen?: Array, offline?: boolean): any; diff --git a/types/promiseUtils.d.ts b/types/promiseUtils.d.ts index a0f44e7c1..e652712a0 100644 --- a/types/promiseUtils.d.ts +++ b/types/promiseUtils.d.ts @@ -1,11 +1,9 @@ export declare function resolvingPromise(): Promise & { - resolve: (res: T) => void; - reject: (err: any) => void; + resolve: (res: T) => void; + reject: (err: any) => void; }; -export declare function when(promises: any): - | Promise - | (Promise & { - resolve: (res: any) => void; - reject: (err: any) => void; - }); +export declare function when(promises: any): Promise | (Promise & { + resolve: (res: any) => void; + reject: (err: any) => void; +}); export declare function continueWhile(test: () => any, emitter: () => Promise): any; diff --git a/types/tests.ts b/types/tests.ts index 9ab22a682..38e5a3fe1 100644 --- a/types/tests.ts +++ b/types/tests.ts @@ -3,23 +3,23 @@ import ParseNode from 'parse/node'; import ParseRN from 'parse/react-native'; class GameScore extends Parse.Object { - constructor(options?: any) { - super('GameScore', options); + constructor() { + super('GameScore'); } } class Game extends Parse.Object { - constructor(options?: any) { - super('Game', options); + constructor() { + super('Game'); } } -function test_config() { - Parse.Config.save({ foo: 'bar' }, { foo: true }); - Parse.Config.get({ useMasterKey: true }); +async function test_config() { + await Parse.Config.save({ foo: 'bar' }, { foo: true }); + await Parse.Config.get({ useMasterKey: true }); } -function test_object() { +async function test_object() { const game = new Game(); game .save(null, { @@ -27,15 +27,17 @@ function test_object() { sessionToken: 'sometoken', cascadeSave: false, }) - .then(result => result); + .then(result => result) + .catch(error => error); - if (!game.isNew()) { - } - - if (game.toPointer().className !== 'Game') { - } + // $ExpectType boolean + game.isNew(); + // $ExpectType Pointer + game.toPointer(); + // $ExpectType string + game.toPointer().className; - game.fetch({}); + await game.fetch({}); // Create a new instance of that class. const gameScore = new GameScore(); @@ -49,11 +51,9 @@ function test_object() { level: '10', difficult: 15, }); - - const score = gameScore.get('score'); - const playerName = gameScore.get('playerName'); - const cheatMode = gameScore.get('cheatMode'); - + gameScore.get('score'); + gameScore.get('playerName'); + gameScore.get('cheatMode'); gameScore.increment('score'); gameScore.addUnique('skills', 'flying'); gameScore.addUnique('skills', 'kungfu'); @@ -62,24 +62,23 @@ function test_object() { gameScore.remove('skills', 'flying'); gameScore.removeAll('skills', ['kungFu']); game.set('gameScore', gameScore); - - const gameCopy = Game.fromJSON(JSON.parse(JSON.stringify(game)), true); + // $ExpectType ParseObject + Game.fromJSON(JSON.parse(JSON.stringify(game)), true); const object = new Parse.Object('TestObject'); object.equals(gameScore); - object.fetchWithInclude(['key1', 'key2']); + await object.fetchWithInclude(['key1', 'key2']); } function test_errors() { - try { - throw new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'sdfds'); - } catch (error) { - if (error.code !== 1) { - } - } + const error = new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'sdfds'); + // $ExpectType number + error.code; + // $ExpectType string + error.message; } -function test_query() { +async function test_query() { const gameScore = new GameScore(); const query = new Parse.Query(GameScore); @@ -91,8 +90,8 @@ function test_query() { diacriticSensitive: true, }); query.greaterThan('playerAge', 18); - query.eachBatch(objs => Promise.resolve(), { batchSize: 10 }); - query.each(score => Promise.resolve()); + await query.eachBatch(objs => {}, { batchSize: 10 }); + await query.each(score => {}); query.hint('_id_'); query.explain(true); query.limit(10); @@ -143,21 +142,23 @@ function test_query() { query.equalTo('score', gameScore); query.exists('score'); query.include('score'); + query.include('score', 'team'); query.include(['score.team']); + query.include('*'); query.includeAll(); query.sortByTextScore(); // Find objects that match the aggregation pipeline - query.aggregate({ + await query.aggregate({ group: { objectId: '$name', }, }); - query.aggregate({ + await query.aggregate({ count: 'total', }); - query.aggregate({ + await query.aggregate({ lookup: { from: 'Collection', foreignField: 'id', @@ -165,7 +166,7 @@ function test_query() { as: 'result', }, }); - query.aggregate({ + await query.aggregate({ lookup: { from: 'Target', let: { foo: 'bar', baz: 123 }, @@ -174,7 +175,7 @@ function test_query() { }, }); - query.aggregate({ + await query.aggregate({ graphLookup: { from: 'Target', connectFromField: 'objectId', @@ -183,7 +184,7 @@ function test_query() { }, }); - query.aggregate({ + await query.aggregate({ facet: { foo: [ { @@ -200,11 +201,11 @@ function test_query() { }, }); - query.aggregate({ + await query.aggregate({ unwind: '$field', }); - query.aggregate({ + await query.aggregate({ unwind: { path: '$field', includeArrayIndex: 'newIndex', @@ -213,7 +214,7 @@ function test_query() { }); // Find objects with distinct key - query.distinct('name'); + await query.distinct('name'); const testQuery = Parse.Query.or(query, query); } @@ -259,57 +260,57 @@ async function test_query_promise() { async function test_live_query() { const subscription = await new Parse.Query('Test').subscribe(); - subscription.on('close', object => { - // $ExpectType Object + subscription.on('close', (object: Parse.Object) => { + // $ExpectType ParseObject object; }); - subscription.on('create', object => { - // $ExpectType Object + subscription.on('create', (object: Parse.Object) => { + // $ExpectType ParseObject object; }); - subscription.on('delete', object => { - // $ExpectType Object + subscription.on('delete', (object: Parse.Object) => { + // $ExpectType ParseObject object; }); - subscription.on('enter', object => { - // $ExpectType Object + subscription.on('enter', (object: Parse.Object) => { + // $ExpectType ParseObject object; }); - subscription.on('leave', object => { - // $ExpectType Object + subscription.on('leave', (object: Parse.Object) => { + // $ExpectType ParseObject object; }); - subscription.on('open', object => { - // $ExpectType Object + subscription.on('open', (object: Parse.Object) => { + // $ExpectType ParseObject object; }); - subscription.on('update', object => { - // $ExpectType Object + subscription.on('update', (object: Parse.Object) => { + // $ExpectType ParseObject object; }); } -function test_anonymous_utils() { +async function test_anonymous_utils() { // $ExpectType boolean Parse.AnonymousUtils.isLinked(new Parse.User()); - // $ExpectType Promise> - Parse.AnonymousUtils.link(new Parse.User(), { useMasterKey: true, sessionToken: '' }); - // $ExpectType Promise> - Parse.AnonymousUtils.logIn({ useMasterKey: true, sessionToken: '' }); + // $ExpectType ParseUser + await Parse.AnonymousUtils.link(new Parse.User(), { useMasterKey: true, sessionToken: '' }); + // $ExpectType ParseUser + await Parse.AnonymousUtils.logIn({ useMasterKey: true, sessionToken: '' }); } function return_a_query(): Parse.Query { return new Parse.Query(Game); } -function test_each() { - new Parse.Query(Game).each(game => { +async function test_each() { + await new Parse.Query(Game).each(game => { // $ExpectType Game game; }); } -function test_file() { +async function test_file() { const base64 = 'V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE='; let file = new Parse.File('myfile.txt', { base64 }); @@ -323,9 +324,9 @@ function test_file() { const src = file.url(); const secure = file.url({ forceSecure: true }); - file.save(); + await file.save(); file.cancel(); - file.destroy(); + await file.destroy(); } function test_file_tags_and_metadata() { @@ -335,15 +336,13 @@ function test_file_tags_and_metadata() { file.addTag('labes', 'one'); file.setMetadata({ contentType: 'plain/text', contentLength: 579 }); file.addMetadata('author', 'John Doe'); - - const tags = file.tags(); - const ownerId = tags['ownerId']; - - const metadata = file.metadata(); - const contentType = metadata['contentType']; + // $ExpectType Record + file.tags(); + // $ExpectType Record + file.metadata(); } -function test_analytics() { +async function test_analytics() { const dimensions = { // Define ranges to bucket data points into meaningful segments priceRange: '1000-1500', @@ -353,10 +352,10 @@ function test_analytics() { dayType: 'weekday', }; // Send the dimensions to Parse along with the 'search' event - Parse.Analytics.track('search', dimensions); + await Parse.Analytics.track('search', dimensions); const codeString = '404'; - Parse.Analytics.track('error', { code: codeString }); + await Parse.Analytics.track('error', { code: codeString }); } function test_relation() { @@ -367,7 +366,8 @@ 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]); @@ -375,12 +375,12 @@ function test_relation() { new Parse.User().relation('games').remove([game1, game2]); } -function test_user() { +async function test_user() { const user = new Parse.User(); user.set('username', 'my name'); user.set('password', 'my pass'); user.set('email', 'email@example.com'); - user.signUp(null, { useMasterKey: true }); + await user.signUp(null, { useMasterKey: true }); const anotherUser: Parse.User = Parse.User.fromJSON({}); anotherUser.set('email', 'email@example.com'); @@ -391,11 +391,11 @@ async function test_user_currentAsync() { if (asyncUser) { asyncUser.set('email', 'email@example.com'); } else if (asyncUser === null) { - Parse.User.logIn('email@example.com', 'my pass'); + await Parse.User.logIn('email@example.com', 'my pass'); } } -function test_user_acl_roles() { +async function test_user_acl_roles() { const user = new Parse.User(); user.set('username', 'my name'); user.set('password', 'my pass'); @@ -411,41 +411,51 @@ function test_user_acl_roles() { // show the signup or login page } - Parse.User.become('session-token-here').then( - user => { - // The current user is now set to user. - }, - error => { - // The token could not be validated. - } - ); + Parse.User.become('session-token-here') + .then( + user => { + // The current user is now set to user. + }, + error => { + // The token could not be validated. + } + ) + .catch(error => error); - Parse.User.hydrate({}).then( - user => { - // The current user is now set to user. - }, - error => { - // The token could not be validated. - } - ); + Parse.User.hydrate({}) + .then( + user => { + // The current user is now set to user. + }, + error => { + // The token could not be validated. + } + ) + .catch(error => error); const game = new Game(); game.set('gameScore', new GameScore()); game.setACL(new Parse.ACL(Parse.User.current())); - game.save().then((game: Game) => {}); - game.save(null, { useMasterKey: true }); - game.save({ score: '10' }, { useMasterKey: true }).then( - game => { - // Update game then revert it to the last saved state. - game.set('score', '20'); - game.revert('score'); - game.revert('score', 'ACL'); - game.revert(); - }, - error => { - // The save failed - } - ); + game + .save() + .then((game: Game) => {}) + .catch(error => error); + await game.save(null, { useMasterKey: true }); + game + .save({ score: '10' }, { useMasterKey: true }) + .then( + game => { + // Update game then revert it to the last saved state. + game.set('score', '20'); + game.revert('score'); + game.revert('score', 'ACL'); + game.revert(); + }, + error => { + // The save failed + } + ) + .catch(error => error); const groupACL = new Parse.ACL(); @@ -460,36 +470,42 @@ function test_user_acl_roles() { game.setACL(groupACL); - Parse.User.requestPasswordReset('email@example.com').then( - data => { - // The current user is now set to user. - }, - error => { - // The token could not be validated. - } - ); + Parse.User.requestPasswordReset('email@example.com') + .then( + data => { + // The current user is now set to user. + }, + error => { + // The token could not be validated. + } + ) + .catch(error => error); - Parse.User.requestEmailVerification('email@example.com').then( - data => { - // The current user is now set to user. - }, - error => { - // The token could not be validated. - } - ); + Parse.User.requestEmailVerification('email@example.com') + .then( + data => { + // The current user is now set to user. + }, + error => { + // The token could not be validated. + } + ) + .catch(error => error); // By specifying no write privileges for the ACL, we can ensure the role cannot be altered. const role = new Parse.Role('Administrator', groupACL); role.getUsers().add(userList[0]); role.getRoles().add(role); - role.save(); + await role.save(); - Parse.User.logOut().then(data => { - // logged out - }); + await Parse.User.logOut() + .then(data => { + // logged out + }) + .catch(error => error); } -function test_facebook_util() { +async function test_facebook_util() { Parse.FacebookUtils.init({ appId: 'YOUR_APP_ID', // Facebook App ID channelUrl: '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File @@ -497,7 +513,7 @@ function test_facebook_util() { xfbml: true, // parse XFBML }); - Parse.FacebookUtils.logIn(null, { + await Parse.FacebookUtils.logIn(null, { success: (user: Parse.User) => { if (!user.existed()) { alert('User signed up and logged in through Facebook!'); @@ -513,7 +529,7 @@ function test_facebook_util() { const user = Parse.User.current()!; if (!Parse.FacebookUtils.isLinked(user)) { - Parse.FacebookUtils.link(user, null, { + await Parse.FacebookUtils.link(user, null, { success: (user: any) => { alert('Woohoo, user logged in with Facebook!'); }, @@ -523,7 +539,7 @@ function test_facebook_util() { }); } - Parse.FacebookUtils.unlink(user, { + await Parse.FacebookUtils.unlink(user, { success: (user: Parse.User) => { alert('The user is no longer associated with their Facebook account.'); }, @@ -531,240 +547,183 @@ function test_facebook_util() { } async function test_cloud_functions() { - Parse.Cloud.run( - 'hello', - {}, - { - success: (result: any) => { - // result - }, - error: (error: any) => {}, - } - ); - // $ExpectType any await Parse.Cloud.run('SomeFunction'); - // $ExpectType any await Parse.Cloud.run('SomeFunction', { something: 'whatever' }); - // $ExpectType any await Parse.Cloud.run('SomeFunction', null, { useMasterKey: true }); - // ExpectType boolean await Parse.Cloud.run<() => boolean>('SomeFunction'); - // $ExpectType boolean await Parse.Cloud.run<() => boolean>('SomeFunction', null); - // $ExpectType boolean await Parse.Cloud.run<() => boolean>('SomeFunction', null, { useMasterKey: true }); - // $ExpectType number await Parse.Cloud.run<(params: { paramA: string }) => number>('SomeFunction', { paramA: 'hello', }); - - // @ts-expect-error + // $ExpectError await Parse.Cloud.run<(params: { paramA: string }) => number>('SomeFunction'); - await Parse.Cloud.run<(params: { paramA: string }) => number>('SomeFunction', { - // @ts-expect-error + // $ExpectError paramZ: 'hello', }); - - // @ts-expect-error + // $ExpectError await Parse.Cloud.run<(params: { paramA: string }) => number>('SomeFunction', null, { useMasterKey: true, }); - - // @ts-expect-error + // $ExpectError await Parse.Cloud.run<(params: string) => any>('SomeFunction', 'hello'); - - Parse.Cloud.afterDelete('MyCustomClass', (request: Parse.Cloud.AfterDeleteRequest) => { - // result - }); - - Parse.Cloud.afterSave('MyCustomClass', (request: Parse.Cloud.AfterSaveRequest) => { - if (!request.context) { - throw new Error('Request context should be defined'); - } - // result - }); - - Parse.Cloud.beforeDelete('MyCustomClass', (request: Parse.Cloud.BeforeDeleteRequest) => { - // result - }); - - Parse.Cloud.beforeDelete('MyCustomClass', async (request: Parse.Cloud.BeforeDeleteRequest) => { - // result - }); - - interface BeforeSaveObject { - immutable: boolean; - } - - Parse.Cloud.beforeSave('MyCustomClass', async request => { - if (request.object.isNew()) { - if (!request.object.has('immutable')) throw new Error('Field immutable is required'); - } else { - const original = request.original; - if (original == null) { - // When the object is not new, request.original must be defined - throw new Error('Original must me defined for an existing object'); - } - - if (original.get('immutable') !== request.object.get('immutable')) { - throw new Error('This field cannot be changed'); - } - } - if (!request.context) { - throw new Error('Request context should be defined'); - } - }); - - Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => { - const query = request.query; // the Parse.Query - const user = request.user; // the user - const isMaster = request.master; // if the query is run with masterKey - const isCount = request.count; // if the query is a count operation (available on parse-server 2.4.0 or up) - const isGet = request.isGet; // if the query is a get operation - - // All possible read preferences - request.readPreference = Parse.Cloud.ReadPreferenceOption.Primary; - request.readPreference = Parse.Cloud.ReadPreferenceOption.PrimaryPreferred; - request.readPreference = Parse.Cloud.ReadPreferenceOption.Secondary; - request.readPreference = Parse.Cloud.ReadPreferenceOption.SecondaryPreferred; - request.readPreference = Parse.Cloud.ReadPreferenceOption.Nearest; - }); - - Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => { - const query = request.query; // the Parse.Query - - return new Parse.Query('QueryMe!'); - }); - - Parse.Cloud.beforeFind('MyCustomClass', async (request: Parse.Cloud.BeforeFindRequest) => { - const query = request.query; // the Parse.Query - - return new Parse.Query('QueryMe, IN THE FUTURE!'); - }); - - Parse.Cloud.afterFind('MyCustomClass', async (request: Parse.Cloud.AfterFindRequest) => { - return new Parse.Object('MyCustomClass'); - }); - - Parse.Cloud.beforeLogin((request: Parse.Cloud.TriggerRequest) => { - return Promise.resolve(); - }); - - Parse.Cloud.afterLogin((request: Parse.Cloud.TriggerRequest) => { - return Promise.resolve(); - }); - - Parse.Cloud.afterLogout((request: Parse.Cloud.TriggerRequest) => { - return Promise.resolve(); - }); - - Parse.Cloud.beforeSaveFile((request: Parse.Cloud.FileTriggerRequest) => { - return Promise.resolve(new Parse.File('myFile.txt', { base64: '' })); - }); - - Parse.Cloud.beforeSaveFile((request: Parse.Cloud.FileTriggerRequest) => {}); - - Parse.Cloud.beforeDeleteFile((request: Parse.Cloud.FileTriggerRequest) => {}); - - Parse.Cloud.afterDeleteFile((request: Parse.Cloud.FileTriggerRequest) => {}); - - Parse.Cloud.define('AFunc', (request: Parse.Cloud.FunctionRequest) => { - return 'Some result'; - }); - - Parse.Cloud.define( - 'AFunc', - (request: Parse.Cloud.FunctionRequest) => { - return 'Some result'; - }, - { - requireUser: true, - requireMaster: true, - validateMasterKey: true, - skipWithMasterKey: true, - requireAnyUserRoles: ['a'], - requireAllUserRoles: ['a'], - fields: { - name: { - type: String, - constant: true, - default: true, - options: [], - error: 'invalid field.', - }, - }, - requireUserKeys: { - name: { - type: String, - constant: true, - default: true, - options: [], - error: 'invalid field.', - }, - }, - } - ); - - Parse.Cloud.define('AFunc', request => { - // $ExpectType Params - request.params; - - // $ExpectType any - request.params.anything; - }); - - Parse.Cloud.define<() => void>('AFunc', request => { - // $ExpectType {} - request.params; - }); - - Parse.Cloud.define<(params: { something: string }) => number>('AFunc', request => { - // $ExpectType { something: string; } - request.params; - - // @ts-expect-error - request.params.somethingElse; - - return 123; - }); - - // @ts-expect-error - Parse.Cloud.define('AFunc'); - - // @ts-expect-error - Parse.Cloud.define<() => string>('AFunc', () => 123); - - // @ts-expect-error - Parse.Cloud.define<(params: string) => number>('AFunc', () => 123); - - Parse.Cloud.job('AJob', (request: Parse.Cloud.JobRequest) => { - request.message('Message to associate with this job run'); - }); - - Parse.Cloud.startJob('AJob', {}).then(v => v); - - Parse.Cloud.getJobStatus('AJob').then(v => v); - - Parse.Cloud.getJobsData().then(v => v); + // Parse.Cloud.afterDelete('MyCustomClass', (request: Parse.Cloud.AfterDeleteRequest) => { + // // result + // }); + // Parse.Cloud.afterSave('MyCustomClass', (request: Parse.Cloud.AfterSaveRequest) => { + // if (!request.context) { + // throw new Error('Request context should be defined'); + // } + // // result + // }); + // Parse.Cloud.beforeDelete('MyCustomClass', (request: Parse.Cloud.BeforeDeleteRequest) => { + // // result + // }); + // Parse.Cloud.beforeDelete('MyCustomClass', async (request: Parse.Cloud.BeforeDeleteRequest) => { + // // result + // }); + // interface BeforeSaveObject { + // immutable: boolean; + // } + // Parse.Cloud.beforeSave('MyCustomClass', request => { + // if (request.object.isNew()) { + // if (!request.object.has('immutable')) throw new Error('Field immutable is required'); + // } else { + // const original = request.original; + // if (original == null) { + // // When the object is not new, request.original must be defined + // throw new Error('Original must me defined for an existing object'); + // } + // if (original.get('immutable') !== request.object.get('immutable')) { + // throw new Error('This field cannot be changed'); + // } + // } + // if (!request.context) { + // throw new Error('Request context should be defined'); + // } + // }); + // Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => { + // const query = request.query; // the Parse.Query + // const user = request.user; // the user + // const isMaster = request.master; // if the query is run with masterKey + // const isCount = request.count; // if the query is a count operation (available on parse-server 2.4.0 or up) + // const isGet = request.isGet; // if the query is a get operation + // // All possible read preferences + // request.readPreference = Parse.Cloud.ReadPreferenceOption.Primary; + // request.readPreference = Parse.Cloud.ReadPreferenceOption.PrimaryPreferred; + // request.readPreference = Parse.Cloud.ReadPreferenceOption.Secondary; + // request.readPreference = Parse.Cloud.ReadPreferenceOption.SecondaryPreferred; + // request.readPreference = Parse.Cloud.ReadPreferenceOption.Nearest; + // }); + // Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => { + // const query = request.query; // the Parse.Query + // return new Parse.Query('QueryMe!'); + // }); + // Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => { + // const query = request.query; // the Parse.Query + // return new Parse.Query('QueryMe, IN THE FUTURE!'); + // }); + // Parse.Cloud.afterFind('MyCustomClass', (request: Parse.Cloud.AfterFindRequest) => { + // return new Parse.Object('MyCustomClass'); + // }); + // Parse.Cloud.beforeLogin((request: Parse.Cloud.TriggerRequest) => { + // return Promise.resolve(); + // }); + // Parse.Cloud.afterLogin((request: Parse.Cloud.TriggerRequest) => { + // return Promise.resolve(); + // }); + // Parse.Cloud.afterLogout((request: Parse.Cloud.TriggerRequest) => { + // return Promise.resolve(); + // }); + // Parse.Cloud.beforeSaveFile((request: Parse.Cloud.FileTriggerRequest) => { + // return Promise.resolve(new Parse.File('myFile.txt', { base64: '' })); + // }); + // Parse.Cloud.beforeSaveFile((request: Parse.Cloud.FileTriggerRequest) => {}); + // Parse.Cloud.beforeDeleteFile((request: Parse.Cloud.FileTriggerRequest) => {}); + // Parse.Cloud.afterDeleteFile((request: Parse.Cloud.FileTriggerRequest) => {}); + // Parse.Cloud.define('AFunc', (request: Parse.Cloud.FunctionRequest) => { + // return 'Some result'; + // }); + // Parse.Cloud.define( + // 'AFunc', + // (request: Parse.Cloud.FunctionRequest) => { + // return 'Some result'; + // }, + // { + // requireUser: true, + // requireMaster: true, + // validateMasterKey: true, + // skipWithMasterKey: true, + // requireAnyUserRoles: ['a'], + // requireAllUserRoles: ['a'], + // fields: { + // name: { + // type: String, + // constant: true, + // default: true, + // options: [], + // error: 'invalid field.', + // }, + // }, + // requireUserKeys: { + // name: { + // type: String, + // constant: true, + // default: true, + // options: [], + // error: 'invalid field.', + // }, + // }, + // } + // ); + // Parse.Cloud.define('AFunc', request => { + // // $ExpectType Params + // request.params; + // // $ExpectType any + // request.params.anything; + // }); + // Parse.Cloud.define<() => void>('AFunc', request => { + // // $ExpectType {} + // request.params; + // }); + // Parse.Cloud.define<(params: { something: string }) => number>('AFunc', request => { + // // $ExpectType { something: string; } + // request.params; + // // $ExpectError + // request.params.somethingElse; + // return 123; + // }); + // // $ExpectError + // Parse.Cloud.define('AFunc'); + // // $ExpectError + // Parse.Cloud.define<() => string>('AFunc', () => 123); + // // $ExpectError + // Parse.Cloud.define<(params: string) => number>('AFunc', () => 123); + // Parse.Cloud.job('AJob', (request: Parse.Cloud.JobRequest) => { + // request.message('Message to associate with this job run'); + // }); + await Parse.Cloud.startJob('AJob', {}).then(v => v); + await Parse.Cloud.getJobStatus('AJob').then(v => v); + await Parse.Cloud.getJobsData().then(v => v); } class PlaceObject extends Parse.Object {} function test_geo_points() { let point = new Parse.GeoPoint(); - // @ts-expect-error + // $ExpectError point = new Parse.GeoPoint('40.0'); - // @ts-expect-error + // $ExpectType ParseGeoPoint point = new Parse.GeoPoint(40.0); - // @ts-expect-error + // $ExpectError point = new Parse.GeoPoint([40.0, -30.0, 20.0]); point = new Parse.GeoPoint([40.0, -30.0]); point = new Parse.GeoPoint(40.0, -30.0); @@ -788,11 +747,14 @@ function test_geo_points() { const query2 = new Parse.Query(PlaceObject); query2.withinGeoBox('location', southwestOfSF, northeastOfSF); - const query3 = new Parse.Query('PlaceObject').find().then((o: Parse.Object[]) => {}); + const query3 = new Parse.Query('PlaceObject') + .find() + .then((o: Parse.Object[]) => {}) + .catch(error => error); } -function test_push() { - Parse.Push.send( +async function test_push() { + await Parse.Push.send( { channels: ['Gia nts', 'Mets'], data: { @@ -812,7 +774,7 @@ function test_push() { const query = new Parse.Query(Parse.Installation); query.equalTo('injuryReports', true); - Parse.Push.send( + await Parse.Push.send( { where: query, // Set our Installation query data: { @@ -830,22 +792,22 @@ function test_push() { ); } -function test_batch_operations() { +async function test_batch_operations() { const game1 = new Game(); const game2 = new Game(); const games = [game1, game2]; // Master key - Parse.Object.saveAll(games, { useMasterKey: true }); - Parse.Object.destroyAll(games, { useMasterKey: true }); - Parse.Object.fetchAll(games, { useMasterKey: true }); - Parse.Object.fetchAllIfNeeded(games, { useMasterKey: true }); + await Parse.Object.saveAll(games, { useMasterKey: true }); + await Parse.Object.destroyAll(games, { useMasterKey: true }); + await Parse.Object.fetchAll(games, { useMasterKey: true }); + await Parse.Object.fetchAllIfNeeded(games, { useMasterKey: true }); // Session token - Parse.Object.saveAll(games, { sessionToken: '' }); - Parse.Object.destroyAll(games, { sessionToken: '' }); - Parse.Object.fetchAll(games, { sessionToken: '' }); - Parse.Object.fetchAllIfNeeded(games, { sessionToken: '' }); + await Parse.Object.saveAll(games, { sessionToken: '' }); + await Parse.Object.destroyAll(games, { sessionToken: '' }); + await Parse.Object.fetchAll(games, { sessionToken: '' }); + await Parse.Object.fetchAllIfNeeded(games, { sessionToken: '' }); } async function test_query_subscribe() { @@ -867,7 +829,7 @@ async function test_query_subscribe() { }); // unsubscribe - subscription.unsubscribe(); + await subscription.unsubscribe(); } function test_serverURL() { @@ -912,9 +874,10 @@ async function test_local_datastore() { await Parse.Object.unPinAllWithName(name, [obj]); await Parse.Object.unPinAllObjects(); await Parse.Object.unPinAllObjectsWithName(name); - - const flag = Parse.isLocalDatastoreEnabled(); - const LDS = await Parse.dumpLocalDatastore(); + // $ExpectType boolean + Parse.isLocalDatastoreEnabled(); + // $ExpectType any + await Parse.dumpLocalDatastore(); const query = new Parse.Query('TestObject'); query.fromPin(); @@ -937,7 +900,7 @@ async function test_cancel_query() { await obj.save(); const query = new Parse.Query('TestObject'); - query.fromNetwork().find(); + await query.fromNetwork().find(); query.cancel(); } @@ -973,7 +936,7 @@ async function test_schema( schema.addArray('arrayField'); schema.addArray('arrayField', { defaultValue: [1, 2, 3, 4] }); - // @ts-expect-error + // $ExpectError schema.addArray('arrayField', { defaultValue: notArray }); /** @@ -983,52 +946,52 @@ async function test_schema( schema.addField('defaultFieldString', 'String', { defaultValue: anyField }); schema.addField('defaultFieldString', 'Number'); schema.addField('defaultFieldString', 'Relation'); - // @ts-expect-error + // $ExpectError schema.addField('defaultFieldString', 'String', 'Invalid Options'); schema.addString('field'); schema.addString('field', { defaultValue: 'some string', required: true }); - // @ts-expect-error + // $ExpectError schema.addString('field', { defaultValue: notString }); schema.addNumber('field'); schema.addNumber('field', { defaultValue: 0, required: true }); - // @ts-expect-error + // $ExpectError schema.addNumber('field', { defaultValue: notNumber }); schema.addBoolean('field'); schema.addBoolean('field', { defaultValue: true, required: true }); - // @ts-expect-error + // $ExpectError schema.addBoolean('field', { defaultValue: notboolean }); schema.addDate('field'); schema.addDate('field', { defaultValue: new Date(), required: true }); - // @ts-expect-error + // $ExpectError schema.addDate('field', { defaultValue: notDate }); schema.addFile('field'); schema.addFile('field', { defaultValue: new Parse.File('myfile', []), required: true }); - // @ts-expect-error + // $ExpectError schema.addFile('field', { defaultValue: notFile }); schema.addGeoPoint('field'); schema.addGeoPoint('field', { defaultValue: new Parse.GeoPoint(), required: true }); - // @ts-expect-error + // $ExpectError schema.addGeoPoint('field', { defaultValue: notGeopoint }); schema.addPolygon('field'); schema.addPolygon('field', { defaultValue: new Parse.Polygon([]), required: true }); - // @ts-expect-error + // $ExpectError schema.addPolygon('field', { defaultValue: notPolygon }); schema.addObject('field'); schema.addObject('field', { defaultValue: {}, required: true }); schema.addObject('field', { defaultValue: { abc: 'def' } }); - // @ts-expect-error + // $ExpectError schema.addObject('field', { defaultValue: notObject }); schema.addPointer('field', 'SomeClass'); - // @ts-expect-error + // $ExpectError schema.addPointer('field'); /** * @todo Infer defaultValue type from targetClass @@ -1037,29 +1000,29 @@ async function test_schema( defaultValue: new Parse.User().toPointer(), required: true, }); - // @ts-expect-error + // $ExpectError schema.addPointer('field', { defaultValue: notPointer }); schema.addRelation('field', 'SomeClass'); - // @ts-expect-error + // $ExpectError schema.addRelation('field'); - // @ts-expect-error + // $ExpectError schema.addRelation('field', 'SomeClass', 'anything'); schema.addIndex('testIndex', { stringField: 'text' }); schema.addIndex('testIndex', { stringField: 1 }); schema.addIndex('testIndex', { stringField: -1 }); - // @ts-expect-error + // $ExpectError schema.addIndex('testIndex', { stringField: true }); schema.deleteField('defaultFieldString'); schema.deleteIndex('testIndex'); - schema.delete().then(results => {}); + await schema.delete(); // $ExpectType RestSchema await schema.get(); - schema.purge().then(results => {}); - schema.save().then(results => {}); - schema.update().then(results => {}); + await schema.purge(); + await schema.save(); + await schema.update(); function testGenericType() { interface iTestAttributes { @@ -1090,52 +1053,55 @@ async function test_schema( schema.addRelation('relationField', 'FooClass'); schema.addString('stringField'); - // @ts-expect-error + // $ExpectError schema.addArray('wrong'); - // @ts-expect-error + // $ExpectError schema.addBoolean('wrong'); - // @ts-expect-error + // $ExpectError schema.addDate('wrong'); - // @ts-expect-error + // $ExpectError schema.addFile('wrong'); - // @ts-expect-error + // $ExpectError schema.addGeoPoint('wrong'); - // @ts-expect-error + // $ExpectError schema.addNumber('wrong'); - // @ts-expect-error + // $ExpectError schema.addObject('wrong'); - // @ts-expect-error + // $ExpectError schema.addPointer('wrong', 'FooClass'); - // @ts-expect-error + // $ExpectError schema.addPolygon('wrong'); - // @ts-expect-error + // $ExpectError schema.addRelation('wrong', 'FooClass'); - // @ts-expect-error + // $ExpectError schema.addString('wrong'); } } function testObject() { function testConstructor() { - // $ExpectType Object + // $ExpectType ParseObject new Parse.Object(); - // $ExpectType Object + // $ExpectType ParseObject new Parse.Object('TestObject'); - // $ExpectType Object<{ example: number; }> + // $ExpectType ParseObject<{ example: number; }> new Parse.Object('TestObject', { example: 100 }); - // $ExpectType Object<{ example: boolean; }> + // $ExpectType ParseObject<{ example: boolean; }> new Parse.Object<{ example: boolean }>('TestObject', { example: true }); - // $ExpectType Object<{ example: string; }> + // $ExpectType ParseObject<{ example: string; }> new Parse.Object('TestObject', { example: 'hello' }, { ignoreValidation: true }); - // @ts-expect-error + // $ExpectType ParseObject<{ example: string; }> new Parse.Object<{ example: string }>('TestObject'); - // @ts-expect-error + // $ExpectType ParseObject<{ example: number; }> + new Parse.Object<{ example: number }>('TestObject', { example: 100 }); + + // $ExpectError new Parse.Object<{ example: boolean }>('TestObject', { example: 'hello' }); } @@ -1144,16 +1110,16 @@ function testObject() { objUntyped: Parse.Object, objTyped: Parse.Object<{ example: string }> ) { - // $ExpectType Object[] + // $ExpectType ParseObject[] await Parse.Object.saveAll([objUntyped]); - // $ExpectType Object<{ example: string; }>[] + // $ExpectType ParseObject<{ example: string; }>[] await Parse.Object.saveAll([objTyped]); - // $ExpectType [Object, Object<{ example: string; }>] + // $ExpectType [ParseObject, ParseObject<{ example: string; }>] await Parse.Object.saveAll<[typeof objUntyped, typeof objTyped]>([objUntyped, objTyped]); - // @ts-expect-error + // $ExpectError await Parse.Object.saveAll([123]); } } @@ -1165,7 +1131,7 @@ function testObject() { // $ExpectType string objTyped.attributes.example; - // @ts-expect-error + // $ExpectError objTyped.attributes.other; } @@ -1173,19 +1139,19 @@ function testObject() { objUntyped: Parse.Object, objTyped: Parse.Object<{ stringList: string[]; thing: boolean }> ) { - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.add('whatever', 'hello'); - // $ExpectType false | Object<{ stringList: string[]; thing: boolean; }> + // $ExpectType ParseObject<{ stringList: string[]; thing: boolean; }> objTyped.add('stringList', 'hello'); - // @ts-expect-error + // $ExpectError objTyped.add('stringList', 100); - // @ts-expect-error + // $ExpectError objTyped.add('thing', true); - // @ts-expect-error + // $ExpectError objTyped.add('whatever', 'hello'); } @@ -1193,19 +1159,19 @@ function testObject() { objUntyped: Parse.Object, objTyped: Parse.Object<{ stringList: string[]; thing: boolean }> ) { - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.addAll('whatever', ['hello', 100]); - // $ExpectType false | Object<{ stringList: string[]; thing: boolean; }> + // $ExpectType ParseObject<{ stringList: string[]; thing: boolean; }> objTyped.addAll('stringList', ['hello']); - // @ts-expect-error + // $ExpectError objTyped.addAll('stringList', [100]); - // @ts-expect-error + // $ExpectError objTyped.addAll('thing', [true]); - // @ts-expect-error + // $ExpectError objTyped.addAll('whatever', ['hello']); } @@ -1213,19 +1179,19 @@ function testObject() { objUntyped: Parse.Object, objTyped: Parse.Object<{ stringList: string[]; thing: boolean }> ) { - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.addAllUnique('whatever', ['hello', 100]); - // $ExpectType false | Object<{ stringList: string[]; thing: boolean; }> + // $ExpectType ParseObject<{ stringList: string[]; thing: boolean; }> objTyped.addAllUnique('stringList', ['hello']); - // @ts-expect-error + // $ExpectError objTyped.addAllUnique('stringList', [100]); - // @ts-expect-error + // $ExpectError objTyped.addAllUnique('thing', [true]); - // @ts-expect-error + // $ExpectError objTyped.addAllUnique('whatever', ['hello']); } @@ -1233,19 +1199,19 @@ function testObject() { objUntyped: Parse.Object, objTyped: Parse.Object<{ stringList: string[]; thing: boolean }> ) { - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.addUnique('whatever', 'hello'); - // $ExpectType false | Object<{ stringList: string[]; thing: boolean; }> + // $ExpectType ParseObject<{ stringList: string[]; thing: boolean; }> objTyped.addUnique('stringList', 'hello'); - // @ts-expect-error + // $ExpectError objTyped.addUnique('stringList', 100); - // @ts-expect-error + // $ExpectError objTyped.addUnique('thing', true); - // @ts-expect-error + // $ExpectError objTyped.addUnique('whatever', 'hello'); } @@ -1262,7 +1228,7 @@ function testObject() { // $ExpectType boolean objTyped.dirty('example'); - // @ts-expect-error + // $ExpectError objTyped.dirty('other'); } @@ -1273,7 +1239,7 @@ function testObject() { // $ExpectType boolean objTyped.equals(objUntyped); - // @ts-expect-error + // $ExpectError objUntyped.equals('blah'); } @@ -1284,49 +1250,49 @@ function testObject() { // $ExpectType string objTyped.escape('example'); - // @ts-expect-error + // $ExpectError objTyped.escape('other'); } - function testFetchWithInclude( + async function testFetchWithInclude( objUntyped: Parse.Object, objTyped: Parse.Object<{ example: string }> ) { - // $ExpectType Promise> - objUntyped.fetchWithInclude('whatever'); + // $ExpectType ParseObject + await objUntyped.fetchWithInclude('whatever'); - // $ExpectType Promise> - objUntyped.fetchWithInclude(['whatever']); + // $ExpectType ParseObject + await objUntyped.fetchWithInclude(['whatever']); - // $ExpectType Promise> - objUntyped.fetchWithInclude([['whatever']]); + // $ExpectType ParseObject + await objUntyped.fetchWithInclude([['whatever']]); - // @ts-expect-error - objUntyped.fetchWithInclude([[['whatever']]]); + // $ExpectError + await objUntyped.fetchWithInclude([[['whatever']]]); - // $ExpectType Promise> - objTyped.fetchWithInclude('example'); + // $ExpectType ParseObject<{ example: string; }> + await objTyped.fetchWithInclude('example'); - // $ExpectType Promise> - objTyped.fetchWithInclude(['example']); + // $ExpectType ParseObject<{ example: string; }> + await objTyped.fetchWithInclude(['example']); - // $ExpectType Promise> - objTyped.fetchWithInclude([['example']]); + // $ExpectType ParseObject<{ example: string; }> + await objTyped.fetchWithInclude([['example']]); - // @ts-expect-error - objTyped.fetchWithInclude([[['example']]]); + // $ExpectError + await objTyped.fetchWithInclude([[['example']]]); - // $ExpectType Promise[]> - Parse.Object.fetchAllIfNeededWithInclude([objTyped], 'example'); + // $ExpectType ParseObject<{ example: string; }>[] + await Parse.Object.fetchAllIfNeededWithInclude([objTyped], 'example'); - // @ts-expect-error - Parse.Object.fetchAllIfNeededWithInclude([objTyped], 'notAnAttribute'); + // $ExpectError + await Parse.Object.fetchAllIfNeededWithInclude([objTyped], 'notAnAttribute'); - // $ExpectType Promise[]> - Parse.Object.fetchAllWithInclude([objTyped], 'example'); + // $ExpectType ParseObject<{ example: string; }>[] + await Parse.Object.fetchAllWithInclude([objTyped], 'example'); - // @ts-expect-error - Parse.Object.fetchAllWithInclude([objTyped], 'notAnAttribute'); + // $ExpectError + await Parse.Object.fetchAllWithInclude([objTyped], 'notAnAttribute'); } function testGet(objUntyped: Parse.Object, objTyped: Parse.Object<{ example: number }>) { @@ -1336,7 +1302,7 @@ function testObject() { // $ExpectType number objTyped.get('example'); - // @ts-expect-error + // $ExpectError objTyped.get('other'); } @@ -1347,66 +1313,66 @@ function testObject() { // $ExpectType boolean objTyped.has('example'); - // @ts-expect-error + // $ExpectError objTyped.has('other'); } function testIncrement(objUntyped: Parse.Object, objTyped: Parse.Object<{ example: number }>) { - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.increment('whatever'); - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.increment('whatever', 10); - // $ExpectType false | Object<{ example: number; }> + // $ExpectType ParseObject<{ example: number; }> objTyped.increment('example'); - // $ExpectType false | Object<{ example: number; }> + // $ExpectType ParseObject<{ example: number; }> objTyped.increment('example', 20); - // @ts-expect-error + // $ExpectError objTyped.increment('example', true); - // @ts-expect-error + // $ExpectError objTyped.increment('other'); } function testDecrement(objUntyped: Parse.Object, objTyped: Parse.Object<{ example: number }>) { - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.decrement('whatever'); - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.decrement('whatever', 10); - // $ExpectType false | Object<{ example: number; }> + // $ExpectType ParseObject<{ example: number; }> objTyped.decrement('example'); - // $ExpectType false | Object<{ example: number; }> + // $ExpectType ParseObject<{ example: number; }> objTyped.decrement('example', 20); - // @ts-expect-error + // $ExpectError objTyped.decrement('example', true); - // @ts-expect-error + // $ExpectError objTyped.decrement('other'); } function testNewInstance(objUntyped: Parse.Object, objTyped: Parse.Object<{ example: number }>) { - // $ExpectType Object + // $ExpectType ParseObject objUntyped.newInstance(); - // $ExpectType Object<{ example: number; }> + // $ExpectType ParseObject<{ example: number; }> objTyped.newInstance(); } function testOp(objUntyped: Parse.Object, objTyped: Parse.Object<{ example: number }>) { - // $ExpectType any + // $ExpectType Op | undefined objUntyped.op('whatever'); - // $ExpectType any + // $ExpectType Op | undefined objTyped.op('example'); - // @ts-expect-error + // $ExpectError objTyped.op('other'); } @@ -1414,16 +1380,16 @@ function testObject() { objUntyped: Parse.Object, objTyped: Parse.Object<{ example: number; rel: Parse.Relation }> ) { - // $ExpectType Relation, Object> + // $ExpectType ParseRelation, ParseObject> objUntyped.relation('whatever'); - // $ExpectType Relation, Object>; }>, Object> + // $ExpectType ParseRelation, ParseObject>; }>, ParseObject> objTyped.relation('rel'); - // @ts-expect-error + // $ExpectError objTyped.relation('example'); - // @ts-expect-error + // $ExpectError objTyped.relation('other'); } @@ -1431,19 +1397,19 @@ function testObject() { objUntyped: Parse.Object, objTyped: Parse.Object<{ stringList: string[]; thing: boolean }> ) { - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.remove('whatever', 'hello'); - // $ExpectType false | Object<{ stringList: string[]; thing: boolean; }> + // $ExpectType ParseObject<{ stringList: string[]; thing: boolean; }> objTyped.remove('stringList', 'hello'); - // @ts-expect-error + // $ExpectError objTyped.remove('stringList', 100); - // @ts-expect-error + // $ExpectError objTyped.remove('thing', true); - // @ts-expect-error + // $ExpectError objTyped.remove('whatever', 'hello'); } @@ -1451,19 +1417,19 @@ function testObject() { objUntyped: Parse.Object, objTyped: Parse.Object<{ stringList: string[]; thing: boolean }> ) { - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.removeAll('whatever', ['hello', 100]); - // $ExpectType false | Object<{ stringList: string[]; thing: boolean; }> + // $ExpectType ParseObject<{ stringList: string[]; thing: boolean; }> objTyped.removeAll('stringList', ['hello']); - // @ts-expect-error + // $ExpectError objTyped.removeAll('stringList', [100]); - // @ts-expect-error + // $ExpectError objTyped.removeAll('thing', [true]); - // @ts-expect-error + // $ExpectError objTyped.removeAll('whatever', ['hello']); } @@ -1483,7 +1449,7 @@ function testObject() { // $ExpectType void objTyped.revert('thingOne', 'thingTwo'); - // @ts-expect-error + // $ExpectError objTyped.revert('other'); } interface ObjectAttributes { @@ -1500,59 +1466,68 @@ function testObject() { objTyped: Parse.Object, objTypedOptional: Parse.Object ) { - // $ExpectType Object + // $ExpectType ParseObject await objUntyped.save({ whatever: 100 }); - // $ExpectType Object + // $ExpectType ParseObject await objUntyped.save('whatever', 100); - // $ExpectType Object + // $ExpectType ParseObject await objTyped.save({ example: true }); - // $ExpectType Object + // $ExpectType ParseObject await objTyped.save({ example: true, someString: 'hello' }); - // @ts-expect-error + // $ExpectError await objTyped.save({ example: 'hello', someString: true }); - // $ExpectType Object + // $ExpectType ParseObject await objTyped.save('example', true); - // @ts-expect-error + // $ExpectError await objTyped.save({ example: 'hello' }); - // @ts-expect-error + // $ExpectError await objTyped.save({ wrongProp: 5 }); - // @ts-expect-error + // $ExpectError await objTyped.save('example', 10); - // @ts-expect-error + // $ExpectError await objTyped.save('wrongProp', true); - // @ts-expect-error + // $ExpectError await objTyped.save({ example: undefined }); - // @ts-expect-error + // $ExpectError await objTyped.save('example', undefined); - // $ExpectType Object + // $ExpectType ParseObject await objTyped.save({}); - // $ExpectType Object + // $ExpectType ParseObject + await objTyped.save(); + + // $ExpectType ParseObject await objTypedOptional.save({ example: undefined }); - // $ExpectType Object + // $ExpectType ParseObject await objTypedOptional.save('example', undefined); - // $ExpectType Object + // $ExpectType ParseObject await objTypedOptional.save({}); - // $ExpectType Object + // $ExpectType ParseObject await objTypedOptional.saveEventually({}); - // $ExpectType Object + // $ExpectType ParseObject await objTypedOptional.destroyEventually({}); + + // $ExpectType ParseObject + await objTypedOptional.saveEventually(); + + // $ExpectType ParseObject + await objTypedOptional.destroyEventually(); } function testSet( @@ -1560,52 +1535,52 @@ function testObject() { objTyped: Parse.Object, objTypedOptional: Parse.Object ) { - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.set('propA', 'some value'); - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.set({ propA: undefined }); - // $ExpectType false | Object + // $ExpectError objTyped.set({ example: false }); - // $ExpectType false | Object + // $ExpectType ParseObject objTyped.set({ example: true, someString: 'abc' }); - // @ts-expect-error + // $ExpectError objTyped.set({ example: 123, someString: 'abc' }); - // $ExpectType false | Object + // $ExpectType ParseObject objTyped.set('example', true); - // @ts-expect-error + // $ExpectError objTyped.set({ example: 100 }); - // @ts-expect-error + // $ExpectError objTyped.set({ other: 'something' }); - // @ts-expect-error + // $ExpectError objTyped.set('example', 100); - // @ts-expect-error + // $ExpectError objTyped.set('other', 100); - // @ts-expect-error + // $ExpectError objTyped.set({ example: undefined }); - // $ExpectType false | Object - objTyped.set({}); + // $ExpectType ParseObject + objTyped.set({}); // Should this error? - // @ts-expect-error - objTyped.set('example', undefined); + // $ExpectType ParseObject + objTyped.set('example', undefined); // Should this error? - // $ExpectType false | Object + // $ExpectType ParseObject objTypedOptional.set({ example: undefined }); - // $ExpectType false | Object + // $ExpectType ParseObject objTypedOptional.set('example', undefined); - // $ExpectType false | Object + // $ExpectType ParseObject objTypedOptional.set({}); } @@ -1670,113 +1645,116 @@ function testObject() { JSONTyped.someParseObjectUntyped; // $ExpectType Pointer | (ToJSON & JSONBaseAttributes) JSONTyped.someParseObjectTyped; - // $ExpectType any + // $ExpectType ByIdMap JSONTyped.someParseACL; - // $ExpectType any + // $ExpectType { __type: string; latitude: number; longitude: number; } JSONTyped.someParseGeoPoint; - // $ExpectType any + // $ExpectType { __type: string; coordinates: Coordinates; } JSONTyped.someParsePolygon; - // $ExpectType any + // $ExpectType { __type: "Relation"; className: string | null; } JSONTyped.someParseRelation; - // $ExpectType { __type: string; name: string; url: string; } + // $ExpectType { __type: "File"; name?: string | undefined; url?: string | undefined; } JSONTyped.someParseFile; } function testUnset(objUntyped: Parse.Object, objTyped: Parse.Object<{ example: string }>) { - // $ExpectType false | Object + // $ExpectType ParseObject objUntyped.unset('whatever'); - // $ExpectType false | Object<{ example: string; }> + // $ExpectType ParseObject<{ example: string; }> objTyped.unset('example'); - // @ts-expect-error + // $ExpectError objTyped.unset('other'); } - function testValidate(obj: Parse.Object<{}>) { + function testValidate(obj: Parse.Object) { // Note: The attributes being validated don't necessarily have to match the current object's attributes - // $ExpectType false | Error + // $ExpectType ParseError | boolean obj.validate({ someAttrToValidate: 'hello' }); } function testNullableArrays(objTyped: Parse.Object<{ stringList?: string[] | null }>) { - // $ExpectType false | Object<{ stringList?: string[] | null | undefined; }> + // $ExpectType ParseObject<{ stringList?: string[] | null | undefined; }> objTyped.add('stringList', 'foo'); - // @ts-expect-error + // $ExpectError objTyped.add('stringList', 4); - // $ExpectType false | Object<{ stringList?: string[] | null | undefined; }> + // $ExpectType ParseObject<{ stringList?: string[] | null | undefined; }> objTyped.addAll('stringList', ['foo']); - // @ts-expect-error + // $ExpectError objTyped.addAll('stringList', [4]); - // $ExpectType false | Object<{ stringList?: string[] | null | undefined; }> + // $ExpectType ParseObject<{ stringList?: string[] | null | undefined; }> objTyped.addAllUnique('stringList', ['foo', 'bar']); - // @ts-expect-error + // $ExpectError objTyped.addAllUnique('stringList', [4]); - // $ExpectType false | Object<{ stringList?: string[] | null | undefined; }> + // $ExpectType ParseObject<{ stringList?: string[] | null | undefined; }> objTyped.addUnique('stringList', 'foo'); - // @ts-expect-error + // $ExpectError objTyped.addUnique('stringList', 4); - // $ExpectType false | Object<{ stringList?: string[] | null | undefined; }> + // $ExpectType ParseObject<{ stringList?: string[] | null | undefined; }> objTyped.remove('stringList', 'bar'); - // @ts-expect-error + // $ExpectError objTyped.remove('stringList', 4); - // $ExpectType false | Object<{ stringList?: string[] | null | undefined; }> + // $ExpectType ParseObject<{ stringList?: string[] | null | undefined; }> objTyped.removeAll('stringList', ['bar']); - // @ts-expect-error + // $ExpectError objTyped.removeAll('stringList', [4]); } } function testInstallation() { function testConstructor() { - // $ExpectType Installation + // $ExpectType ParseInstallation new Parse.Installation(); - // $ExpectType Installation<{ example: number; }> + // $ExpectType ParseInstallation<{ example: number; }> new Parse.Installation({ example: 100 }); - // @ts-expect-error + // $ExpectType ParseInstallation<{ example: number; }> new Parse.Installation<{ example: number }>(); - // @ts-expect-error + // $ExpectType ParseInstallation<{ example: number; }> + new Parse.Installation<{ example: number }>({ example: 100 }); + + // $ExpectError new Parse.Installation<{ example: number }>({ example: 'hello' }); } } function testQuery() { function testConstructor() { - // $ExpectType Query> + // $ExpectType ParseQuery> new Parse.Query('TestObject'); - // $ExpectType Query> + // $ExpectType ParseQuery> new Parse.Query(Parse.Role); - // $ExpectType Query> + // $ExpectType ParseQuery> new Parse.Query(Parse.User); - // $ExpectType Query> + // $ExpectType ParseQuery> new Parse.Query>('TestObject'); - // $ExpectType Query> + // $ExpectType ParseQuery> new Parse.Query>(Parse.Role); - // $ExpectType Query> + // $ExpectType ParseQuery> new Parse.Query>(Parse.User); } - async function testQueryMethodTypes() { + function testQueryMethodTypes() { class AnotherSubClass extends Parse.Object<{ x: any }> { constructor() { super('Another', { x: 'example' }); @@ -1790,250 +1768,272 @@ function testQuery() { }> {} const query = new Parse.Query(MySubClass); - // $ExpectType Query + // $ExpectType ParseQuery query.addAscending(['attribute1', 'attribute2', 'updatedAt']); - // @ts-expect-error + + // $ExpectType ParseQuery + query.addAscending('attribute1', 'attribute2', 'updatedAt'); + + // $ExpectError query.addAscending(['attribute1', 'unexistenProp']); - // $ExpectType Query + // $ExpectType ParseQuery query.addDescending(['attribute1', 'attribute2', 'createdAt']); - // @ts-expect-error + // $ExpectError query.addDescending(['attribute1', 'unexistenProp']); - // $ExpectType Query + // $ExpectType ParseQuery query.ascending(['attribute1', 'attribute2', 'objectId']); - // @ts-expect-error + // $ExpectError query.ascending(['attribute1', 'nonexistentProp']); - // $ExpectType Query + // $ExpectType ParseQuery query.containedBy('attribute1', ['a', 'b', 'c']); - // $ExpectType Query + // $ExpectType ParseQuery query.containedBy('attribute3', ['objectId1', 'objectId2', 'objectId3']); - // @ts-expect-error + // $ExpectError query.containedBy('attribute2', ['a', 'b', 'c']); - // @ts-expect-error + // $ExpectError query.containedBy('attribute1', [1, 2, 3]); - // @ts-expect-error + // $ExpectError query.containedBy('nonexistentProp', ['a', 'b', 'c']); - // $ExpectType Query + // $ExpectType ParseQuery query.containedIn('attribute1', ['a', 'b', 'c']); - // $ExpectType Query + // $ExpectType ParseQuery query.containedIn('attribute3', ['objectId1', 'objectId2', 'objectId3']); - // @ts-expect-error + // $ExpectError query.containedIn('attribute2', ['a', 'b', 'c']); - // @ts-expect-error + // $ExpectError query.containedIn('attribute1', [1, 2, 3]); - // @ts-expect-error + // $ExpectError query.containedIn('nonexistentProp', ['a', 'b', 'c']); - // $ExpectType Query + // $ExpectType ParseQuery query.contains('attribute1', 'a substring'); - // @ts-expect-error + // $ExpectError query.contains('nonexistentProp', 'a substring'); - // $ExpectType Query + // $ExpectType ParseQuery query.containsAll('attribute1', ['a', 'b', 'c']); - // @ts-expect-error + // $ExpectError query.containsAll('nonexistentProp', ['a', 'b', 'c']); - // $ExpectType Query + // $ExpectType ParseQuery query.containsAllStartingWith('attribute1', ['a', 'b', 'c']); - // @ts-expect-error + // $ExpectError query.containsAllStartingWith('nonexistentProp', ['a', 'b', 'c']); - // $ExpectType Query + // $ExpectType ParseQuery query.descending(['attribute1', 'attribute2', 'objectId']); - // @ts-expect-error + // $ExpectError query.descending(['attribute1', 'nonexistentProp']); - // $ExpectType Query + // $ExpectType ParseQuery query.doesNotExist('attribute1'); - // @ts-expect-error + // $ExpectError query.doesNotExist('nonexistentProp'); - // $ExpectType Query + // $ExpectType ParseQuery query.doesNotMatchKeyInQuery('attribute1', 'x', new Parse.Query(AnotherSubClass)); - // @ts-expect-error + // $ExpectError query.doesNotMatchKeyInQuery('unexistenProp', 'x', new Parse.Query(AnotherSubClass)); - // @ts-expect-error + // $ExpectError query.doesNotMatchKeyInQuery('attribute1', 'unknownKey', new Parse.Query(AnotherSubClass)); - // $ExpectType Query + // $ExpectType ParseQuery query.doesNotMatchKeyInQuery('objectId', 'x', new Parse.Query(AnotherSubClass)); - // $ExpectType Query + // $ExpectType ParseQuery query.doesNotMatchKeyInQuery('updatedAt', 'x', new Parse.Query(AnotherSubClass)); - // $ExpectType Query + // $ExpectType ParseQuery query.doesNotMatchQuery('attribute1', new Parse.Query('Example')); - // @ts-expect-error + // $ExpectError query.doesNotMatchQuery('nonexistentProp', new Parse.Query('Example')); - // $ExpectType Query + // $ExpectType ParseQuery query.endsWith('attribute1', 'asuffixstring'); - // @ts-expect-error + // $ExpectError query.endsWith('nonexistentProp', 'asuffixstring'); - // $ExpectType Query + // $ExpectType ParseQuery query.equalTo('attribute2', 0); - // $ExpectType Query + // $ExpectType ParseQuery query.equalTo('attribute3', new AnotherSubClass()); - // $ExpectType Query + // $ExpectType ParseQuery query.equalTo('attribute3', new AnotherSubClass().toPointer()); - // @ts-expect-error + // $ExpectError query.equalTo('attribute1', new AnotherSubClass().toPointer()); - // @ts-expect-error + // $ExpectError query.equalTo('attribute2', 'a string value'); - // @ts-expect-error + // $ExpectError query.equalTo('nonexistentProp', 'any value'); - // $ExpectType Query + // $ExpectType ParseQuery query.equalTo('attribute4', 'a_string_value'); // Can query contents of array // Can query array itself if equal too (mongodb $eq matches the array exactly or the contains an element that matches the array exactly) - // $ExpectType Query + // $ExpectType ParseQuery query.equalTo('attribute4', ['a_string_value']); - // $ExpectType Query + // $ExpectType ParseQuery query.notEqualTo('attribute4', 'a_string_value'); - // $ExpectType Query + // $ExpectType ParseQuery query.notEqualTo('attribute4', ['a_string_value']); - // @ts-expect-error + // $ExpectError query.equalTo('attribute4', 5); - // @ts-expect-error + // $ExpectError query.notEqualTo('attribute4', 5); - // @ts-expect-error + // $ExpectError query.equalTo('attribute4', [5]); - // @ts-expect-error + // $ExpectError query.notEqualTo('attribute4', [5]); - // $ExpectType Query + // $ExpectType ParseQuery query.exists('attribute1'); - // @ts-expect-error + // $ExpectError query.exists('nonexistentProp'); - // $ExpectType Query + // $ExpectType ParseQuery query.fullText('attribute1', 'full text'); - // @ts-expect-error + // $ExpectError query.fullText('nonexistentProp', 'full text'); - // $ExpectType Query + // $ExpectType ParseQuery query.greaterThan('attribute2', 1000); - // @ts-expect-error + // $ExpectError query.greaterThan('attribute2', '1000'); - // @ts-expect-error + // $ExpectError query.greaterThan('nonexistentProp', 1000); - // $ExpectType Query + // $ExpectType ParseQuery query.greaterThanOrEqualTo('attribute2', 1000); - // @ts-expect-error + // $ExpectError query.greaterThanOrEqualTo('attribute2', '1000'); - // @ts-expect-error + // $ExpectError query.greaterThanOrEqualTo('nonexistentProp', 1000); - // $ExpectType Query + // $ExpectType ParseQuery query.include(['attribute1', 'attribute2']); - // $ExpectType Query + // $ExpectType ParseQuery + query.include('attribute1', 'attribute2'); + // $ExpectType ParseQuery query.include('attribute3.someProp'); - // @ts-expect-error + // $ExpectError query.include(['attribute1', 'nonexistentProp']); - // $ExpectType Query + // $ExpectType ParseQuery + query.exclude('attribute1', 'attribute2'); + // $ExpectType ParseQuery + query.exclude(['attribute1', 'attribute2']); + // $ExpectError + query.exclude('attribute1', 'nonexistentProp'); + + // $ExpectType ParseQuery query.lessThan('attribute2', 1000); - // @ts-expect-error + // $ExpectError query.lessThan('attribute2', '1000'); - // @ts-expect-error + // $ExpectError query.lessThan('nonexistentProp', 1000); - // $ExpectType Query + // $ExpectType ParseQuery query.lessThanOrEqualTo('attribute2', 1000); - // @ts-expect-error + // $ExpectError query.lessThanOrEqualTo('attribute2', '1000'); - // @ts-expect-error + // $ExpectError query.lessThanOrEqualTo('nonexistentProp', 1000); - // $ExpectType Query + // $ExpectType ParseQuery query.matches('attribute1', /a regex/); - // @ts-expect-error + // $ExpectError query.matches('nonexistentProp', /a regex/); - // $ExpectType Query + // $ExpectType ParseQuery query.matchesKeyInQuery('attribute1', 'x', new Parse.Query(AnotherSubClass)); - // @ts-expect-error + // $ExpectError query.matchesKeyInQuery('nonexistentProp', 'x', new Parse.Query(AnotherSubClass)); - // @ts-expect-error + // $ExpectError query.matchesKeyInQuery('attribute1', 'unknownKey', new Parse.Query(AnotherSubClass)); - // $ExpectType Query + // $ExpectType ParseQuery query.matchesQuery('attribute1', new Parse.Query('Example')); - // @ts-expect-error + // $ExpectError query.matchesQuery('nonexistentProp', new Parse.Query('Example')); - // $ExpectType Query + // $ExpectType ParseQuery query.near('attribute1', new Parse.GeoPoint()); - // @ts-expect-error + // $ExpectError query.near('nonexistentProp', new Parse.GeoPoint()); - // $ExpectType Query + // $ExpectType ParseQuery query.notContainedIn('attribute2', [1, 2, 3]); - // @ts-expect-error + // $ExpectError query.notContainedIn('attribute2', ['1', '2', '3']); - // @ts-expect-error + // $ExpectError query.notContainedIn('nonexistentProp', [1, 2, 3]); - // $ExpectType Query + // $ExpectType ParseQuery query.notEqualTo('attribute1', '1'); - // @ts-expect-error + // $ExpectError query.notEqualTo('attribute1', 1); - // @ts-expect-error + // $ExpectError query.notEqualTo('nonexistentProp', 1); - // $ExpectType Query + // $ExpectType ParseQuery query.polygonContains('attribute1', new Parse.GeoPoint()); - // @ts-expect-error + // $ExpectError query.polygonContains('nonexistentProp', new Parse.GeoPoint()); - // $ExpectType Query + // $ExpectType ParseQuery query.select('attribute1', 'attribute2'); - // @ts-expect-error + // $ExpectType ParseQuery + query.select(['attribute1', 'attribute2']); + // $ExpectError query.select('attribute1', 'nonexistentProp'); - // $ExpectType Query + // $ExpectType ParseQuery query.startsWith('attribute1', 'prefix string'); - // @ts-expect-error + // $ExpectError query.startsWith('nonexistentProp', 'prefix string'); - // $ExpectType Query + // $ExpectType ParseQuery + query.watch('attribute1', 'attribute2'); + // $ExpectType ParseQuery + query.watch(['attribute1', 'attribute2']); + // $ExpectError + query.watch('attribute1', 'nonexistentProp'); + + // $ExpectType ParseQuery query.withCount(true); - // $ExpectType Query + // $ExpectType ParseQuery query.withinGeoBox('attribute1', new Parse.GeoPoint(), new Parse.GeoPoint()); - // @ts-expect-error + // $ExpectError query.withinGeoBox('nonexistentProp', new Parse.GeoPoint(), new Parse.GeoPoint()); - // $ExpectType Query + // $ExpectType ParseQuery query.withinKilometers('attribute1', new Parse.GeoPoint(), 100); - // @ts-expect-error + // $ExpectError query.withinKilometers('nonexistentProp', new Parse.GeoPoint(), 100); - // $ExpectType Query + // $ExpectType ParseQuery query.withinMiles('attribute1', new Parse.GeoPoint(), 100); - // @ts-expect-error + // $ExpectError query.withinMiles('nonexistentProp', new Parse.GeoPoint(), 100); - // $ExpectType Query + // $ExpectType ParseQuery query.withinPolygon('attribute1', [ [12.3, 45.6], [-78.9, 10.1], ]); - // @ts-expect-error + // $ExpectError query.withinPolygon('nonexistentProp', [ [12.3, 45.6], [-78.9, 10.1], ]); - // $ExpectType Query + // $ExpectType ParseQuery query.withinRadians('attribute1', new Parse.GeoPoint(), 100); - // @ts-expect-error + // $ExpectError query.withinRadians('nonexistentProp', new Parse.GeoPoint(), 100); } @@ -2041,32 +2041,32 @@ function testQuery() { queryUntyped: Parse.Query, queryTyped: Parse.Query> ) { - // $ExpectType Object + // $ExpectType ParseObject await queryUntyped.get('objectId'); - // $ExpectType Object[] + // $ExpectType ParseObject[] await queryUntyped.find(); // $ExpectType string[] await queryTyped.distinct('example'); - // $ExpectType Object | undefined + // $ExpectType ParseObject | undefined await queryUntyped.first(); - // $ExpectType Object<{ example: string; }> + // $ExpectType ParseObject<{ example: string; }> await queryTyped.get('objectId'); - // $ExpectType Object<{ example: string; }>[] + // $ExpectType ParseObject<{ example: string; }>[] await queryTyped.find(); - // $ExpectType Object<{ example: string; }> | undefined + // $ExpectType ParseObject<{ example: string; }> | undefined await queryTyped.first(); } } function testRole() { function testConstructor(acl: Parse.ACL) { - // $ExpectType Role> + // $ExpectType ParseRole<{ example: string; }> new Parse.Role<{ example: string }>('TestRole', acl); } @@ -2079,32 +2079,99 @@ function testRole() { } } -// $ExpectType Session -new Parse.Session(); +function testSession() { + async function testConstructor() { + // $ExpectType ParseSession + const session = new Parse.Session(); + + // $ExpectType ParseSession<{ example: number; }> + new Parse.Session({ example: 100 }); -// $ExpectType Session<{ example: number; }> -new Parse.Session({ example: 100 }); + // $ExpectType ParseSession<{ example: number; }> + new Parse.Session<{ example: number }>(); -// @ts-expect-error: invalid type -new Parse.Session<{ example: number }>(); + // $ExpectType ParseSession<{ example: number; }> + new Parse.Session<{ example: number }>({ example: 100 }); -// @ts-expect-error: invalid type -new Parse.Session<{ example: number }>({ example: 'hello' }); + // $ExpectError + new Parse.Session<{ example: number }>({ example: 'hello' }); + + // $ExpectType boolean + Parse.Session.isCurrentSessionRevocable(); + + // $ExpectType string[] + Parse.Session.readOnlyAttributes(); + + // $ExpectType string + session.getSessionToken(); + + // $ExpectType ParseSession + await Parse.Session.current(); + + // $ExpectType ParseSession<{ example: string; }> + await Parse.Session.current>(); + } +} function testUser() { function testConstructor() { - // $ExpectType User + // $ExpectType ParseUser new Parse.User(); - // $ExpectType User<{ example: number; }> + // $ExpectType ParseUser<{ example: number; }> new Parse.User({ example: 100 }); - // @ts-expect-error + // $ExpectType ParseUser<{ example: number; }> new Parse.User<{ example: number }>(); - // @ts-expect-error + // $ExpectType ParseUser<{ example: number; }> + new Parse.User<{ example: number }>({ example: 100 }); + + // $ExpectError new Parse.User<{ example: number }>({ example: 'hello' }); } + + async function testStatic() { + const user = new Parse.User<{ field: 'hello' }>(); + + // $ExpectType ParseUser<{ field: "hello"; }> | null + Parse.User.current>(); + + // $ExpectType ParseUser<{ field: "hello"; }> | null + await Parse.User.currentAsync>(); + + // $ExpectType ParseUser<{ field: "hello"; }> + await Parse.User.signUp>('username', 'password', {}); + + // $ExpectType ParseUser<{ field: "hello"; }> + await Parse.User.become>('session-token'); + + // $ExpectType ParseUser<{ field: "hello"; }> + await Parse.User.logIn>('username', 'password'); + + // $ExpectType ParseUser<{ field: "hello"; }> + await Parse.User.logInWith>('provider', {}); + + // $ExpectType ParseUser<{ field: "hello"; }> + await Parse.User.logInWithAdditionalAuth>( + 'username', + 'password', + {} + ); + + // $ExpectType ParseUser<{ field: "hello"; }> + await Parse.User.loginAs>(user.id!); + + // $ExpectType ParseUser<{ field: "hello"; }> + await Parse.User.verifyPassword>('username', 'password'); + + // $ExpectType ParseUser<{ field: "hello"; }> + await Parse.User.hydrate>(user); + + // $ExpectType ParseUser<{ field: "hello"; }> + await Parse.User.me>('session-token'); + } + async function testAuthenticationProvider() { const authProvider: Parse.AuthProvider = { authenticate: () => {}, @@ -2149,33 +2216,33 @@ function testEncryptingUser() { } function testEventuallyQueue() { - function test() { + async function test() { const obj = new Parse.Object('TestObject'); - // $ExpectType Promise - Parse.EventuallyQueue.clear(); - // $ExpectType Promise - Parse.EventuallyQueue.getQueue(); + // $ExpectType void + await Parse.EventuallyQueue.clear(); + // $ExpectType Queue + await Parse.EventuallyQueue.getQueue(); // $ExpectType boolean Parse.EventuallyQueue.isPolling(); - // $ExpectType Promise - Parse.EventuallyQueue.save(obj); - // $ExpectType Promise - Parse.EventuallyQueue.save(obj, {}); - // $ExpectType Promise - Parse.EventuallyQueue.destroy(obj); - // $ExpectType Promise - Parse.EventuallyQueue.destroy(obj, {}); - // $ExpectType Promise - Parse.EventuallyQueue.length(); - // $ExpectType Promise - Parse.EventuallyQueue.sendQueue(); + // $ExpectType void + await Parse.EventuallyQueue.save(obj); + // $ExpectType void + await Parse.EventuallyQueue.save(obj, {}); + // $ExpectType void + await Parse.EventuallyQueue.destroy(obj); + // $ExpectType void + await Parse.EventuallyQueue.destroy(obj, {}); + // $ExpectType number + await Parse.EventuallyQueue.length(); + // $ExpectType boolean + await Parse.EventuallyQueue.sendQueue(); // $ExpectType void Parse.EventuallyQueue.stopPoll(); // $ExpectType void Parse.EventuallyQueue.poll(); // $ExpectType void Parse.EventuallyQueue.poll(300); - // @ts-expect-error + // $ExpectError Parse.EventuallyQueue.poll('300'); } } diff --git a/types/unsavedChildren.d.ts b/types/unsavedChildren.d.ts index 1e55e3aa4..57881ba36 100644 --- a/types/unsavedChildren.d.ts +++ b/types/unsavedChildren.d.ts @@ -8,7 +8,4 @@ import type ParseObject from './ParseObject'; * @param {boolean} allowDeepUnsaved * @returns {Array} */ -export default function unsavedChildren( - obj: ParseObject, - allowDeepUnsaved?: boolean -): Array; +export default function unsavedChildren(obj: ParseObject, allowDeepUnsaved?: boolean): Array;