From ecfc19948959b55e39b2a72ba0ac1eed11ef4676 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 24 Dec 2025 07:54:52 +0000 Subject: [PATCH] fix typescript errors --- .github/workflows/npm-publish.yml | 24 +- CHANGELOG.md | 4 + README.md | 4 +- index.ts | 2 +- install.ps1 | 4 +- install.sh | 2 +- lib/client.ts | 10 +- lib/commands/account.ts | 8 +- lib/commands/console.ts | 4 +- lib/commands/databases.ts | 71 +-- lib/commands/functions.ts | 44 +- lib/commands/generic.ts | 10 +- lib/commands/graphql.ts | 7 +- lib/commands/health.ts | 4 +- lib/commands/init.ts | 8 +- lib/commands/locale.ts | 3 +- lib/commands/messaging.ts | 65 +-- lib/commands/migrations.ts | 15 +- lib/commands/project.ts | 4 +- lib/commands/projects.ts | 30 +- lib/commands/proxy.ts | 5 +- lib/commands/pull.ts | 2 +- lib/commands/push.ts | 41 +- lib/commands/run.ts | 7 +- lib/commands/sites.ts | 31 +- lib/commands/storage.ts | 40 +- lib/commands/tables-db.ts | 71 +-- lib/commands/teams.ts | 11 +- lib/commands/tokens.ts | 3 +- lib/commands/users.ts | 11 +- lib/commands/vcs.ts | 4 +- lib/config.ts | 215 ++++----- lib/emulation/docker.ts | 14 +- lib/enums/adapter.ts | 5 + lib/enums/api-service.ts | 16 + lib/enums/api.ts | 6 + lib/enums/attribute-status.ts | 8 + lib/enums/auth-method.ts | 10 + lib/enums/authentication-factor.ts | 7 + lib/enums/authenticator-type.ts | 4 + lib/enums/browser.ts | 17 + lib/enums/build-runtime.ts | 70 +++ lib/enums/column-status.ts | 8 + lib/enums/compression.ts | 6 + lib/enums/console-resource-type.ts | 4 + lib/enums/credit-card.ts | 20 + lib/enums/database-type.ts | 5 + lib/enums/deployment-download-type.ts | 5 + lib/enums/deployment-status.ts | 8 + lib/enums/email-template-locale.ts | 134 ++++++ lib/enums/email-template-type.ts | 10 + lib/enums/execution-method.ts | 10 + lib/enums/execution-status.ts | 8 + lib/enums/execution-trigger.ts | 6 + lib/enums/flag.ts | 198 ++++++++ lib/enums/framework.ts | 18 + lib/enums/health-antivirus-status.ts | 6 + lib/enums/health-check-status.ts | 5 + lib/enums/image-format.ts | 10 + lib/enums/image-gravity.ts | 12 + lib/enums/index-status.ts | 8 + lib/enums/index-type.ts | 7 + lib/enums/message-priority.ts | 5 + lib/enums/message-status.ts | 8 + lib/enums/messaging-provider-type.ts | 6 + lib/enums/name.ts | 15 + lib/enums/o-auth-provider.ts | 43 ++ lib/enums/output.ts | 10 + lib/enums/password-hash.ts | 14 + lib/enums/platform-type.ts | 18 + lib/enums/project-usage-range.ts | 5 + lib/enums/proxy-resource-type.ts | 5 + .../proxy-rule-deployment-resource-type.ts | 5 + lib/enums/proxy-rule-status.ts | 7 + lib/enums/region.ts | 4 + lib/enums/relation-mutate.ts | 6 + lib/enums/relationship-type.ts | 7 + lib/enums/runtime.ts | 70 +++ lib/enums/sms-template-locale.ts | 134 ++++++ lib/enums/sms-template-type.ts | 7 + lib/enums/smtp-encryption.ts | 6 + lib/enums/smtp-secure.ts | 5 + lib/enums/status-code.ts | 7 + lib/enums/template-reference-type.ts | 6 + lib/enums/theme.ts | 5 + lib/enums/timezone.ts | 422 ++++++++++++++++++ lib/enums/usage-range.ts | 6 + lib/enums/vcs-detection-type.ts | 5 + lib/enums/vcs-reference-type.ts | 6 + lib/paginate.ts | 30 +- lib/parser.ts | 2 +- lib/questions.ts | 6 +- lib/types.ts | 243 ++++++++-- package.json | 4 +- scoop/appwrite.config.json | 6 +- 95 files changed, 2122 insertions(+), 415 deletions(-) create mode 100644 lib/enums/adapter.ts create mode 100644 lib/enums/api-service.ts create mode 100644 lib/enums/api.ts create mode 100644 lib/enums/attribute-status.ts create mode 100644 lib/enums/auth-method.ts create mode 100644 lib/enums/authentication-factor.ts create mode 100644 lib/enums/authenticator-type.ts create mode 100644 lib/enums/browser.ts create mode 100644 lib/enums/build-runtime.ts create mode 100644 lib/enums/column-status.ts create mode 100644 lib/enums/compression.ts create mode 100644 lib/enums/console-resource-type.ts create mode 100644 lib/enums/credit-card.ts create mode 100644 lib/enums/database-type.ts create mode 100644 lib/enums/deployment-download-type.ts create mode 100644 lib/enums/deployment-status.ts create mode 100644 lib/enums/email-template-locale.ts create mode 100644 lib/enums/email-template-type.ts create mode 100644 lib/enums/execution-method.ts create mode 100644 lib/enums/execution-status.ts create mode 100644 lib/enums/execution-trigger.ts create mode 100644 lib/enums/flag.ts create mode 100644 lib/enums/framework.ts create mode 100644 lib/enums/health-antivirus-status.ts create mode 100644 lib/enums/health-check-status.ts create mode 100644 lib/enums/image-format.ts create mode 100644 lib/enums/image-gravity.ts create mode 100644 lib/enums/index-status.ts create mode 100644 lib/enums/index-type.ts create mode 100644 lib/enums/message-priority.ts create mode 100644 lib/enums/message-status.ts create mode 100644 lib/enums/messaging-provider-type.ts create mode 100644 lib/enums/name.ts create mode 100644 lib/enums/o-auth-provider.ts create mode 100644 lib/enums/output.ts create mode 100644 lib/enums/password-hash.ts create mode 100644 lib/enums/platform-type.ts create mode 100644 lib/enums/project-usage-range.ts create mode 100644 lib/enums/proxy-resource-type.ts create mode 100644 lib/enums/proxy-rule-deployment-resource-type.ts create mode 100644 lib/enums/proxy-rule-status.ts create mode 100644 lib/enums/region.ts create mode 100644 lib/enums/relation-mutate.ts create mode 100644 lib/enums/relationship-type.ts create mode 100644 lib/enums/runtime.ts create mode 100644 lib/enums/sms-template-locale.ts create mode 100644 lib/enums/sms-template-type.ts create mode 100644 lib/enums/smtp-encryption.ts create mode 100644 lib/enums/smtp-secure.ts create mode 100644 lib/enums/status-code.ts create mode 100644 lib/enums/template-reference-type.ts create mode 100644 lib/enums/theme.ts create mode 100644 lib/enums/timezone.ts create mode 100644 lib/enums/usage-range.ts create mode 100644 lib/enums/vcs-detection-type.ts create mode 100644 lib/enums/vcs-reference-type.ts diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index e29aa8b..54ac357 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -1,15 +1,21 @@ name: Publish Package to npmjs + on: release: types: [published] + +permissions: +id-token: write + contents: read + jobs: - build-for-linux-and-windows: + build-and-publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions/setup-node@v2 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - node-version: '16.x' + node-version: '22' registry-url: 'https://registry.npmjs.org' - name: Setup binfmt with QEMU run: | @@ -22,9 +28,9 @@ jobs: cd ./ldid sudo make sudo make install - - name: Install dependenices and build for Linux and Windows + - name: Install dependencies and build for Linux and Windows run: | - npm install + npm ci npm run linux-x64 npm run linux-arm64 npm run windows-x64 @@ -35,13 +41,11 @@ jobs: run: | if ${{ contains(github.event.release.tag_name, '-rc') }}; then echo "Publishing Release Candidate ${{ github.event.release.tag_name}} to NPM" - npm publish --tag next + npm publish --provenance --access public --tag next else echo "Publishing ${{ github.event.release.tag_name}} to NPM" - npm publish + npm publish --provenance --access public fi - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN_NO_ORG }} - uses: fnkr/github-action-ghr@v1 env: GHR_PATH: build/ diff --git a/CHANGELOG.md b/CHANGELOG.md index fbc157e..ccb799c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Change Log +## 13.0.0-rc.2 + +* Fixes a lot of typescript errors throughout the codebase + ## 13.0.0-rc.1 * Migrates codebase from JavaScript to TypeScript diff --git a/README.md b/README.md index f1cdf54..0566982 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Once the installation is complete, you can verify the install using ```sh $ appwrite -v -13.0.0-rc.1 +13.0.0-rc.2 ``` ### Install using prebuilt binaries @@ -60,7 +60,7 @@ $ scoop install https://raw.githubusercontent.com/appwrite/sdk-for-cli/master/sc Once the installation completes, you can verify your install using ``` $ appwrite -v -13.0.0-rc.1 +13.0.0-rc.2 ``` ## Getting Started diff --git a/index.ts b/index.ts index 54d01fd..f781565 100644 --- a/index.ts +++ b/index.ts @@ -5,7 +5,7 @@ const oldWidth = process.stdout.columns; process.stdout.columns = 100; /** ---------------------------------------------- */ -import program = require('commander'); +import { program } from 'commander'; import chalk = require('chalk'); const { version } = require('../package.json'); import { commandDescriptions, cliConfig } from './lib/parser'; diff --git a/install.ps1 b/install.ps1 index d21f8f5..86ca00b 100644 --- a/install.ps1 +++ b/install.ps1 @@ -13,8 +13,8 @@ # You can use "View source" of this page to see the full script. # REPO -$GITHUB_x64_URL = "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.1/appwrite-cli-win-x64.exe" -$GITHUB_arm64_URL = "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.1/appwrite-cli-win-arm64.exe" +$GITHUB_x64_URL = "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.2/appwrite-cli-win-x64.exe" +$GITHUB_arm64_URL = "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.2/appwrite-cli-win-arm64.exe" $APPWRITE_BINARY_NAME = "appwrite.exe" diff --git a/install.sh b/install.sh index 8732228..faa9c24 100644 --- a/install.sh +++ b/install.sh @@ -96,7 +96,7 @@ printSuccess() { downloadBinary() { echo "[2/4] Downloading executable for $OS ($ARCH) ..." - GITHUB_LATEST_VERSION="13.0.0-rc.1" + GITHUB_LATEST_VERSION="13.0.0-rc.2" GITHUB_FILE="appwrite-cli-${OS}-${ARCH}" GITHUB_URL="https://github.com/$GITHUB_REPOSITORY_NAME/releases/download/$GITHUB_LATEST_VERSION/$GITHUB_FILE" diff --git a/lib/client.ts b/lib/client.ts index 9d6833d..34868fb 100644 --- a/lib/client.ts +++ b/lib/client.ts @@ -1,5 +1,5 @@ import os = require('os'); -import { fetch, FormData, Agent } from 'undici'; +import { fetch, FormData, Agent, File } from 'undici'; import JSONbig = require('json-bigint'); import AppwriteException = require('./exception'); import { globalConfig } from './config'; @@ -9,7 +9,7 @@ import type { Headers, RequestParams, ResponseType, FileUpload } from './types'; const JSONBigInt = JSONbig({ storeAsString: false }); class Client { - private readonly CHUNK_SIZE = 5 * 1024 * 1024; // 5MB + readonly CHUNK_SIZE = 5 * 1024 * 1024; // 5MB private endpoint: string; private headers: Headers; private selfSigned: boolean; @@ -22,8 +22,8 @@ class Client { 'x-sdk-name': 'Command Line', 'x-sdk-platform': 'console', 'x-sdk-language': 'cli', - 'x-sdk-version': '13.0.0-rc.1', - 'user-agent': `AppwriteCLI/13.0.0-rc.1 (${os.type()} ${os.version()}; ${os.arch()})`, + 'x-sdk-version': '13.0.0-rc.2', + 'user-agent': `AppwriteCLI/13.0.0-rc.2 (${os.type()} ${os.version()}; ${os.arch()})`, 'X-Appwrite-Response-Format': '1.8.0', }; } @@ -168,7 +168,7 @@ class Client { for (const [key, value] of Object.entries(flatParams)) { if (value && typeof value === 'object' && 'type' in value && value.type === 'file') { const fileUpload = value as FileUpload; - formData.append(key, fileUpload.file as any, fileUpload.filename); + formData.append(key, fileUpload.file, fileUpload.filename); } else { formData.append(key, value as string); } diff --git a/lib/commands/account.ts b/lib/commands/account.ts index 98a88fd..a8c5887 100644 --- a/lib/commands/account.ts +++ b/lib/commands/account.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,10 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { AuthenticatorType } from '../enums/authenticator-type'; +import { AuthenticationFactor } from '../enums/authentication-factor'; +import { OAuthProvider } from '../enums/o-auth-provider'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -669,7 +673,7 @@ export const accountGetPrefs = async ({parseOutput = true, overrideForCli = fals } interface AccountUpdatePrefsRequestParams { - prefs: object; + prefs: string; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; diff --git a/lib/commands/console.ts b/lib/commands/console.ts index e9ad93c..412c8fd 100644 --- a/lib/commands/console.ts +++ b/lib/commands/console.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,8 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { ConsoleResourceType } from '../enums/console-resource-type'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ diff --git a/lib/commands/databases.ts b/lib/commands/databases.ts index 83de029..2142c8e 100644 --- a/lib/commands/databases.ts +++ b/lib/commands/databases.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,11 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { UsageRange } from '../enums/usage-range'; +import { RelationshipType } from '../enums/relationship-type'; +import { RelationMutate } from '../enums/relation-mutate'; +import { IndexType } from '../enums/index-type'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -267,7 +272,7 @@ export const databasesDeleteTransaction = async ({transactionId,parseOutput = tr } interface DatabasesCreateOperationsRequestParams { transactionId: string; - operations?: object[]; + operations?: string[]; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; @@ -278,7 +283,7 @@ export const databasesCreateOperations = async ({transactionId,operations,parseO sdk; let apiPath = '/databases/transactions/{transactionId}/operations'.replace('{transactionId}', transactionId); let payload = {}; - operations = operations === true ? [] : operations; + operations = (operations as unknown) === true ? [] : operations; if (typeof operations !== 'undefined') { payload['operations'] = operations; } @@ -468,8 +473,8 @@ interface DatabasesCreateCollectionRequestParams { permissions?: string[]; documentSecurity?: boolean; enabled?: boolean; - attributes?: object[]; - indexes?: object[]; + attributes?: string[]; + indexes?: string[]; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; @@ -486,7 +491,7 @@ export const databasesCreateCollection = async ({databaseId,collectionId,name,pe if (typeof name !== 'undefined') { payload['name'] = name; } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -496,11 +501,11 @@ export const databasesCreateCollection = async ({databaseId,collectionId,name,pe if (typeof enabled !== 'undefined') { payload['enabled'] = enabled; } - attributes = attributes === true ? [] : attributes; + attributes = (attributes as unknown) === true ? [] : attributes; if (typeof attributes !== 'undefined') { payload['attributes'] = attributes; } - indexes = indexes === true ? [] : indexes; + indexes = (indexes as unknown) === true ? [] : indexes; if (typeof indexes !== 'undefined') { payload['indexes'] = indexes; } @@ -569,7 +574,7 @@ export const databasesUpdateCollection = async ({databaseId,collectionId,name,pe if (typeof name !== 'undefined') { payload['name'] = name; } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -929,7 +934,7 @@ export const databasesCreateEnumAttribute = async ({databaseId,collectionId,key, if (typeof key !== 'undefined') { payload['key'] = key; } - elements = elements === true ? [] : elements; + elements = (elements as unknown) === true ? [] : elements; if (typeof elements !== 'undefined') { payload['elements'] = elements; } @@ -974,7 +979,7 @@ export const databasesUpdateEnumAttribute = async ({databaseId,collectionId,key, sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/attributes/enum/{key}'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId).replace('{key}', key); let payload = {}; - elements = elements === true ? [] : elements; + elements = (elements as unknown) === true ? [] : elements; if (typeof elements !== 'undefined') { payload['elements'] = elements; } @@ -1304,7 +1309,7 @@ export const databasesCreateLineAttribute = async ({databaseId,collectionId,key, if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1342,7 +1347,7 @@ export const databasesUpdateLineAttribute = async ({databaseId,collectionId,key, if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1385,7 +1390,7 @@ export const databasesCreatePointAttribute = async ({databaseId,collectionId,key if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1423,7 +1428,7 @@ export const databasesUpdatePointAttribute = async ({databaseId,collectionId,key if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1466,7 +1471,7 @@ export const databasesCreatePolygonAttribute = async ({databaseId,collectionId,k if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1504,7 +1509,7 @@ export const databasesUpdatePolygonAttribute = async ({databaseId,collectionId,k if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1892,7 +1897,7 @@ interface DatabasesCreateDocumentRequestParams { databaseId: string; collectionId: string; documentId: string; - data: object; + data: string; permissions?: string[]; transactionId?: string; overrideForCli?: boolean; @@ -1911,7 +1916,7 @@ export const databasesCreateDocument = async ({databaseId,collectionId,documentI if (typeof data !== 'undefined') { payload['data'] = JSON.parse(data); } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -1935,7 +1940,7 @@ export const databasesCreateDocument = async ({databaseId,collectionId,documentI interface DatabasesCreateDocumentsRequestParams { databaseId: string; collectionId: string; - documents: object[]; + documents: string[]; transactionId?: string; overrideForCli?: boolean; parseOutput?: boolean; @@ -1947,7 +1952,7 @@ export const databasesCreateDocuments = async ({databaseId,collectionId,document sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; - documents = documents === true ? [] : documents; + documents = (documents as unknown) === true ? [] : documents; if (typeof documents !== 'undefined') { payload['documents'] = documents; } @@ -1971,7 +1976,7 @@ export const databasesCreateDocuments = async ({databaseId,collectionId,document interface DatabasesUpsertDocumentsRequestParams { databaseId: string; collectionId: string; - documents: object[]; + documents: string[]; transactionId?: string; overrideForCli?: boolean; parseOutput?: boolean; @@ -1983,7 +1988,7 @@ export const databasesUpsertDocuments = async ({databaseId,collectionId,document sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; - documents = documents === true ? [] : documents; + documents = (documents as unknown) === true ? [] : documents; if (typeof documents !== 'undefined') { payload['documents'] = documents; } @@ -2007,7 +2012,7 @@ export const databasesUpsertDocuments = async ({databaseId,collectionId,document interface DatabasesUpdateDocumentsRequestParams { databaseId: string; collectionId: string; - data?: object; + data?: string; queries?: string[]; transactionId?: string; overrideForCli?: boolean; @@ -2023,7 +2028,7 @@ export const databasesUpdateDocuments = async ({databaseId,collectionId,data,que if (typeof data !== 'undefined') { payload['data'] = JSON.parse(data); } - queries = queries === true ? [] : queries; + queries = (queries as unknown) === true ? [] : queries; if (typeof queries !== 'undefined') { payload['queries'] = queries; } @@ -2059,7 +2064,7 @@ export const databasesDeleteDocuments = async ({databaseId,collectionId,queries, sdk; let apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); let payload = {}; - queries = queries === true ? [] : queries; + queries = (queries as unknown) === true ? [] : queries; if (typeof queries !== 'undefined') { payload['queries'] = queries; } @@ -2124,7 +2129,7 @@ interface DatabasesUpsertDocumentRequestParams { databaseId: string; collectionId: string; documentId: string; - data?: object; + data?: string; permissions?: string[]; transactionId?: string; overrideForCli?: boolean; @@ -2140,7 +2145,7 @@ export const databasesUpsertDocument = async ({databaseId,collectionId,documentI if (typeof data !== 'undefined') { payload['data'] = JSON.parse(data); } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -2165,7 +2170,7 @@ interface DatabasesUpdateDocumentRequestParams { databaseId: string; collectionId: string; documentId: string; - data?: object; + data?: string; permissions?: string[]; transactionId?: string; overrideForCli?: boolean; @@ -2181,7 +2186,7 @@ export const databasesUpdateDocument = async ({databaseId,collectionId,documentI if (typeof data !== 'undefined') { payload['data'] = JSON.parse(data); } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -2410,15 +2415,15 @@ export const databasesCreateIndex = async ({databaseId,collectionId,key,type,att if (typeof type !== 'undefined') { payload['type'] = type; } - attributes = attributes === true ? [] : attributes; + attributes = (attributes as unknown) === true ? [] : attributes; if (typeof attributes !== 'undefined') { payload['attributes'] = attributes; } - orders = orders === true ? [] : orders; + orders = (orders as unknown) === true ? [] : orders; if (typeof orders !== 'undefined') { payload['orders'] = orders; } - lengths = lengths === true ? [] : lengths; + lengths = (lengths as unknown) === true ? [] : lengths; if (typeof lengths !== 'undefined') { payload['lengths'] = lengths; } diff --git a/lib/commands/functions.ts b/lib/commands/functions.ts index e592c00..947d5c3 100644 --- a/lib/commands/functions.ts +++ b/lib/commands/functions.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,13 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { Runtime } from '../enums/runtime'; +import { UsageRange } from '../enums/usage-range'; +import { TemplateReferenceType } from '../enums/template-reference-type'; +import { VCSReferenceType } from '../enums/vcs-reference-type'; +import { DeploymentDownloadType } from '../enums/deployment-download-type'; +import { ExecutionMethod } from '../enums/execution-method'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -114,11 +121,11 @@ export const functionsCreate = async ({functionId,name,runtime,execute,events,sc if (typeof runtime !== 'undefined') { payload['runtime'] = runtime; } - execute = execute === true ? [] : execute; + execute = (execute as unknown) === true ? [] : execute; if (typeof execute !== 'undefined') { payload['execute'] = execute; } - events = events === true ? [] : events; + events = (events as unknown) === true ? [] : events; if (typeof events !== 'undefined') { payload['events'] = events; } @@ -140,7 +147,7 @@ export const functionsCreate = async ({functionId,name,runtime,execute,events,sc if (typeof commands !== 'undefined') { payload['commands'] = commands; } - scopes = scopes === true ? [] : scopes; + scopes = (scopes as unknown) === true ? [] : scopes; if (typeof scopes !== 'undefined') { payload['scopes'] = scopes; } @@ -406,11 +413,11 @@ export const functionsUpdate = async ({functionId,name,runtime,execute,events,sc if (typeof runtime !== 'undefined') { payload['runtime'] = runtime; } - execute = execute === true ? [] : execute; + execute = (execute as unknown) === true ? [] : execute; if (typeof execute !== 'undefined') { payload['execute'] = execute; } - events = events === true ? [] : events; + events = (events as unknown) === true ? [] : events; if (typeof events !== 'undefined') { payload['events'] = events; } @@ -432,7 +439,7 @@ export const functionsUpdate = async ({functionId,name,runtime,execute,events,sc if (typeof commands !== 'undefined') { payload['commands'] = commands; } - scopes = scopes === true ? [] : scopes; + scopes = (scopes as unknown) === true ? [] : scopes; if (typeof scopes !== 'undefined') { payload['scopes'] = scopes; } @@ -575,10 +582,10 @@ interface FunctionsCreateDeploymentRequestParams { overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; - onProgress?: (progress: number) => void; + onProgress?: (progress: UploadProgress) => void; } -export const functionsCreateDeployment = async ({functionId,code,activate,entrypoint,commands,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}: FunctionsCreateDeploymentRequestParams): Promise => { +export const functionsCreateDeployment = async ({functionId,code,activate,entrypoint,commands,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = (progress: any) => {}}: FunctionsCreateDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/functions/{functionId}/deployments'.replace('{functionId}', functionId); @@ -629,15 +636,18 @@ export const functionsCreateDeployment = async ({functionId,code,activate,entryp const nodeStream = fs.createReadStream(filePath); const stream = convertReadStreamToReadableStream(nodeStream); - if (typeof filePath !== 'undefined') { - code = { type: 'file', stream, filename: pathLib.basename(filePath), size: fs.statSync(filePath).size }; - payload['code'] = code - } + const codeUpload: FileInput = { + type: 'file', + stream, + filename: pathLib.basename(filePath), + size: fs.statSync(filePath).size + }; + payload['code'] = codeUpload; if (typeof activate !== 'undefined') { payload['activate'] = activate; } - const size = code.size; + const size = codeUpload.size; const apiHeaders = { 'content-type': 'multipart/form-data', @@ -679,7 +689,7 @@ export const functionsCreateDeployment = async ({functionId,code,activate,entryp apiHeaders['x-appwrite-id'] = id; } - payload['code'] = { type: 'file', file: new File([uploadableChunkTrimmed], code.filename), filename: code.filename }; + payload['code'] = { type: 'file', file: new File([uploadableChunkTrimmed], codeUpload.filename), filename: codeUpload.filename }; response = await client.call('post', apiPath, apiHeaders, payload); @@ -702,7 +712,7 @@ export const functionsCreateDeployment = async ({functionId,code,activate,entryp currentPosition = 0; } - for await (const chunk of code.stream) { + for await (const chunk of codeUpload.stream) { for(const b of chunk) { uploadableChunk[currentPosition] = b; @@ -1024,7 +1034,7 @@ interface FunctionsCreateExecutionRequestParams { async?: boolean; xpath?: string; method?: ExecutionMethod; - headers?: object; + headers?: string; scheduledAt?: string; overrideForCli?: boolean; parseOutput?: boolean; diff --git a/lib/commands/generic.ts b/lib/commands/generic.ts index 5dfc962..9f9c16b 100644 --- a/lib/commands/generic.ts +++ b/lib/commands/generic.ts @@ -52,7 +52,7 @@ export const loginCommand = async ({ email, password, endpoint, mfa, code }: Log const id = ID.unique(); - globalConfig.addSession(id, {}); + globalConfig.addSession(id, { endpoint: configEndpoint }); globalConfig.setCurrentSession(id); globalConfig.setEndpoint(configEndpoint); globalConfig.setEmail(answers.email); @@ -279,12 +279,12 @@ export const client = new Command("client") if (selfSigned || globalConfig.getSelfSigned()) { clientInstance.setSelfSigned(true); } - let response = await clientInstance.call('GET', '/health/version'); + let response = await clientInstance.call<{ version?: string }>('GET', '/health/version'); if (!response.version) { throw new Error(); } globalConfig.setCurrentSession(id); - globalConfig.addSession(id, {}); + globalConfig.addSession(id, { endpoint }); globalConfig.setEndpoint(endpoint); } catch (_) { throw new Error("Invalid endpoint or your Appwrite server is not running as expected."); @@ -320,8 +320,8 @@ export const migrate = async (): Promise => { return; } - const endpoint = globalConfig.get('endpoint'); - const cookie = globalConfig.get('cookie'); + const endpoint = globalConfig.get('endpoint') as string; + const cookie = globalConfig.get('cookie') as string; const id = ID.unique(); const data = { diff --git a/lib/commands/graphql.ts b/lib/commands/graphql.ts index 04d0f74..ee6a7c6 100644 --- a/lib/commands/graphql.ts +++ b/lib/commands/graphql.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,7 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -36,7 +37,7 @@ export const graphql = new Command("graphql").description(commandDescriptions['g }) interface GraphqlQueryRequestParams { - query: object; + query: string; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; @@ -66,7 +67,7 @@ export const graphqlQuery = async ({query,parseOutput = true, overrideForCli = f } interface GraphqlMutationRequestParams { - query: object; + query: string; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; diff --git a/lib/commands/health.ts b/lib/commands/health.ts index 7852de7..b6da608 100644 --- a/lib/commands/health.ts +++ b/lib/commands/health.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,8 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { Name } from '../enums/name'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ diff --git a/lib/commands/init.ts b/lib/commands/init.ts index ab03fa2..88edef0 100644 --- a/lib/commands/init.ts +++ b/lib/commands/init.ts @@ -41,7 +41,7 @@ const initResources = async (): Promise => { collection: initCollection } - const answers = await inquirer.prompt(questionsInitResources[0]); + const answers = await inquirer.prompt([questionsInitResources[0]]); const action = actions[answers.resource]; if (action !== undefined) { @@ -85,9 +85,9 @@ const initProject = async ({ organizationId, projectId, projectName }: InitProje answers.project = {}; answers.organization = {}; - answers.organization = organizationId ?? (await inquirer.prompt(questionsInitProject[2])).organization; - answers.project.name = projectName ?? (await inquirer.prompt(questionsInitProject[3])).project; - answers.project = projectId ?? (await inquirer.prompt(questionsInitProject[4])).id; + answers.organization = organizationId ?? (await inquirer.prompt([questionsInitProject[2]])).organization; + answers.project.name = projectName ?? (await inquirer.prompt([questionsInitProject[3]])).project; + answers.project = projectId ?? (await inquirer.prompt([questionsInitProject[4]])).id; try { await projectsGet({ projectId, parseOutput: false }); diff --git a/lib/commands/locale.ts b/lib/commands/locale.ts index e80a44a..703a480 100644 --- a/lib/commands/locale.ts +++ b/lib/commands/locale.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,7 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ diff --git a/lib/commands/messaging.ts b/lib/commands/messaging.ts index 92d4c85..faae93b 100644 --- a/lib/commands/messaging.ts +++ b/lib/commands/messaging.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,9 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { MessagePriority } from '../enums/message-priority'; +import { SmtpEncryption } from '../enums/smtp-encryption'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -108,27 +111,27 @@ export const messagingCreateEmail = async ({messageId,subject,content,topics,use if (typeof content !== 'undefined') { payload['content'] = content; } - topics = topics === true ? [] : topics; + topics = (topics as unknown) === true ? [] : topics; if (typeof topics !== 'undefined') { payload['topics'] = topics; } - users = users === true ? [] : users; + users = (users as unknown) === true ? [] : users; if (typeof users !== 'undefined') { payload['users'] = users; } - targets = targets === true ? [] : targets; + targets = (targets as unknown) === true ? [] : targets; if (typeof targets !== 'undefined') { payload['targets'] = targets; } - cc = cc === true ? [] : cc; + cc = (cc as unknown) === true ? [] : cc; if (typeof cc !== 'undefined') { payload['cc'] = cc; } - bcc = bcc === true ? [] : bcc; + bcc = (bcc as unknown) === true ? [] : bcc; if (typeof bcc !== 'undefined') { payload['bcc'] = bcc; } - attachments = attachments === true ? [] : attachments; + attachments = (attachments as unknown) === true ? [] : attachments; if (typeof attachments !== 'undefined') { payload['attachments'] = attachments; } @@ -178,15 +181,15 @@ export const messagingUpdateEmail = async ({messageId,topics,users,targets,subje sdk; let apiPath = '/messaging/messages/email/{messageId}'.replace('{messageId}', messageId); let payload = {}; - topics = topics === true ? [] : topics; + topics = (topics as unknown) === true ? [] : topics; if (typeof topics !== 'undefined') { payload['topics'] = topics; } - users = users === true ? [] : users; + users = (users as unknown) === true ? [] : users; if (typeof users !== 'undefined') { payload['users'] = users; } - targets = targets === true ? [] : targets; + targets = (targets as unknown) === true ? [] : targets; if (typeof targets !== 'undefined') { payload['targets'] = targets; } @@ -202,18 +205,18 @@ export const messagingUpdateEmail = async ({messageId,topics,users,targets,subje if (typeof html !== 'undefined') { payload['html'] = html; } - cc = cc === true ? [] : cc; + cc = (cc as unknown) === true ? [] : cc; if (typeof cc !== 'undefined') { payload['cc'] = cc; } - bcc = bcc === true ? [] : bcc; + bcc = (bcc as unknown) === true ? [] : bcc; if (typeof bcc !== 'undefined') { payload['bcc'] = bcc; } if (typeof scheduledAt !== 'undefined') { payload['scheduledAt'] = scheduledAt; } - attachments = attachments === true ? [] : attachments; + attachments = (attachments as unknown) === true ? [] : attachments; if (typeof attachments !== 'undefined') { payload['attachments'] = attachments; } @@ -238,7 +241,7 @@ interface MessagingCreatePushRequestParams { topics?: string[]; users?: string[]; targets?: string[]; - data?: object; + data?: string; action?: string; image?: string; icon?: string; @@ -270,15 +273,15 @@ export const messagingCreatePush = async ({messageId,title,body,topics,users,tar if (typeof body !== 'undefined') { payload['body'] = body; } - topics = topics === true ? [] : topics; + topics = (topics as unknown) === true ? [] : topics; if (typeof topics !== 'undefined') { payload['topics'] = topics; } - users = users === true ? [] : users; + users = (users as unknown) === true ? [] : users; if (typeof users !== 'undefined') { payload['users'] = users; } - targets = targets === true ? [] : targets; + targets = (targets as unknown) === true ? [] : targets; if (typeof targets !== 'undefined') { payload['targets'] = targets; } @@ -342,7 +345,7 @@ interface MessagingUpdatePushRequestParams { targets?: string[]; title?: string; body?: string; - data?: object; + data?: string; action?: string; image?: string; icon?: string; @@ -365,15 +368,15 @@ export const messagingUpdatePush = async ({messageId,topics,users,targets,title, sdk; let apiPath = '/messaging/messages/push/{messageId}'.replace('{messageId}', messageId); let payload = {}; - topics = topics === true ? [] : topics; + topics = (topics as unknown) === true ? [] : topics; if (typeof topics !== 'undefined') { payload['topics'] = topics; } - users = users === true ? [] : users; + users = (users as unknown) === true ? [] : users; if (typeof users !== 'undefined') { payload['users'] = users; } - targets = targets === true ? [] : targets; + targets = (targets as unknown) === true ? [] : targets; if (typeof targets !== 'undefined') { payload['targets'] = targets; } @@ -460,15 +463,15 @@ export const messagingCreateSMS = async ({messageId,content,topics,users,targets if (typeof content !== 'undefined') { payload['content'] = content; } - topics = topics === true ? [] : topics; + topics = (topics as unknown) === true ? [] : topics; if (typeof topics !== 'undefined') { payload['topics'] = topics; } - users = users === true ? [] : users; + users = (users as unknown) === true ? [] : users; if (typeof users !== 'undefined') { payload['users'] = users; } - targets = targets === true ? [] : targets; + targets = (targets as unknown) === true ? [] : targets; if (typeof targets !== 'undefined') { payload['targets'] = targets; } @@ -510,15 +513,15 @@ export const messagingUpdateSMS = async ({messageId,topics,users,targets,content sdk; let apiPath = '/messaging/messages/sms/{messageId}'.replace('{messageId}', messageId); let payload = {}; - topics = topics === true ? [] : topics; + topics = (topics as unknown) === true ? [] : topics; if (typeof topics !== 'undefined') { payload['topics'] = topics; } - users = users === true ? [] : users; + users = (users as unknown) === true ? [] : users; if (typeof users !== 'undefined') { payload['users'] = users; } - targets = targets === true ? [] : targets; + targets = (targets as unknown) === true ? [] : targets; if (typeof targets !== 'undefined') { payload['targets'] = targets; } @@ -827,7 +830,7 @@ export const messagingUpdateAPNSProvider = async ({providerId,name,enabled,authK interface MessagingCreateFCMProviderRequestParams { providerId: string; name: string; - serviceAccountJSON?: object; + serviceAccountJSON?: string; enabled?: boolean; overrideForCli?: boolean; parseOutput?: boolean; @@ -869,7 +872,7 @@ interface MessagingUpdateFCMProviderRequestParams { providerId: string; name?: string; enabled?: boolean; - serviceAccountJSON?: object; + serviceAccountJSON?: string; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; @@ -2069,7 +2072,7 @@ export const messagingCreateTopic = async ({topicId,name,subscribe,parseOutput = if (typeof name !== 'undefined') { payload['name'] = name; } - subscribe = subscribe === true ? [] : subscribe; + subscribe = (subscribe as unknown) === true ? [] : subscribe; if (typeof subscribe !== 'undefined') { payload['subscribe'] = subscribe; } @@ -2134,7 +2137,7 @@ export const messagingUpdateTopic = async ({topicId,name,subscribe,parseOutput = if (typeof name !== 'undefined') { payload['name'] = name; } - subscribe = subscribe === true ? [] : subscribe; + subscribe = (subscribe as unknown) === true ? [] : subscribe; if (typeof subscribe !== 'undefined') { payload['subscribe'] = subscribe; } diff --git a/lib/commands/migrations.ts b/lib/commands/migrations.ts index b2c6a74..f3b5153 100644 --- a/lib/commands/migrations.ts +++ b/lib/commands/migrations.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,7 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -86,7 +87,7 @@ export const migrationsCreateAppwriteMigration = async ({resources,endpoint,proj sdk; let apiPath = '/migrations/appwrite'; let payload = {}; - resources = resources === true ? [] : resources; + resources = (resources as unknown) === true ? [] : resources; if (typeof resources !== 'undefined') { payload['resources'] = resources; } @@ -179,11 +180,11 @@ export const migrationsCreateCSVExport = async ({resourceId,filename,columns,que if (typeof filename !== 'undefined') { payload['filename'] = filename; } - columns = columns === true ? [] : columns; + columns = (columns as unknown) === true ? [] : columns; if (typeof columns !== 'undefined') { payload['columns'] = columns; } - queries = queries === true ? [] : queries; + queries = (queries as unknown) === true ? [] : queries; if (typeof queries !== 'undefined') { payload['queries'] = queries; } @@ -270,7 +271,7 @@ export const migrationsCreateFirebaseMigration = async ({resources,serviceAccoun sdk; let apiPath = '/migrations/firebase'; let payload = {}; - resources = resources === true ? [] : resources; + resources = (resources as unknown) === true ? [] : resources; if (typeof resources !== 'undefined') { payload['resources'] = resources; } @@ -342,7 +343,7 @@ export const migrationsCreateNHostMigration = async ({resources,subdomain,region sdk; let apiPath = '/migrations/nhost'; let payload = {}; - resources = resources === true ? [] : resources; + resources = (resources as unknown) === true ? [] : resources; if (typeof resources !== 'undefined') { payload['resources'] = resources; } @@ -455,7 +456,7 @@ export const migrationsCreateSupabaseMigration = async ({resources,endpoint,apiK sdk; let apiPath = '/migrations/supabase'; let payload = {}; - resources = resources === true ? [] : resources; + resources = (resources as unknown) === true ? [] : resources; if (typeof resources !== 'undefined') { payload['resources'] = resources; } diff --git a/lib/commands/project.ts b/lib/commands/project.ts index 9e6f33d..48059de 100644 --- a/lib/commands/project.ts +++ b/lib/commands/project.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,8 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { ProjectUsageRange } from '../enums/project-usage-range'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ diff --git a/lib/commands/projects.ts b/lib/commands/projects.ts index f8b2c8c..467890c 100644 --- a/lib/commands/projects.ts +++ b/lib/commands/projects.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,18 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { Region } from '../enums/region'; +import { Api } from '../enums/api'; +import { AuthMethod } from '../enums/auth-method'; +import { OAuthProvider } from '../enums/o-auth-provider'; +import { PlatformType } from '../enums/platform-type'; +import { ApiService } from '../enums/api-service'; +import { SMTPSecure } from '../enums/smtp-secure'; +import { EmailTemplateType } from '../enums/email-template-type'; +import { EmailTemplateLocale } from '../enums/email-template-locale'; +import { SmsTemplateType } from '../enums/sms-template-type'; +import { SmsTemplateLocale } from '../enums/sms-template-locale'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -469,7 +481,7 @@ export const projectsUpdateMembershipsPrivacy = async ({projectId,userName,userE } interface ProjectsUpdateMockNumbersRequestParams { projectId: string; - numbers: object[]; + numbers: string[]; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; @@ -480,7 +492,7 @@ export const projectsUpdateMockNumbers = async ({projectId,numbers,parseOutput = sdk; let apiPath = '/projects/{projectId}/auth/mock-numbers'.replace('{projectId}', projectId); let payload = {}; - numbers = numbers === true ? [] : numbers; + numbers = (numbers as unknown) === true ? [] : numbers; if (typeof numbers !== 'undefined') { payload['numbers'] = numbers; } @@ -854,7 +866,7 @@ export const projectsCreateJWT = async ({projectId,scopes,duration,parseOutput = sdk; let apiPath = '/projects/{projectId}/jwts'.replace('{projectId}', projectId); let payload = {}; - scopes = scopes === true ? [] : scopes; + scopes = (scopes as unknown) === true ? [] : scopes; if (typeof scopes !== 'undefined') { payload['scopes'] = scopes; } @@ -927,7 +939,7 @@ export const projectsCreateKey = async ({projectId,name,scopes,expire,parseOutpu if (typeof name !== 'undefined') { payload['name'] = name; } - scopes = scopes === true ? [] : scopes; + scopes = (scopes as unknown) === true ? [] : scopes; if (typeof scopes !== 'undefined') { payload['scopes'] = scopes; } @@ -998,7 +1010,7 @@ export const projectsUpdateKey = async ({projectId,keyId,name,scopes,expire,pars if (typeof name !== 'undefined') { payload['name'] = name; } - scopes = scopes === true ? [] : scopes; + scopes = (scopes as unknown) === true ? [] : scopes; if (typeof scopes !== 'undefined') { payload['scopes'] = scopes; } @@ -1416,7 +1428,7 @@ export const projectsCreateSMTPTest = async ({projectId,emails,senderName,sender sdk; let apiPath = '/projects/{projectId}/smtp/tests'.replace('{projectId}', projectId); let payload = {}; - emails = emails === true ? [] : emails; + emails = (emails as unknown) === true ? [] : emails; if (typeof emails !== 'undefined') { payload['emails'] = emails; } @@ -1737,7 +1749,7 @@ export const projectsCreateWebhook = async ({projectId,name,events,url,security, if (typeof enabled !== 'undefined') { payload['enabled'] = enabled; } - events = events === true ? [] : events; + events = (events as unknown) === true ? [] : events; if (typeof events !== 'undefined') { payload['events'] = events; } @@ -1824,7 +1836,7 @@ export const projectsUpdateWebhook = async ({projectId,webhookId,name,events,url if (typeof enabled !== 'undefined') { payload['enabled'] = enabled; } - events = events === true ? [] : events; + events = (events as unknown) === true ? [] : events; if (typeof events !== 'undefined') { payload['events'] = events; } diff --git a/lib/commands/proxy.ts b/lib/commands/proxy.ts index fb48eaf..5c80adf 100644 --- a/lib/commands/proxy.ts +++ b/lib/commands/proxy.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,9 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { StatusCode } from '../enums/status-code'; +import { ProxyResourceType } from '../enums/proxy-resource-type'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ diff --git a/lib/commands/pull.ts b/lib/commands/pull.ts index 3c306cc..d7f96eb 100644 --- a/lib/commands/pull.ts +++ b/lib/commands/pull.ts @@ -54,7 +54,7 @@ export const pullResources = async ({ await action({ returnOnZero: true }); } } else { - const answers = await inquirer.prompt(questionsPullResources[0]); + const answers = await inquirer.prompt([questionsPullResources[0]]); const action = actions[answers.resource]; if (action !== undefined) { diff --git a/lib/commands/push.ts b/lib/commands/push.ts index d59f88f..dd46125 100644 --- a/lib/commands/push.ts +++ b/lib/commands/push.ts @@ -92,6 +92,8 @@ import { projectsUpdateSessionAlerts, projectsUpdateMockNumbers, } from "./projects"; +import { ApiService } from '../enums/api-service'; +import { AuthMethod } from '../enums/auth-method'; import { checkDeployConditions } from '../utils'; const JSONbigNative = JSONbig({ storeAsString: false }); @@ -622,7 +624,6 @@ const updateAttribute = (databaseId: string, collectionId: string, attribute: an key: attribute.key, required: attribute.required, xdefault: attribute.default, - array: attribute.array, parseOutput: false }) case 'url': @@ -632,7 +633,6 @@ const updateAttribute = (databaseId: string, collectionId: string, attribute: an key: attribute.key, required: attribute.required, xdefault: attribute.default, - array: attribute.array, parseOutput: false }) case 'ip': @@ -642,7 +642,6 @@ const updateAttribute = (databaseId: string, collectionId: string, attribute: an key: attribute.key, required: attribute.required, xdefault: attribute.default, - array: attribute.array, parseOutput: false }) case 'enum': @@ -653,7 +652,6 @@ const updateAttribute = (databaseId: string, collectionId: string, attribute: an elements: attribute.elements, required: attribute.required, xdefault: attribute.default, - array: attribute.array, parseOutput: false }) default: @@ -661,10 +659,8 @@ const updateAttribute = (databaseId: string, collectionId: string, attribute: an databaseId, collectionId, key: attribute.key, - size: attribute.size, required: attribute.required, xdefault: attribute.default, - array: attribute.array, parseOutput: false }) @@ -678,7 +674,6 @@ const updateAttribute = (databaseId: string, collectionId: string, attribute: an min: attribute.min, max: attribute.max, xdefault: attribute.default, - array: attribute.array, parseOutput: false }) case 'double': @@ -690,7 +685,6 @@ const updateAttribute = (databaseId: string, collectionId: string, attribute: an min: attribute.min, max: attribute.max, xdefault: attribute.default, - array: attribute.array, parseOutput: false }) case 'boolean': @@ -700,7 +694,6 @@ const updateAttribute = (databaseId: string, collectionId: string, attribute: an key: attribute.key, required: attribute.required, xdefault: attribute.default, - array: attribute.array, parseOutput: false }) case 'datetime': @@ -710,18 +703,13 @@ const updateAttribute = (databaseId: string, collectionId: string, attribute: an key: attribute.key, required: attribute.required, xdefault: attribute.default, - array: attribute.array, parseOutput: false }) case 'relationship': return databasesUpdateRelationshipAttribute({ databaseId, collectionId, - relatedCollectionId: attribute.relatedTable ?? attribute.relatedCollection, - type: attribute.relationType, - twoWay: attribute.twoWay, key: attribute.key, - twoWayKey: attribute.twoWayKey, onDelete: attribute.onDelete, parseOutput: false }) @@ -1034,7 +1022,7 @@ const pushResources = async (): Promise => { await action({ returnOnZero: true }); } } else { - const answers = await inquirer.prompt(questionsPushResources[0]); + const answers = await inquirer.prompt(questionsPushResources); const action = actions[answers.resource]; if (action !== undefined) { @@ -1093,7 +1081,7 @@ const pushSettings = async (): Promise => { for (let [service, status] of Object.entries(settings.services)) { await projectsUpdateServiceStatus({ projectId, - service, + service: service as ApiService, status, parseOutput: false }); @@ -1119,7 +1107,7 @@ const pushSettings = async (): Promise => { for (let [method, status] of Object.entries(settings.auth.methods)) { await projectsUpdateAuthStatus({ projectId, - method, + method: method as AuthMethod, status, parseOutput: false }); @@ -1157,7 +1145,7 @@ const pushSite = async({ siteId, async: asyncDeploy, code, withVariables }: Push } if (siteIds.length <= 0) { - const answers = await inquirer.prompt(questionsPushSites[0]); + const answers = await inquirer.prompt(questionsPushSites); if (answers.sites) { siteIds.push(...answers.sites); } @@ -1241,8 +1229,6 @@ const pushSite = async({ siteId, async: asyncDeploy, code, withVariables }: Push buildCommand: site.buildCommand, installCommand: site.installCommand, outputDirectory: site.outputDirectory, - fallbackFile: site.fallbackFile, - vars: JSON.stringify(response.vars), parseOutput: false }); } catch (e: any) { @@ -1269,7 +1255,6 @@ const pushSite = async({ siteId, async: asyncDeploy, code, withVariables }: Push buildCommand: site.buildCommand, installCommand: site.installCommand, outputDirectory: site.outputDirectory, - fallbackFile: site.fallbackFile, adapter: site.adapter, timeout: site.timeout, enabled: site.enabled, @@ -1356,10 +1341,6 @@ const pushSite = async({ siteId, async: asyncDeploy, code, withVariables }: Push updaterRow.update({ status: 'Pushing' }).replaceSpinner(SPINNER_ARC); response = await sitesCreateDeployment({ siteId: site['$id'], - buildCommand: site.buildCommand, - installCommand: site.installCommand, - outputDirectory: site.outputDirectory, - fallbackFile: site.fallbackFile, code: site.path, activate: true, parseOutput: false @@ -1488,7 +1469,7 @@ const pushFunction = async ({ functionId, async: asyncDeploy, code, withVariable } if (functionIds.length <= 0) { - const answers = await inquirer.prompt(questionsPushFunctions[0]); + const answers = await inquirer.prompt(questionsPushFunctions); if (answers.functions) { functionIds.push(...answers.functions); } @@ -1571,7 +1552,6 @@ const pushFunction = async ({ functionId, async: asyncDeploy, code, withVariable entrypoint: func.entrypoint, commands: func.commands, scopes: func.scopes, - vars: JSON.stringify(response.vars), parseOutput: false }); } catch (e: any) { @@ -1665,7 +1645,6 @@ const pushFunction = async ({ functionId, async: asyncDeploy, code, withVariable await Promise.all(envVariables.map(async (variable) => { await functionsCreateVariable({ functionId: func['$id'], - variableId: ID.unique(), key: variable.key, value: variable.value, parseOutput: false, @@ -2314,7 +2293,7 @@ const pushBucket = async ({ returnOnZero }: PushBucketOptions = { returnOnZero: } if (bucketIds.length === 0) { - const answers = await inquirer.prompt(questionsPushBuckets[0]) + const answers = await inquirer.prompt(questionsPushBuckets) if (answers.buckets) { bucketIds.push(...answers.buckets); } @@ -2403,7 +2382,7 @@ const pushTeam = async ({ returnOnZero }: PushTeamOptions = { returnOnZero: fals } if (teamIds.length === 0) { - const answers = await inquirer.prompt(questionsPushTeams[0]) + const answers = await inquirer.prompt(questionsPushTeams) if (answers.teams) { teamIds.push(...answers.teams); } @@ -2476,7 +2455,7 @@ const pushMessagingTopic = async ({ returnOnZero }: PushMessagingTopicOptions = } if (topicsIds.length === 0) { - const answers = await inquirer.prompt(questionsPushMessagingTopics[0]) + const answers = await inquirer.prompt(questionsPushMessagingTopics) if (answers.topics) { topicsIds.push(...answers.topics); } diff --git a/lib/commands/run.ts b/lib/commands/run.ts index 8caf2fe..d3f688d 100644 --- a/lib/commands/run.ts +++ b/lib/commands/run.ts @@ -1,7 +1,7 @@ import { Tail } from 'tail'; import { parse as parseDotenv } from 'dotenv'; import chalk from 'chalk'; -import ignore = require('ignore'); +import ignore from 'ignore'; import tar = require('tar'); import fs = require('fs'); import chokidar from 'chokidar'; @@ -28,7 +28,7 @@ interface RunFunctionOptions { const runFunction = async ({ port, functionId, withVariables, reload, userId }: RunFunctionOptions = {}): Promise => { // Selection if(!functionId) { - const answers = await inquirer.prompt(questionsRunFunctions[0]); + const answers = await inquirer.prompt([questionsRunFunctions[0]]); functionId = answers.function; } @@ -250,13 +250,12 @@ const runFunction = async ({ port, functionId, withVariables, reload, userId }: await tar .extract({ keep: true, - gzip: true, sync: true, cwd: hotSwapPath, file: buildPath }); - const ignorer = ignore.default(); + const ignorer = ignore(); ignorer.add('.appwrite'); if (func.ignore) { ignorer.add(func.ignore); diff --git a/lib/commands/sites.ts b/lib/commands/sites.ts index f213f38..4585060 100644 --- a/lib/commands/sites.ts +++ b/lib/commands/sites.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,14 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { Framework } from '../enums/framework'; +import { BuildRuntime } from '../enums/build-runtime'; +import { Adapter } from '../enums/adapter'; +import { UsageRange } from '../enums/usage-range'; +import { TemplateReferenceType } from '../enums/template-reference-type'; +import { VCSReferenceType } from '../enums/vcs-reference-type'; +import { DeploymentDownloadType } from '../enums/deployment-download-type'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -571,10 +579,10 @@ interface SitesCreateDeploymentRequestParams { overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; - onProgress?: (progress: number) => void; + onProgress?: (progress: UploadProgress) => void; } -export const sitesCreateDeployment = async ({siteId,code,activate,installCommand,buildCommand,outputDirectory,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}: SitesCreateDeploymentRequestParams): Promise => { +export const sitesCreateDeployment = async ({siteId,code,activate,installCommand,buildCommand,outputDirectory,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = (progress: any) => {}}: SitesCreateDeploymentRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/sites/{siteId}/deployments'.replace('{siteId}', siteId); @@ -628,15 +636,18 @@ export const sitesCreateDeployment = async ({siteId,code,activate,installCommand const nodeStream = fs.createReadStream(filePath); const stream = convertReadStreamToReadableStream(nodeStream); - if (typeof filePath !== 'undefined') { - code = { type: 'file', stream, filename: pathLib.basename(filePath), size: fs.statSync(filePath).size }; - payload['code'] = code - } + const codeUpload: FileInput = { + type: 'file', + stream, + filename: pathLib.basename(filePath), + size: fs.statSync(filePath).size + }; + payload['code'] = codeUpload; if (typeof activate !== 'undefined') { payload['activate'] = activate; } - const size = code.size; + const size = codeUpload.size; const apiHeaders = { 'content-type': 'multipart/form-data', @@ -678,7 +689,7 @@ export const sitesCreateDeployment = async ({siteId,code,activate,installCommand apiHeaders['x-appwrite-id'] = id; } - payload['code'] = { type: 'file', file: new File([uploadableChunkTrimmed], code.filename), filename: code.filename }; + payload['code'] = { type: 'file', file: new File([uploadableChunkTrimmed], codeUpload.filename), filename: codeUpload.filename }; response = await client.call('post', apiPath, apiHeaders, payload); @@ -701,7 +712,7 @@ export const sitesCreateDeployment = async ({siteId,code,activate,installCommand currentPosition = 0; } - for await (const chunk of code.stream) { + for await (const chunk of codeUpload.stream) { for(const b of chunk) { uploadableChunk[currentPosition] = b; diff --git a/lib/commands/storage.ts b/lib/commands/storage.ts index a39f491..69c2331 100644 --- a/lib/commands/storage.ts +++ b/lib/commands/storage.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,11 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { Compression } from '../enums/compression'; +import { ImageGravity } from '../enums/image-gravity'; +import { ImageFormat } from '../enums/image-format'; +import { UsageRange } from '../enums/usage-range'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -104,7 +109,7 @@ export const storageCreateBucket = async ({bucketId,name,permissions,fileSecurit if (typeof name !== 'undefined') { payload['name'] = name; } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -117,7 +122,7 @@ export const storageCreateBucket = async ({bucketId,name,permissions,fileSecurit if (typeof maximumFileSize !== 'undefined') { payload['maximumFileSize'] = maximumFileSize; } - allowedFileExtensions = allowedFileExtensions === true ? [] : allowedFileExtensions; + allowedFileExtensions = (allowedFileExtensions as unknown) === true ? [] : allowedFileExtensions; if (typeof allowedFileExtensions !== 'undefined') { payload['allowedFileExtensions'] = allowedFileExtensions; } @@ -202,7 +207,7 @@ export const storageUpdateBucket = async ({bucketId,name,permissions,fileSecurit if (typeof name !== 'undefined') { payload['name'] = name; } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -215,7 +220,7 @@ export const storageUpdateBucket = async ({bucketId,name,permissions,fileSecurit if (typeof maximumFileSize !== 'undefined') { payload['maximumFileSize'] = maximumFileSize; } - allowedFileExtensions = allowedFileExtensions === true ? [] : allowedFileExtensions; + allowedFileExtensions = (allowedFileExtensions as unknown) === true ? [] : allowedFileExtensions; if (typeof allowedFileExtensions !== 'undefined') { payload['allowedFileExtensions'] = allowedFileExtensions; } @@ -321,10 +326,10 @@ interface StorageCreateFileRequestParams { overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; - onProgress?: (progress: number) => void; + onProgress?: (progress: UploadProgress) => void; } -export const storageCreateFile = async ({bucketId,fileId,file,permissions,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = () => {}}: StorageCreateFileRequestParams): Promise => { +export const storageCreateFile = async ({bucketId,fileId,file,permissions,parseOutput = true, overrideForCli = false, sdk = undefined,onProgress = (progress: any) => {}}: StorageCreateFileRequestParams): Promise => { let client = !sdk ? await sdkForProject() : sdk; let apiPath = '/storage/buckets/{bucketId}/files'.replace('{bucketId}', bucketId); @@ -336,16 +341,19 @@ export const storageCreateFile = async ({bucketId,fileId,file,permissions,parseO const nodeStream = fs.createReadStream(filePath); const stream = convertReadStreamToReadableStream(nodeStream); - if (typeof filePath !== 'undefined') { - file = { type: 'file', stream, filename: pathLib.basename(filePath), size: fs.statSync(filePath).size }; - payload['file'] = file - } - permissions = permissions === true ? [] : permissions; + const fileUpload: FileInput = { + type: 'file', + stream, + filename: pathLib.basename(filePath), + size: fs.statSync(filePath).size + }; + payload['file'] = fileUpload; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } - const size = file.size; + const size = fileUpload.size; const apiHeaders = { 'content-type': 'multipart/form-data', @@ -395,7 +403,7 @@ export const storageCreateFile = async ({bucketId,fileId,file,permissions,parseO apiHeaders['x-appwrite-id'] = id; } - payload['file'] = { type: 'file', file: new File([uploadableChunkTrimmed], file.filename), filename: file.filename }; + payload['file'] = { type: 'file', file: new File([uploadableChunkTrimmed], fileUpload.filename), filename: fileUpload.filename }; response = await client.call('post', apiPath, apiHeaders, payload); @@ -418,7 +426,7 @@ export const storageCreateFile = async ({bucketId,fileId,file,permissions,parseO currentPosition = 0; } - for await (const chunk of file.stream) { + for await (const chunk of fileUpload.stream) { for(const b of chunk) { uploadableChunk[currentPosition] = b; @@ -490,7 +498,7 @@ export const storageUpdateFile = async ({bucketId,fileId,name,permissions,parseO if (typeof name !== 'undefined') { payload['name'] = name; } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } diff --git a/lib/commands/tables-db.ts b/lib/commands/tables-db.ts index 28a314f..a15aa3f 100644 --- a/lib/commands/tables-db.ts +++ b/lib/commands/tables-db.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,11 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { UsageRange } from '../enums/usage-range'; +import { RelationshipType } from '../enums/relationship-type'; +import { RelationMutate } from '../enums/relation-mutate'; +import { IndexType } from '../enums/index-type'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -267,7 +272,7 @@ export const tablesDBDeleteTransaction = async ({transactionId,parseOutput = tru } interface TablesDBCreateOperationsRequestParams { transactionId: string; - operations?: object[]; + operations?: string[]; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; @@ -278,7 +283,7 @@ export const tablesDBCreateOperations = async ({transactionId,operations,parseOu sdk; let apiPath = '/tablesdb/transactions/{transactionId}/operations'.replace('{transactionId}', transactionId); let payload = {}; - operations = operations === true ? [] : operations; + operations = (operations as unknown) === true ? [] : operations; if (typeof operations !== 'undefined') { payload['operations'] = operations; } @@ -468,8 +473,8 @@ interface TablesDBCreateTableRequestParams { permissions?: string[]; rowSecurity?: boolean; enabled?: boolean; - columns?: object[]; - indexes?: object[]; + columns?: string[]; + indexes?: string[]; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; @@ -486,7 +491,7 @@ export const tablesDBCreateTable = async ({databaseId,tableId,name,permissions,r if (typeof name !== 'undefined') { payload['name'] = name; } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -496,11 +501,11 @@ export const tablesDBCreateTable = async ({databaseId,tableId,name,permissions,r if (typeof enabled !== 'undefined') { payload['enabled'] = enabled; } - columns = columns === true ? [] : columns; + columns = (columns as unknown) === true ? [] : columns; if (typeof columns !== 'undefined') { payload['columns'] = columns; } - indexes = indexes === true ? [] : indexes; + indexes = (indexes as unknown) === true ? [] : indexes; if (typeof indexes !== 'undefined') { payload['indexes'] = indexes; } @@ -569,7 +574,7 @@ export const tablesDBUpdateTable = async ({databaseId,tableId,name,permissions,r if (typeof name !== 'undefined') { payload['name'] = name; } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -929,7 +934,7 @@ export const tablesDBCreateEnumColumn = async ({databaseId,tableId,key,elements, if (typeof key !== 'undefined') { payload['key'] = key; } - elements = elements === true ? [] : elements; + elements = (elements as unknown) === true ? [] : elements; if (typeof elements !== 'undefined') { payload['elements'] = elements; } @@ -974,7 +979,7 @@ export const tablesDBUpdateEnumColumn = async ({databaseId,tableId,key,elements, sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/columns/enum/{key}'.replace('{databaseId}', databaseId).replace('{tableId}', tableId).replace('{key}', key); let payload = {}; - elements = elements === true ? [] : elements; + elements = (elements as unknown) === true ? [] : elements; if (typeof elements !== 'undefined') { payload['elements'] = elements; } @@ -1304,7 +1309,7 @@ export const tablesDBCreateLineColumn = async ({databaseId,tableId,key,required, if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1342,7 +1347,7 @@ export const tablesDBUpdateLineColumn = async ({databaseId,tableId,key,required, if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1385,7 +1390,7 @@ export const tablesDBCreatePointColumn = async ({databaseId,tableId,key,required if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1423,7 +1428,7 @@ export const tablesDBUpdatePointColumn = async ({databaseId,tableId,key,required if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1466,7 +1471,7 @@ export const tablesDBCreatePolygonColumn = async ({databaseId,tableId,key,requir if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1504,7 +1509,7 @@ export const tablesDBUpdatePolygonColumn = async ({databaseId,tableId,key,requir if (typeof required !== 'undefined') { payload['required'] = required; } - xdefault = xdefault === true ? [] : xdefault; + xdefault = (xdefault as unknown) === true ? [] : xdefault; if (typeof xdefault !== 'undefined') { payload['default'] = xdefault; } @@ -1913,15 +1918,15 @@ export const tablesDBCreateIndex = async ({databaseId,tableId,key,type,columns,o if (typeof type !== 'undefined') { payload['type'] = type; } - columns = columns === true ? [] : columns; + columns = (columns as unknown) === true ? [] : columns; if (typeof columns !== 'undefined') { payload['columns'] = columns; } - orders = orders === true ? [] : orders; + orders = (orders as unknown) === true ? [] : orders; if (typeof orders !== 'undefined') { payload['orders'] = orders; } - lengths = lengths === true ? [] : lengths; + lengths = (lengths as unknown) === true ? [] : lengths; if (typeof lengths !== 'undefined') { payload['lengths'] = lengths; } @@ -2076,7 +2081,7 @@ interface TablesDBCreateRowRequestParams { databaseId: string; tableId: string; rowId: string; - data: object; + data: string; permissions?: string[]; transactionId?: string; overrideForCli?: boolean; @@ -2095,7 +2100,7 @@ export const tablesDBCreateRow = async ({databaseId,tableId,rowId,data,permissio if (typeof data !== 'undefined') { payload['data'] = JSON.parse(data); } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -2119,7 +2124,7 @@ export const tablesDBCreateRow = async ({databaseId,tableId,rowId,data,permissio interface TablesDBCreateRowsRequestParams { databaseId: string; tableId: string; - rows: object[]; + rows: string[]; transactionId?: string; overrideForCli?: boolean; parseOutput?: boolean; @@ -2131,7 +2136,7 @@ export const tablesDBCreateRows = async ({databaseId,tableId,rows,transactionId, sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); let payload = {}; - rows = rows === true ? [] : rows; + rows = (rows as unknown) === true ? [] : rows; if (typeof rows !== 'undefined') { payload['rows'] = rows; } @@ -2155,7 +2160,7 @@ export const tablesDBCreateRows = async ({databaseId,tableId,rows,transactionId, interface TablesDBUpsertRowsRequestParams { databaseId: string; tableId: string; - rows: object[]; + rows: string[]; transactionId?: string; overrideForCli?: boolean; parseOutput?: boolean; @@ -2167,7 +2172,7 @@ export const tablesDBUpsertRows = async ({databaseId,tableId,rows,transactionId, sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); let payload = {}; - rows = rows === true ? [] : rows; + rows = (rows as unknown) === true ? [] : rows; if (typeof rows !== 'undefined') { payload['rows'] = rows; } @@ -2191,7 +2196,7 @@ export const tablesDBUpsertRows = async ({databaseId,tableId,rows,transactionId, interface TablesDBUpdateRowsRequestParams { databaseId: string; tableId: string; - data?: object; + data?: string; queries?: string[]; transactionId?: string; overrideForCli?: boolean; @@ -2207,7 +2212,7 @@ export const tablesDBUpdateRows = async ({databaseId,tableId,data,queries,transa if (typeof data !== 'undefined') { payload['data'] = JSON.parse(data); } - queries = queries === true ? [] : queries; + queries = (queries as unknown) === true ? [] : queries; if (typeof queries !== 'undefined') { payload['queries'] = queries; } @@ -2243,7 +2248,7 @@ export const tablesDBDeleteRows = async ({databaseId,tableId,queries,transaction sdk; let apiPath = '/tablesdb/{databaseId}/tables/{tableId}/rows'.replace('{databaseId}', databaseId).replace('{tableId}', tableId); let payload = {}; - queries = queries === true ? [] : queries; + queries = (queries as unknown) === true ? [] : queries; if (typeof queries !== 'undefined') { payload['queries'] = queries; } @@ -2308,7 +2313,7 @@ interface TablesDBUpsertRowRequestParams { databaseId: string; tableId: string; rowId: string; - data?: object; + data?: string; permissions?: string[]; transactionId?: string; overrideForCli?: boolean; @@ -2324,7 +2329,7 @@ export const tablesDBUpsertRow = async ({databaseId,tableId,rowId,data,permissio if (typeof data !== 'undefined') { payload['data'] = JSON.parse(data); } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } @@ -2349,7 +2354,7 @@ interface TablesDBUpdateRowRequestParams { databaseId: string; tableId: string; rowId: string; - data?: object; + data?: string; permissions?: string[]; transactionId?: string; overrideForCli?: boolean; @@ -2365,7 +2370,7 @@ export const tablesDBUpdateRow = async ({databaseId,tableId,rowId,data,permissio if (typeof data !== 'undefined') { payload['data'] = JSON.parse(data); } - permissions = permissions === true ? [] : permissions; + permissions = (permissions as unknown) === true ? [] : permissions; if (typeof permissions !== 'undefined') { payload['permissions'] = permissions; } diff --git a/lib/commands/teams.ts b/lib/commands/teams.ts index 0f10a3a..e3dd4a1 100644 --- a/lib/commands/teams.ts +++ b/lib/commands/teams.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,7 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -96,7 +97,7 @@ export const teamsCreate = async ({teamId,name,roles,parseOutput = true, overrid if (typeof name !== 'undefined') { payload['name'] = name; } - roles = roles === true ? [] : roles; + roles = (roles as unknown) === true ? [] : roles; if (typeof roles !== 'undefined') { payload['roles'] = roles; } @@ -297,7 +298,7 @@ export const teamsCreateMembership = async ({teamId,roles,email,userId,phone,url if (typeof phone !== 'undefined') { payload['phone'] = phone; } - roles = roles === true ? [] : roles; + roles = (roles as unknown) === true ? [] : roles; if (typeof roles !== 'undefined') { payload['roles'] = roles; } @@ -361,7 +362,7 @@ export const teamsUpdateMembership = async ({teamId,membershipId,roles,parseOutp sdk; let apiPath = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); let payload = {}; - roles = roles === true ? [] : roles; + roles = (roles as unknown) === true ? [] : roles; if (typeof roles !== 'undefined') { payload['roles'] = roles; } @@ -468,7 +469,7 @@ export const teamsGetPrefs = async ({teamId,parseOutput = true, overrideForCli = } interface TeamsUpdatePrefsRequestParams { teamId: string; - prefs: object; + prefs: string; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; diff --git a/lib/commands/tokens.ts b/lib/commands/tokens.ts index 4292ce1..0c2068d 100644 --- a/lib/commands/tokens.ts +++ b/lib/commands/tokens.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,7 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ diff --git a/lib/commands/users.ts b/lib/commands/users.ts index 6d9d21e..0511243 100644 --- a/lib/commands/users.ts +++ b/lib/commands/users.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,11 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { PasswordHash } from '../enums/password-hash'; +import { UsageRange } from '../enums/usage-range'; +import { AuthenticatorType } from '../enums/authenticator-type'; +import { MessagingProviderType } from '../enums/messaging-provider-type'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ @@ -667,7 +672,7 @@ export const usersUpdateLabels = async ({userId,labels,parseOutput = true, overr sdk; let apiPath = '/users/{userId}/labels'.replace('{userId}', userId); let payload = {}; - labels = labels === true ? [] : labels; + labels = (labels as unknown) === true ? [] : labels; if (typeof labels !== 'undefined') { payload['labels'] = labels; } @@ -1031,7 +1036,7 @@ export const usersGetPrefs = async ({userId,parseOutput = true, overrideForCli = } interface UsersUpdatePrefsRequestParams { userId: string; - prefs: object; + prefs: string; overrideForCli?: boolean; parseOutput?: boolean; sdk?: Client; diff --git a/lib/commands/vcs.ts b/lib/commands/vcs.ts index 7b5de57..c2c7cc4 100644 --- a/lib/commands/vcs.ts +++ b/lib/commands/vcs.ts @@ -1,7 +1,7 @@ import fs = require('fs'); import pathLib = require('path'); import tar = require('tar'); -import ignore = require('ignore'); +import ignore from 'ignore'; import { promisify } from 'util'; import Client from '../client'; import { getAllFiles, showConsoleLink } from '../utils'; @@ -11,6 +11,8 @@ import { parse, actionRunner, parseInteger, parseBool, commandDescriptions, succ import { localConfig, globalConfig } from '../config'; import { File } from 'undici'; import { ReadableStream } from 'stream/web'; +import type { UploadProgress, FileInput } from '../types'; +import { VCSDetectionType } from '../enums/vcs-detection-type'; function convertReadStreamToReadableStream(readStream: fs.ReadStream): ReadableStream { return new ReadableStream({ diff --git a/lib/config.ts b/lib/config.ts index c076c55..9e2ad94 100644 --- a/lib/config.ts +++ b/lib/config.ts @@ -3,7 +3,22 @@ import fs = require('fs'); import _path = require('path'); import process = require('process'); import JSONbig = require('json-bigint'); -import type { ConfigData, SessionData, GlobalConfigData, ProjectConfigData } from './types'; +import type { + BucketConfig, + CollectionConfig, + ConfigData, + Entity, + FunctionConfig, + GlobalConfigData, + ProjectConfigData, + ProjectSettings, + RawProjectSettings, + SessionData, + SiteConfig, + TableConfig, + TeamConfig, + TopicConfig +} from './types'; const JSONBigInt = JSONbig({ storeAsString: false }); @@ -102,7 +117,7 @@ function whitelistKeys( } class Config { - protected path: string; + readonly path: string; protected data: T; constructor(path: string) { @@ -165,19 +180,19 @@ class Config { return JSONBigInt.stringify(this.data, null, 4); } - protected _getDBEntities(entityType: string): any[] { + protected _getDBEntities(entityType: string): Entity[] { if (!this.has(entityType)) { return []; } - return this.get(entityType); + return this.get(entityType) as Entity[]; } - protected _getDBEntity(entityType: string, $id: string): any { + protected _getDBEntity(entityType: string, $id: string): Entity | Record { if (!this.has(entityType)) { return {}; } - const entities = this.get(entityType); + const entities = this.get(entityType) as Entity[]; for (let i = 0; i < entities.length; i++) { if (entities[i]['$id'] == $id) { return entities[i]; @@ -189,26 +204,26 @@ class Config { protected _addDBEntity( entityType: string, - props: any, + props: Entity, keysSet: Set, nestedKeys: Record> = {} ): void { props = whitelistKeys(props, keysSet, nestedKeys); if (!this.has(entityType)) { - this.set(entityType, []); + (this.set as (key: string, value: Entity[]) => void)(entityType, []); } - const entities = this.get(entityType); + const entities = this.get(entityType) as Entity[]; for (let i = 0; i < entities.length; i++) { if (entities[i]['$id'] == props['$id']) { entities[i] = props; - this.set(entityType, entities); + (this.set as (key: string, value: Entity[]) => void)(entityType, entities); return; } } entities.push(props); - this.set(entityType, entities); + (this.set as (key: string, value: Entity[]) => void)(entityType, entities); } } @@ -253,26 +268,26 @@ class Local extends Config { } getEndpoint(): string { - return this.get('endpoint' as any) || ''; + return (this.get('endpoint' as keyof ProjectConfigData) as string) || ''; } setEndpoint(endpoint: string): void { this.set('endpoint' as any, endpoint); } - getSites(): any[] { + getSites(): SiteConfig[] { if (!this.has('sites')) { return []; } - return this.get('sites' as any); + return this.get('sites') ?? []; } - getSite($id: string): any { + getSite($id: string): SiteConfig | Record { if (!this.has('sites')) { return {}; } - const sites = this.get('sites' as any); + const sites = this.get('sites') ?? []; for (let i = 0; i < sites.length; i++) { if (sites[i]['$id'] == $id) { return sites[i]; @@ -282,44 +297,44 @@ class Local extends Config { return {}; } - addSite(props: any): void { + addSite(props: SiteConfig): void { props = whitelistKeys(props, KeysSite, { vars: KeysVars, }); if (!this.has('sites')) { - this.set('sites' as any, []); + this.set('sites', []); } - const sites = this.get('sites' as any); + const sites = this.get('sites') ?? []; for (let i = 0; i < sites.length; i++) { if (sites[i]['$id'] == props['$id']) { sites[i] = { ...sites[i], ...props, }; - this.set('sites' as any, sites); + this.set('sites', sites); return; } } sites.push(props); - this.set('sites' as any, sites); + this.set('sites', sites); } - getFunctions(): any[] { + getFunctions(): FunctionConfig[] { if (!this.has('functions')) { return []; } - return this.get('functions' as any); + return this.get('functions') ?? []; } - getFunction($id: string): any { + getFunction($id: string): FunctionConfig | Record { if (!this.has('functions')) { return {}; } - const functions = this.get('functions' as any); + const functions = this.get('functions') ?? []; for (let i = 0; i < functions.length; i++) { if (functions[i]['$id'] == $id) { return functions[i]; @@ -329,44 +344,44 @@ class Local extends Config { return {}; } - addFunction(props: any): void { + addFunction(props: FunctionConfig): void { props = whitelistKeys(props, KeysFunction, { vars: KeysVars, }); if (!this.has('functions')) { - this.set('functions' as any, []); + this.set('functions', []); } - const functions = this.get('functions' as any); + const functions = this.get('functions') ?? []; for (let i = 0; i < functions.length; i++) { if (functions[i]['$id'] == props['$id']) { functions[i] = { ...functions[i], ...props, }; - this.set('functions' as any, functions); + this.set('functions', functions); return; } } functions.push(props); - this.set('functions' as any, functions); + this.set('functions', functions); } - getCollections(): any[] { + getCollections(): CollectionConfig[] { if (!this.has('collections')) { return []; } - return this.get('collections' as any); + return this.get('collections') ?? []; } - getCollection($id: string): any { + getCollection($id: string): CollectionConfig | Record { if (!this.has('collections')) { return {}; } - const collections = this.get('collections' as any); + const collections = this.get('collections') ?? []; for (let i = 0; i < collections.length; i++) { if (collections[i]['$id'] == $id) { return collections[i]; @@ -376,41 +391,41 @@ class Local extends Config { return {}; } - addCollection(props: any): void { + addCollection(props: CollectionConfig): void { props = whitelistKeys(props, KeysCollection, { attributes: KeysAttributes, indexes: KeyIndexes, }); if (!this.has('collections')) { - this.set('collections' as any, []); + this.set('collections', []); } - const collections = this.get('collections' as any); + const collections = this.get('collections') ?? []; for (let i = 0; i < collections.length; i++) { if (collections[i]['$id'] == props['$id'] && collections[i]['databaseId'] == props['databaseId']) { collections[i] = props; - this.set('collections' as any, collections); + this.set('collections', collections); return; } } collections.push(props); - this.set('collections' as any, collections); + this.set('collections', collections); } - getTables(): any[] { + getTables(): TableConfig[] { if (!this.has('tables')) { return []; } - return this.get('tables' as any); + return this.get('tables') ?? []; } - getTable($id: string): any { + getTable($id: string): TableConfig | Record { if (!this.has('tables')) { return {}; } - const tables = this.get('tables' as any); + const tables = this.get('tables') ?? []; for (let i = 0; i < tables.length; i++) { if (tables[i]['$id'] == $id) { return tables[i]; @@ -420,41 +435,41 @@ class Local extends Config { return {}; } - addTable(props: any): void { + addTable(props: TableConfig): void { props = whitelistKeys(props, KeysTable, { columns: KeysColumns, indexes: KeyIndexesColumns, }); if (!this.has('tables')) { - this.set('tables' as any, []); + this.set('tables', []); } - const tables = this.get('tables' as any); + const tables = this.get('tables') ?? []; for (let i = 0; i < tables.length; i++) { if (tables[i]['$id'] == props['$id'] && tables[i]['databaseId'] == props['databaseId']) { tables[i] = props; - this.set('tables' as any, tables); + this.set('tables', tables); return; } } tables.push(props); - this.set('tables' as any, tables); + this.set('tables', tables); } - getBuckets(): any[] { + getBuckets(): BucketConfig[] { if (!this.has('buckets')) { return []; } - return this.get('buckets' as any); + return this.get('buckets') ?? []; } - getBucket($id: string): any { + getBucket($id: string): BucketConfig | Record { if (!this.has('buckets')) { return {}; } - const buckets = this.get('buckets' as any); + const buckets = this.get('buckets') ?? []; for (let i = 0; i < buckets.length; i++) { if (buckets[i]['$id'] == $id) { return buckets[i]; @@ -464,64 +479,64 @@ class Local extends Config { return {}; } - addBucket(props: any): void { + addBucket(props: BucketConfig): void { props = whitelistKeys(props, KeysStorage); if (!this.has('buckets')) { - this.set('buckets' as any, []); + this.set('buckets', []); } - const buckets = this.get('buckets' as any); + const buckets = this.get('buckets') ?? []; for (let i = 0; i < buckets.length; i++) { if (buckets[i]['$id'] == props['$id']) { buckets[i] = props; - this.set('buckets' as any, buckets); + this.set('buckets', buckets); return; } } buckets.push(props); - this.set('buckets' as any, buckets); + this.set('buckets', buckets); } - getMessagingTopics(): any[] { + getMessagingTopics(): TopicConfig[] { if (!this.has('topics')) { return []; } - return this.get('topics' as any); + return this.get('topics') ?? []; } - getMessagingTopic($id: string): any { + getMessagingTopic($id: string): TopicConfig | Record { if (!this.has('topics')) { return {}; } - const topic = this.get('topics' as any); - for (let i = 0; i < topic.length; i++) { - if (topic[i]['$id'] == $id) { - return topic[i]; + const topics = this.get('topics') ?? []; + for (let i = 0; i < topics.length; i++) { + if (topics[i]['$id'] == $id) { + return topics[i]; } } return {}; } - addMessagingTopic(props: any): void { + addMessagingTopic(props: TopicConfig): void { props = whitelistKeys(props, KeysTopics); if (!this.has('topics')) { - this.set('topics' as any, []); + this.set('topics', []); } - const topics = this.get('topics' as any); + const topics = this.get('topics') ?? []; for (let i = 0; i < topics.length; i++) { if (topics[i]['$id'] === props['$id']) { topics[i] = props; - this.set('topics' as any, topics); + this.set('topics', topics); return; } } topics.push(props); - this.set('topics' as any, topics); + this.set('topics', topics); } getTablesDBs(): any[] { @@ -548,19 +563,19 @@ class Local extends Config { this._addDBEntity('databases', props, KeysDatabase); } - getTeams(): any[] { + getTeams(): TeamConfig[] { if (!this.has('teams')) { return []; } - return this.get('teams' as any); + return this.get('teams') ?? []; } - getTeam($id: string): any { + getTeam($id: string): TeamConfig | Record { if (!this.has('teams')) { return {}; } - const teams = this.get('teams' as any); + const teams = this.get('teams') ?? []; for (let i = 0; i < teams.length; i++) { if (teams[i]['$id'] == $id) { return teams[i]; @@ -570,51 +585,51 @@ class Local extends Config { return {}; } - addTeam(props: any): void { + addTeam(props: TeamConfig): void { props = whitelistKeys(props, KeysTeams); if (!this.has('teams')) { - this.set('teams' as any, []); + this.set('teams', []); } - const teams = this.get('teams' as any); + const teams = this.get('teams') ?? []; for (let i = 0; i < teams.length; i++) { if (teams[i]['$id'] == props['$id']) { teams[i] = props; - this.set('teams' as any, teams); + this.set('teams', teams); return; } } teams.push(props); - this.set('teams' as any, teams); + this.set('teams', teams); } - getProject(): { projectId?: string; projectName?: string; projectSettings?: any } { + getProject(): { projectId?: string; projectName?: string; projectSettings?: ProjectSettings } { if (!this.has('projectId')) { return {}; } return { - projectId: this.get('projectId' as any), - projectName: this.get('projectName' as any), - projectSettings: this.get('settings' as any), + projectId: this.get('projectId'), + projectName: this.get('projectName'), + projectSettings: this.get('settings'), }; } - setProject(projectId: string, projectName: string = '', projectSettings: any = undefined): void { - this.set('projectId' as any, projectId); + setProject(projectId: string, projectName: string = '', projectSettings?: RawProjectSettings): void { + this.set('projectId', projectId); if (projectName !== '') { - this.set('projectName' as any, projectName); + this.set('projectName', projectName); } if (projectSettings === undefined) { return; } - this.set('settings' as any, this.createSettingsObject(projectSettings)); + this.set('settings', this.createSettingsObject(projectSettings)); } - createSettingsObject(projectSettings: any): any { + createSettingsObject(projectSettings: RawProjectSettings): ProjectSettings { return { services: { account: projectSettings.serviceStatusForAccount, @@ -658,17 +673,17 @@ class Local extends Config { class Global extends Config { static CONFIG_FILE_PATH = '.appwrite/prefs.json'; - static PREFERENCE_CURRENT = 'current'; - static PREFERENCE_ENDPOINT = 'endpoint'; - static PREFERENCE_EMAIL = 'email'; - static PREFERENCE_SELF_SIGNED = 'selfSigned'; - static PREFERENCE_COOKIE = 'cookie'; - static PREFERENCE_PROJECT = 'project'; - static PREFERENCE_KEY = 'key'; - static PREFERENCE_LOCALE = 'locale'; - static PREFERENCE_MODE = 'mode'; - - static IGNORE_ATTRIBUTES = [ + static PREFERENCE_CURRENT = 'current' as const; + static PREFERENCE_ENDPOINT = 'endpoint' as const; + static PREFERENCE_EMAIL = 'email' as const; + static PREFERENCE_SELF_SIGNED = 'selfSigned' as const; + static PREFERENCE_COOKIE = 'cookie' as const; + static PREFERENCE_PROJECT = 'project' as const; + static PREFERENCE_KEY = 'key' as const; + static PREFERENCE_LOCALE = 'locale' as const; + static PREFERENCE_MODE = 'mode' as const; + + static IGNORE_ATTRIBUTES: readonly string[] = [ Global.PREFERENCE_CURRENT, Global.PREFERENCE_SELF_SIGNED, Global.PREFERENCE_ENDPOINT, @@ -693,12 +708,12 @@ class Global extends Config { if (!this.has(Global.PREFERENCE_CURRENT)) { return ''; } - return this.get(Global.PREFERENCE_CURRENT as any); + return this.get(Global.PREFERENCE_CURRENT); } setCurrentSession(session: string): void { if (session !== undefined) { - this.set(Global.PREFERENCE_CURRENT as any, session); + this.set(Global.PREFERENCE_CURRENT, session); } } diff --git a/lib/emulation/docker.ts b/lib/emulation/docker.ts index 8acd672..6eb07da 100644 --- a/lib/emulation/docker.ts +++ b/lib/emulation/docker.ts @@ -1,4 +1,4 @@ -import ignore = require('ignore'); +import ignore from 'ignore'; import net = require('net'); import chalk from 'chalk'; import childProcess = require('child_process'); @@ -8,15 +8,7 @@ import fs = require('fs'); import { log, error, success } from '../parser'; import { openRuntimesVersion, systemTools, Queue } from './utils'; import { getAllFiles } from '../utils'; - -interface FunctionConfig { - $id: string; - runtime: string; - path: string; - entrypoint: string; - commands: string; - ignore?: string; -} +import type { FunctionConfig } from '../types'; export async function dockerStop(id: string): Promise { const stopProcess = childProcess.spawn('docker', ['rm', '--force', id], { @@ -59,7 +51,7 @@ export async function dockerBuild(func: FunctionConfig, variables: Record { - [key: string]: T; - total: number; -} +// Overload for when wrapper is empty string - returns array +export function paginate( + action: (args: PaginateArgs) => Promise, + args: PaginateArgs, + limit: number, + wrapper: '', + queries?: string[] +): Promise; -export const paginate = async ( +// Overload for when wrapper is specified - returns object with that key +export function paginate( + action: (args: PaginateArgs) => Promise, + args: PaginateArgs, + limit: number, + wrapper: K, + queries?: string[] +): Promise & { total: number }>; + +// Implementation +export async function paginate( action: (args: PaginateArgs) => Promise, args: PaginateArgs = {}, limit: number = 100, wrapper: string = '', queries: string[] = [] -): Promise> => { +): Promise & { total: number })> { let pageNumber = 0; let results: T[] = []; let total = 0; @@ -59,5 +73,5 @@ export const paginate = async ( return { [wrapper]: results, total, - } as PaginateResponse; -}; + } as Record & { total: number }; +} diff --git a/lib/parser.ts b/lib/parser.ts index f9fecb7..df121bf 100644 --- a/lib/parser.ts +++ b/lib/parser.ts @@ -124,7 +124,7 @@ export const parseError = (err: Error): void => { // Silently fail } - const version = '13.0.0-rc.1'; + const version = '13.0.0-rc.2'; const stepsToReproduce = `Running \`appwrite ${(cliConfig.reportData as any).data.args.join(' ')}\``; const yourEnvironment = `CLI version: ${version}\nOperation System: ${os.type()}\nAppwrite version: ${appwriteVersion}\nIs Cloud: ${isCloud()}`; diff --git a/lib/questions.ts b/lib/questions.ts index f314ba4..306fc23 100644 --- a/lib/questions.ts +++ b/lib/questions.ts @@ -37,7 +37,7 @@ interface Question { message: string; default?: any; when?: ((answers: Answers) => boolean | Promise) | boolean; - choices?: (() => Promise | Choice[]) | Choice[]; + choices?: ((answers: Answers) => Promise | Choice[]) | (() => Promise | Choice[]) | Choice[] | string[]; validate?: (value: any) => boolean | string | Promise; mask?: string; } @@ -250,7 +250,7 @@ export const questionsInitProject: Question[] = [ message: "Select your Appwrite Cloud region", choices: async () => { let client = await sdkForConsole(true); - let response = await client.call("GET", "/console/regions"); + let response = await client.call<{ regions: any[] }>("GET", "/console/regions"); let regions = response.regions || []; if (!regions.length) { throw new Error("No regions found. Please check your network or Appwrite Cloud availability."); @@ -711,7 +711,7 @@ export const questionGetEndpoint: Question[] = [ } let client = new Client().setEndpoint(value); try { - let response = await client.call('get', '/health/version'); + let response = await client.call<{ version?: string }>('get', '/health/version'); if (response.version) { return true; } else { diff --git a/lib/types.ts b/lib/types.ts index dee317a..6a2e6ff 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -1,12 +1,7 @@ -export interface CliConfig { - verbose: boolean; - json: boolean; - force: boolean; - all: boolean; - ids: string[]; - report: boolean; - reportData: Record; -} +import type { File } from 'undici'; +import type { ReadableStream } from 'node:stream/web'; + +export type ResponseType = 'json' | 'arraybuffer'; export interface Headers { [key: string]: string; @@ -18,16 +13,52 @@ export interface RequestParams { export interface FileUpload { type: 'file'; - file: Buffer | ReadableStream; + file: File; filename: string; } -export type ResponseType = 'json' | 'arraybuffer'; +export interface FileInput { + type: 'file'; + stream: ReadableStream; + filename: string; + size: number; +} + +export interface UploadProgress { + $id: string; + progress: number; + sizeUploaded: number; + chunksTotal: number; + chunksUploaded: number; +} export interface ConfigData { [key: string]: unknown; } +export interface Entity { + $id: string; + [key: string]: unknown; +} + +export interface ParsedData { + [key: string]: unknown; +} + +export interface CommandDescription { + [key: string]: string; +} + +export interface CliConfig { + verbose: boolean; + json: boolean; + force: boolean; + all: boolean; + ids: string[]; + report: boolean; + reportData: Record; +} + export interface SessionData { endpoint: string; email?: string; @@ -35,7 +66,7 @@ export interface SessionData { cookie?: string; } -export interface GlobalConfigData { +export interface GlobalConfigData extends ConfigData { sessions: { [key: string]: SessionData; }; @@ -43,33 +74,106 @@ export interface GlobalConfigData { cookie?: string; } -export interface ProjectConfigData { - projectId?: string; - projectName?: string; - functions?: FunctionConfig[]; - collections?: CollectionConfig[]; - databases?: DatabaseConfig[]; - buckets?: BucketConfig[]; - teams?: TeamConfig[]; - topics?: TopicConfig[]; +export interface ProjectSettings { + services?: { + account?: boolean; + avatars?: boolean; + databases?: boolean; + locale?: boolean; + health?: boolean; + storage?: boolean; + teams?: boolean; + users?: boolean; + sites?: boolean; + functions?: boolean; + graphql?: boolean; + messaging?: boolean; + }; + auth?: { + methods?: { + jwt?: boolean; + phone?: boolean; + invites?: boolean; + anonymous?: boolean; + 'email-otp'?: boolean; + 'magic-url'?: boolean; + 'email-password'?: boolean; + }; + security?: { + duration?: number; + limit?: number; + sessionsLimit?: number; + passwordHistory?: number; + passwordDictionary?: boolean; + personalDataCheck?: boolean; + sessionAlerts?: boolean; + mockNumbers?: string[]; + }; + }; } -export interface FunctionConfig { +export interface RawProjectSettings { + serviceStatusForAccount?: boolean; + serviceStatusForAvatars?: boolean; + serviceStatusForDatabases?: boolean; + serviceStatusForLocale?: boolean; + serviceStatusForHealth?: boolean; + serviceStatusForStorage?: boolean; + serviceStatusForTeams?: boolean; + serviceStatusForUsers?: boolean; + serviceStatusForSites?: boolean; + serviceStatusForFunctions?: boolean; + serviceStatusForGraphql?: boolean; + serviceStatusForMessaging?: boolean; + authJWT?: boolean; + authPhone?: boolean; + authInvites?: boolean; + authAnonymous?: boolean; + authEmailOtp?: boolean; + authUsersAuthMagicURL?: boolean; + authEmailPassword?: boolean; + authDuration?: number; + authLimit?: number; + authSessionsLimit?: number; + authPasswordHistory?: number; + authPasswordDictionary?: boolean; + authPersonalDataCheck?: boolean; + authSessionAlerts?: boolean; + authMockNumbers?: string[]; +} + +export interface DatabaseConfig { $id: string; name: string; - runtime: string; - path: string; - entrypoint: string; - execute?: string[]; enabled?: boolean; - logging?: boolean; - events?: string[]; - schedule?: string; - timeout?: number; - vars?: Record; - commands?: string; - scopes?: string[]; - specification?: string; +} + +export interface AttributeConfig { + key: string; + type: string; + required?: boolean; + array?: boolean; + size?: number; + default?: unknown; + min?: number; + max?: number; + format?: string; + elements?: string[]; + relatedCollection?: string; + relationType?: string; + twoWay?: boolean; + twoWayKey?: string; + onDelete?: string; + side?: string; + encrypt?: boolean; +} + +export interface IndexConfig { + key: string; + type: string; + status?: string; + attributes?: string[]; + orders?: string[]; } export interface CollectionConfig { @@ -83,7 +187,7 @@ export interface CollectionConfig { indexes?: IndexConfig[]; } -export interface AttributeConfig { +export interface ColumnConfig { key: string; type: string; required?: boolean; @@ -94,7 +198,7 @@ export interface AttributeConfig { max?: number; format?: string; elements?: string[]; - relatedCollection?: string; + relatedTable?: string; relationType?: string; twoWay?: boolean; twoWayKey?: string; @@ -103,18 +207,23 @@ export interface AttributeConfig { encrypt?: boolean; } -export interface IndexConfig { +export interface TableIndexConfig { key: string; type: string; status?: string; - attributes?: string[]; + columns?: string[]; orders?: string[]; } -export interface DatabaseConfig { +export interface TableConfig { $id: string; + $permissions?: string[]; + databaseId: string; name: string; enabled?: boolean; + rowSecurity?: boolean; + columns?: ColumnConfig[]; + indexes?: TableIndexConfig[]; } export interface BucketConfig { @@ -130,6 +239,44 @@ export interface BucketConfig { antivirus?: boolean; } +export interface FunctionConfig { + $id: string; + name: string; + runtime: string; + path: string; + entrypoint: string; + execute?: string[]; + enabled?: boolean; + logging?: boolean; + events?: string[]; + schedule?: string; + timeout?: number; + vars?: Record; + commands?: string; + scopes?: string[]; + specification?: string; + ignore?: string; +} + +export interface SiteConfig { + $id: string; + name: string; + path: string; + enabled?: boolean; + logging?: boolean; + timeout?: number; + framework: string; + buildRuntime?: string; + adapter?: string; + installCommand?: string; + buildCommand?: string; + outputDirectory?: string; + fallbackFile?: string; + specification?: string; + vars?: Record; + ignore?: string; +} + export interface TeamConfig { $id: string; name: string; @@ -141,10 +288,16 @@ export interface TopicConfig { subscribe?: string[]; } -export interface CommandDescription { - [key: string]: string; -} - -export interface ParsedData { - [key: string]: unknown; +export interface ProjectConfigData extends ConfigData { + projectId?: string; + projectName?: string; + settings?: ProjectSettings; + functions?: FunctionConfig[]; + collections?: CollectionConfig[]; + databases?: DatabaseConfig[]; + buckets?: BucketConfig[]; + teams?: TeamConfig[]; + topics?: TopicConfig[]; + sites?: SiteConfig[]; + tables?: TableConfig[]; } diff --git a/package.json b/package.json index e790f27..40dac43 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "appwrite-cli", "homepage": "https://appwrite.io/support", "description": "Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API", - "version": "13.0.0-rc.1", + "version": "13.0.0-rc.2", "license": "BSD-3-Clause", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -14,7 +14,7 @@ "url": "https://github.com/appwrite/sdk-for-cli" }, "scripts": { - "build": "tsc || true", + "build": "tsc", "prepublishOnly": "npm run build", "test": "echo \"Error: no test specified\" && exit 1", "linux-x64": "npm run build && pkg -t node18-linux-x64 -o build/appwrite-cli-linux-x64 package.json", diff --git a/scoop/appwrite.config.json b/scoop/appwrite.config.json index 257a560..4a84a7e 100644 --- a/scoop/appwrite.config.json +++ b/scoop/appwrite.config.json @@ -1,12 +1,12 @@ { "$schema": "https://raw.githubusercontent.com/ScoopInstaller/Scoop/master/schema.json", - "version": "13.0.0-rc.1", + "version": "13.0.0-rc.2", "description": "The Appwrite CLI is a command-line application that allows you to interact with Appwrite and perform server-side tasks using your terminal.", "homepage": "https://github.com/appwrite/sdk-for-cli", "license": "BSD-3-Clause", "architecture": { "64bit": { - "url": "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.1/appwrite-cli-win-x64.exe", + "url": "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.2/appwrite-cli-win-x64.exe", "bin": [ [ "appwrite-cli-win-x64.exe", @@ -15,7 +15,7 @@ ] }, "arm64": { - "url": "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.1/appwrite-cli-win-arm64.exe", + "url": "https://github.com/appwrite/sdk-for-cli/releases/download/13.0.0-rc.2/appwrite-cli-win-arm64.exe", "bin": [ [ "appwrite-cli-win-arm64.exe",