From 9510ed6a7d64c1ce35f34f89f333025abbfc3e16 Mon Sep 17 00:00:00 2001 From: gagik Date: Tue, 4 Nov 2025 11:24:21 +0100 Subject: [PATCH 1/5] chore: disable experimental strip types to fix tests Now, we should definetely adopt erasable syntax but this is a bit too much refactoring right now so this quick fix will do. --- package.json | 2 +- syntaxes/mongodbInjection.tmLanguage.json | 36 +++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 15e63ded6..3230ddcbb 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,7 @@ "pretest": "npm run compile", "test": "npm run test-webview && npm run test-extension", "test-extension": "cross-env NODE_OPTIONS=--no-force-async-hooks-checks xvfb-maybe node ./out/test/runTest.js", - "test-webview": "mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/setup-webview.ts src/test/suite/views/webview-app/**/*.test.tsx", + "test-webview": "cross-env NODE_OPTIONS='--no-experimental-strip-types' mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/setup-webview.ts src/test/suite/views/webview-app/**/*.test.tsx", "ai-accuracy-tests": "env TS_NODE_FILES=true mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/ai-accuracy-tests/test-setup.ts ./src/test/ai-accuracy-tests/ai-accuracy-tests.ts", "analyze-bundle": "webpack --mode production --analyze", "vscode:prepublish": "npm run clean && npm run compile:constants && npm run compile:resources && webpack --mode production", diff --git a/syntaxes/mongodbInjection.tmLanguage.json b/syntaxes/mongodbInjection.tmLanguage.json index 0921df896..484dc15de 100644 --- a/syntaxes/mongodbInjection.tmLanguage.json +++ b/syntaxes/mongodbInjection.tmLanguage.json @@ -1161,6 +1161,33 @@ } } }, + { + "name": "meta.object.member.mongodb", + "match": "\\$similarityCosine\\b", + "captures": { + "0": { + "name": "keyword.other.$similarityCosine.mongodb" + } + } + }, + { + "name": "meta.object.member.mongodb", + "match": "\\$similarityDotProduct\\b", + "captures": { + "0": { + "name": "keyword.other.$similarityDotProduct.mongodb" + } + } + }, + { + "name": "meta.object.member.mongodb", + "match": "\\$similarityEuclidean\\b", + "captures": { + "0": { + "name": "keyword.other.$similarityEuclidean.mongodb" + } + } + }, { "name": "meta.object.member.mongodb", "match": "\\$size\\b", @@ -1962,6 +1989,15 @@ } } }, + { + "name": "meta.object.member.mongodb", + "match": "\\$scoreFusion\\b", + "captures": { + "0": { + "name": "keyword.other.$scoreFusion.mongodb" + } + } + }, { "name": "meta.object.member.mongodb", "match": "\\$search\\b", From 18f82a59949de0b2d7e91d8c95e3ad1823d73a5b Mon Sep 17 00:00:00 2001 From: gagik Date: Wed, 12 Nov 2025 14:57:03 +0100 Subject: [PATCH 2/5] chore: remove all erasable syntax --- .github/workflows/test-and-build.yaml | 10 +- package-lock.json | 66 ++++--- package.json | 10 +- src/commands/index.ts | 167 +++++++++--------- src/connectionController.ts | 45 +++-- src/documentSource.ts | 15 +- src/editors/editDocumentCodeLensProvider.ts | 10 +- src/editors/mongoDBDocumentService.ts | 4 +- .../queryWithCopilotCodeLensProvider.ts | 4 +- src/explorer/collectionTreeItem.ts | 12 +- src/explorer/documentListTreeItem.ts | 19 +- src/explorer/explorerController.ts | 8 +- src/explorer/explorerTreeController.ts | 13 +- src/explorer/fieldTreeItem.ts | 88 ++++----- src/explorer/helpExplorer.ts | 5 +- src/explorer/indexTreeItem.ts | 35 ++-- src/explorer/playgroundsExplorer.ts | 4 +- src/extensionConstants.ts | 7 +- src/language/diagnosticCodes.ts | 9 +- src/language/languageServerController.ts | 42 +++-- src/language/mongoDBService.ts | 12 +- src/language/server.ts | 14 +- src/language/serverCommands.ts | 31 ++-- src/language/worker.ts | 8 +- src/mdbExtensionController.ts | 14 +- src/participant/participant.ts | 16 +- src/participant/participantErrorTypes.ts | 17 +- src/participant/prompts/promptHistory.ts | 6 +- src/storage/connectionStorage.ts | 80 +++++---- src/storage/index.ts | 7 +- src/storage/storageController.ts | 80 +++++---- src/telemetry/connectionTelemetry.ts | 11 +- src/telemetry/telemetryEvents.ts | 10 +- src/telemetry/telemetryService.ts | 15 +- src/test/suite/connectionController.test.ts | 152 ++++++++-------- .../collectionDocumentsProvider.test.ts | 23 ++- .../editDocumentCodeLensProvider.test.ts | 11 +- .../editors/mongoDBDocumentService.test.ts | 16 +- .../suite/explorer/collectionTreeItem.test.ts | 12 +- .../explorer/documentListTreeItem.test.ts | 10 +- .../suite/explorer/explorerController.test.ts | 22 +-- src/test/suite/explorer/indexTreeItem.test.ts | 4 +- .../suite/explorer/schemaTreeItem.test.ts | 4 +- .../suite/language/mongoDBService.test.ts | 4 +- .../mcp/mcpConnectionErrorHandler.test.ts | 13 +- src/test/suite/mdbExtensionController.test.ts | 28 +-- .../suite/participant/participant.test.ts | 18 +- .../suite/storage/connectionStorage.test.ts | 92 +++++----- .../suite/storage/storageController.test.ts | 18 +- src/test/suite/stubbableMdbExtension.ts | 13 +- .../telemetry/connectionTelemetry.test.ts | 38 ++-- .../suite/telemetry/telemetryService.test.ts | 14 +- src/utils/playground.ts | 6 +- .../extension-app-message-constants.ts | 87 ++++----- src/views/webview-app/use-connection-form.ts | 13 +- .../webview-app/use-connection-status.ts | 5 +- src/views/webviewController.ts | 4 +- tsconfig.json | 3 +- 58 files changed, 816 insertions(+), 688 deletions(-) diff --git a/.github/workflows/test-and-build.yaml b/.github/workflows/test-and-build.yaml index 5399eef5f..479e1289f 100644 --- a/.github/workflows/test-and-build.yaml +++ b/.github/workflows/test-and-build.yaml @@ -31,10 +31,18 @@ jobs: with: fetch-depth: 0 + - name: Get Node.js version from VS Code + id: get-node-version + shell: bash + run: | + NODE_VERSION=$(curl -fsSL https://raw.githubusercontent.com/microsoft/vscode/refs/heads/main/.nvmrc | tr -d '[:space:]') + echo "node-version=$NODE_VERSION" >> $GITHUB_OUTPUT + echo "Using Node.js version: $NODE_VERSION" + - name: Setup Node.js Environment uses: actions/setup-node@v4 with: - node-version: 22.15.1 + node-version: ${{ steps.get-node-version.outputs.node-version }} cache: npm - name: Run tests and build diff --git a/package-lock.json b/package-lock.json index c48ecc8cc..da155d029 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5230,6 +5230,7 @@ "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", "dev": true, + "license": "MIT", "dependencies": { "@jridgewell/trace-mapping": "0.3.9" }, @@ -5242,6 +5243,7 @@ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", "dev": true, + "license": "MIT", "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" @@ -9989,28 +9991,32 @@ "license": "MIT" }, "node_modules/@tsconfig/node10": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz", - "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==", - "dev": true + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz", + "integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==", + "dev": true, + "license": "MIT" }, "node_modules/@tsconfig/node12": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/@tsconfig/node14": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/@tsconfig/node16": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/@types/aria-query": { "version": "5.0.4", @@ -11351,6 +11357,19 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/acorn-walk": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", + "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/acquit": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/acquit/-/acquit-1.3.0.tgz", @@ -11569,7 +11588,8 @@ "version": "4.1.3", "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/argparse": { "version": "1.0.10", @@ -13737,7 +13757,8 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/crelt": { "version": "1.0.6", @@ -20114,7 +20135,8 @@ "version": "1.3.6", "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/map-obj": { "version": "4.3.0", @@ -27076,6 +27098,7 @@ "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", "dev": true, + "license": "MIT", "dependencies": { "@cspotcode/source-map-support": "^0.8.0", "@tsconfig/node10": "^1.0.7", @@ -27114,20 +27137,12 @@ } } }, - "node_modules/ts-node/node_modules/acorn-walk": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", - "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", - "dev": true, - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/ts-node/node_modules/diff": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", "dev": true, + "license": "BSD-3-Clause", "engines": { "node": ">=0.3.1" } @@ -27633,7 +27648,8 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/validate-npm-package-license": { "version": "3.0.4", @@ -28020,15 +28036,6 @@ "node": ">= 10.13.0" } }, - "node_modules/webpack-bundle-analyzer/node_modules/acorn-walk": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", - "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", - "dev": true, - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/webpack-bundle-analyzer/node_modules/commander": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", @@ -28740,6 +28747,7 @@ "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } diff --git a/package.json b/package.json index 3230ddcbb..e53797b58 100644 --- a/package.json +++ b/package.json @@ -40,10 +40,10 @@ "scripts": { "clean": "rimraf ./out/* ./dist/* ", "lint": "eslint . && prettier --check .", - "update-grammar": "ts-node ./scripts/update-grammar.ts", + "update-grammar": "node ./scripts/update-grammar.ts", "precompile": "npm run clean", "compile": "npm-run-all compile:*", - "compile:constants": "ts-node ./scripts/generate-constants.ts", + "compile:constants": "node ./scripts/generate-constants.ts", "compile:resources": "npm run update-grammar", "compile:extension": "tsc -p ./", "compile:extension-bundles": "webpack --mode development", @@ -53,15 +53,15 @@ "pretest": "npm run compile", "test": "npm run test-webview && npm run test-extension", "test-extension": "cross-env NODE_OPTIONS=--no-force-async-hooks-checks xvfb-maybe node ./out/test/runTest.js", - "test-webview": "cross-env NODE_OPTIONS='--no-experimental-strip-types' mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/setup-webview.ts src/test/suite/views/webview-app/**/*.test.tsx", - "ai-accuracy-tests": "env TS_NODE_FILES=true mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/ai-accuracy-tests/test-setup.ts ./src/test/ai-accuracy-tests/ai-accuracy-tests.ts", + "test-webview": "mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/setup-webview.ts src/test/suite/views/webview-app/**/*.test.tsx", + "ai-accuracy-tests": "mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/ai-accuracy-tests/test-setup.ts ./src/test/ai-accuracy-tests/ai-accuracy-tests.ts", "analyze-bundle": "webpack --mode production --analyze", "vscode:prepublish": "npm run clean && npm run compile:constants && npm run compile:resources && webpack --mode production", "check": "npm run lint && npm run depcheck", "depcheck": "depcheck", "package": "cross-env NODE_OPTIONS='--require ./scripts/no-npm-list-fail.js' vsce package --githubBranch main", "local-install": "npm run package && code --install-extension ./mongodb-vscode-*.vsix", - "check-vsix-size": "ts-node ./scripts/check-vsix-size.ts", + "check-vsix-size": "node ./scripts/check-vsix-size.ts", "release-draft": "node ./scripts/release-draft.js", "reformat": "prettier --write .", "presnyk-test": "echo \"Creating backup for package-lock.json.\"; cp package-lock.json original-package-lock.json", diff --git a/src/commands/index.ts b/src/commands/index.ts index 6d0439853..ac020be2f 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,96 +1,105 @@ -enum EXTENSION_COMMANDS { - MDB_CONNECT = 'mdb.connect', - MDB_CONNECT_WITH_URI = 'mdb.connectWithURI', - MDB_OPEN_OVERVIEW_PAGE = 'mdb.openOverviewPage', - MDB_DISCONNECT = 'mdb.disconnect', - MDB_REMOVE_CONNECTION = 'mdb.removeConnection', +const EXTENSION_COMMANDS = { + MDB_CONNECT: 'mdb.connect', + MDB_CONNECT_WITH_URI: 'mdb.connectWithURI', + MDB_OPEN_OVERVIEW_PAGE: 'mdb.openOverviewPage', + MDB_DISCONNECT: 'mdb.disconnect', + MDB_REMOVE_CONNECTION: 'mdb.removeConnection', - OPEN_MONGODB_ISSUE_REPORTER = 'mdb.openMongoDBIssueReporter', + OPEN_MONGODB_ISSUE_REPORTER: 'mdb.openMongoDBIssueReporter', - MDB_OPEN_MDB_SHELL = 'mdb.openMongoDBShell', - MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW = 'mdb.treeViewOpenMongoDBShell', + MDB_OPEN_MDB_SHELL: 'mdb.openMongoDBShell', + MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW: 'mdb.treeViewOpenMongoDBShell', - MDB_CREATE_PLAYGROUND = 'mdb.createPlayground', - MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE = 'mdb.createNewPlaygroundFromOverviewPage', - MDB_RUN_SELECTED_PLAYGROUND_BLOCKS = 'mdb.runSelectedPlaygroundBlocks', - MDB_RUN_ALL_PLAYGROUND_BLOCKS = 'mdb.runAllPlaygroundBlocks', - MDB_RUN_ALL_OR_SELECTED_PLAYGROUND_BLOCKS = 'mdb.runPlayground', - MDB_EXPORT_CODE_TO_PLAYGROUND = 'mdb.exportCodeToPlayground', + MDB_CREATE_PLAYGROUND: 'mdb.createPlayground', + MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE: + 'mdb.createNewPlaygroundFromOverviewPage', + MDB_RUN_SELECTED_PLAYGROUND_BLOCKS: 'mdb.runSelectedPlaygroundBlocks', + MDB_RUN_ALL_PLAYGROUND_BLOCKS: 'mdb.runAllPlaygroundBlocks', + MDB_RUN_ALL_OR_SELECTED_PLAYGROUND_BLOCKS: 'mdb.runPlayground', + MDB_EXPORT_CODE_TO_PLAYGROUND: 'mdb.exportCodeToPlayground', - MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX = 'mdb.fixThisInvalidInteractiveSyntax', - MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX = 'mdb.fixAllInvalidInteractiveSyntax', + MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX: + 'mdb.fixThisInvalidInteractiveSyntax', + MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX: 'mdb.fixAllInvalidInteractiveSyntax', - MDB_SELECT_TARGET_FOR_EXPORT_TO_LANGUAGE = 'mdb.selectTargetForExportToLanguage', - MDB_EXPORT_TO_LANGUAGE = 'mdb.exportToLanguage', - MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE = 'mdb.changeDriverSyntaxForExportToLanguage', + MDB_SELECT_TARGET_FOR_EXPORT_TO_LANGUAGE: + 'mdb.selectTargetForExportToLanguage', + MDB_EXPORT_TO_LANGUAGE: 'mdb.exportToLanguage', + MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE: + 'mdb.changeDriverSyntaxForExportToLanguage', - MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS = 'mdb.openMongoDBDocumentFromCodeLens', - MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE = 'mdb.openMongoDBDocumentFromTree', - MDB_SAVE_MONGODB_DOCUMENT = 'mdb.saveMongoDBDocument', + MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS: + 'mdb.openMongoDBDocumentFromCodeLens', + MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE: 'mdb.openMongoDBDocumentFromTree', + MDB_SAVE_MONGODB_DOCUMENT: 'mdb.saveMongoDBDocument', - MDB_CHANGE_ACTIVE_CONNECTION = 'mdb.changeActiveConnection', + MDB_CHANGE_ACTIVE_CONNECTION: 'mdb.changeActiveConnection', - MDB_CODELENS_SHOW_MORE_DOCUMENTS = 'mdb.codeLens.showMoreDocumentsClicked', + MDB_CODELENS_SHOW_MORE_DOCUMENTS: 'mdb.codeLens.showMoreDocumentsClicked', // Commands from the tree view. - MDB_ADD_CONNECTION = 'mdb.addConnection', - MDB_ADD_CONNECTION_WITH_URI = 'mdb.addConnectionWithURI', - MDB_REFRESH_PLAYGROUNDS_FROM_TREE_VIEW = 'mdb.refreshPlaygroundsFromTreeView', - MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW = 'mdb.openPlaygroundFromTreeView', - MDB_CONNECT_TO_CONNECTION_TREE_VIEW = 'mdb.connectToConnectionTreeItem', - MDB_CREATE_PLAYGROUND_FROM_TREE_VIEW = 'mdb.createNewPlaygroundFromTreeView', - MDB_CREATE_PLAYGROUND_FROM_TREE_ITEM = 'mdb.createNewPlaygroundFromTreeItem', - MDB_DISCONNECT_FROM_CONNECTION_TREE_VIEW = 'mdb.disconnectFromConnectionTreeItem', - MDB_EDIT_CONNECTION = 'mdb.editConnection', - MDB_REFRESH_CONNECTION = 'mdb.refreshConnection', - MDB_COPY_CONNECTION_STRING = 'mdb.copyConnectionString', - MDB_EDIT_PRESET_CONNECTIONS = 'mdb.editPresetConnections', - MDB_REMOVE_CONNECTION_TREE_VIEW = 'mdb.treeItemRemoveConnection', - MDB_RENAME_CONNECTION = 'mdb.renameConnection', - MDB_ADD_DATABASE = 'mdb.addDatabase', - MDB_SEARCH_FOR_DOCUMENTS = 'mdb.searchForDocuments', - MDB_COPY_DATABASE_NAME = 'mdb.copyDatabaseName', - MDB_DROP_DATABASE = 'mdb.dropDatabase', - MDB_REFRESH_DATABASE = 'mdb.refreshDatabase', - MDB_ADD_COLLECTION = 'mdb.addCollection', - MDB_COPY_COLLECTION_NAME = 'mdb.copyCollectionName', - MDB_DROP_COLLECTION = 'mdb.dropCollection', - MDB_VIEW_COLLECTION_DOCUMENTS = 'mdb.viewCollectionDocuments', - MDB_REFRESH_COLLECTION = 'mdb.refreshCollection', - MDB_REFRESH_DOCUMENT_LIST = 'mdb.refreshDocumentList', - MDB_INSERT_DOCUMENT_FROM_TREE_VIEW = 'mdb.insertDocumentFromTreeView', - MDB_REFRESH_SCHEMA = 'mdb.refreshSchema', - MDB_COPY_SCHEMA_FIELD_NAME = 'mdb.copySchemaFieldName', - MDB_REFRESH_INDEXES = 'mdb.refreshIndexes', - MDB_CREATE_INDEX_TREE_VIEW = 'mdb.createIndexFromTreeView', - MDB_INSERT_OBJECTID_TO_EDITOR = 'mdb.insertObjectIdToEditor', - MDB_GENERATE_OBJECTID_TO_CLIPBOARD = 'mdb.generateObjectIdToClipboard', - MDB_COPY_DOCUMENT_CONTENTS_FROM_TREE_VIEW = 'mdb.copyDocumentContentsFromTreeView', - MDB_CLONE_DOCUMENT_FROM_TREE_VIEW = 'mdb.cloneDocumentFromTreeView', - MDB_DELETE_DOCUMENT_FROM_TREE_VIEW = 'mdb.deleteDocumentFromTreeView', - MDB_ADD_STREAM_PROCESSOR = 'mdb.addStreamProcessor', - MDB_START_STREAM_PROCESSOR = 'mdb.startStreamProcessor', - MDB_STOP_STREAM_PROCESSOR = 'mdb.stopStreamProcessor', - MDB_DROP_STREAM_PROCESSOR = 'mdb.dropStreamProcessor', + MDB_ADD_CONNECTION: 'mdb.addConnection', + MDB_ADD_CONNECTION_WITH_URI: 'mdb.addConnectionWithURI', + MDB_REFRESH_PLAYGROUNDS_FROM_TREE_VIEW: 'mdb.refreshPlaygroundsFromTreeView', + MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW: 'mdb.openPlaygroundFromTreeView', + MDB_CONNECT_TO_CONNECTION_TREE_VIEW: 'mdb.connectToConnectionTreeItem', + MDB_CREATE_PLAYGROUND_FROM_TREE_VIEW: 'mdb.createNewPlaygroundFromTreeView', + MDB_CREATE_PLAYGROUND_FROM_TREE_ITEM: 'mdb.createNewPlaygroundFromTreeItem', + MDB_DISCONNECT_FROM_CONNECTION_TREE_VIEW: + 'mdb.disconnectFromConnectionTreeItem', + MDB_EDIT_CONNECTION: 'mdb.editConnection', + MDB_REFRESH_CONNECTION: 'mdb.refreshConnection', + MDB_COPY_CONNECTION_STRING: 'mdb.copyConnectionString', + MDB_EDIT_PRESET_CONNECTIONS: 'mdb.editPresetConnections', + MDB_REMOVE_CONNECTION_TREE_VIEW: 'mdb.treeItemRemoveConnection', + MDB_RENAME_CONNECTION: 'mdb.renameConnection', + MDB_ADD_DATABASE: 'mdb.addDatabase', + MDB_SEARCH_FOR_DOCUMENTS: 'mdb.searchForDocuments', + MDB_COPY_DATABASE_NAME: 'mdb.copyDatabaseName', + MDB_DROP_DATABASE: 'mdb.dropDatabase', + MDB_REFRESH_DATABASE: 'mdb.refreshDatabase', + MDB_ADD_COLLECTION: 'mdb.addCollection', + MDB_COPY_COLLECTION_NAME: 'mdb.copyCollectionName', + MDB_DROP_COLLECTION: 'mdb.dropCollection', + MDB_VIEW_COLLECTION_DOCUMENTS: 'mdb.viewCollectionDocuments', + MDB_REFRESH_COLLECTION: 'mdb.refreshCollection', + MDB_REFRESH_DOCUMENT_LIST: 'mdb.refreshDocumentList', + MDB_INSERT_DOCUMENT_FROM_TREE_VIEW: 'mdb.insertDocumentFromTreeView', + MDB_REFRESH_SCHEMA: 'mdb.refreshSchema', + MDB_COPY_SCHEMA_FIELD_NAME: 'mdb.copySchemaFieldName', + MDB_REFRESH_INDEXES: 'mdb.refreshIndexes', + MDB_CREATE_INDEX_TREE_VIEW: 'mdb.createIndexFromTreeView', + MDB_INSERT_OBJECTID_TO_EDITOR: 'mdb.insertObjectIdToEditor', + MDB_GENERATE_OBJECTID_TO_CLIPBOARD: 'mdb.generateObjectIdToClipboard', + MDB_COPY_DOCUMENT_CONTENTS_FROM_TREE_VIEW: + 'mdb.copyDocumentContentsFromTreeView', + MDB_CLONE_DOCUMENT_FROM_TREE_VIEW: 'mdb.cloneDocumentFromTreeView', + MDB_DELETE_DOCUMENT_FROM_TREE_VIEW: 'mdb.deleteDocumentFromTreeView', + MDB_ADD_STREAM_PROCESSOR: 'mdb.addStreamProcessor', + MDB_START_STREAM_PROCESSOR: 'mdb.startStreamProcessor', + MDB_STOP_STREAM_PROCESSOR: 'mdb.stopStreamProcessor', + MDB_DROP_STREAM_PROCESSOR: 'mdb.dropStreamProcessor', // Chat participant. - OPEN_PARTICIPANT_CODE_IN_PLAYGROUND = 'mdb.openParticipantCodeInPlayground', - SEND_MESSAGE_TO_PARTICIPANT = 'mdb.sendMessageToParticipant', - SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT = 'mdb.sendMessageToParticipantFromInput', - ASK_COPILOT_FROM_TREE_ITEM = 'mdb.askCopilotFromTreeItem', - RUN_PARTICIPANT_CODE = 'mdb.runParticipantCode', - CONNECT_WITH_PARTICIPANT = 'mdb.connectWithParticipant', - SELECT_DATABASE_WITH_PARTICIPANT = 'mdb.selectDatabaseWithParticipant', - SELECT_COLLECTION_WITH_PARTICIPANT = 'mdb.selectCollectionWithParticipant', - PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT = 'mdb.participantViewRawSchemaOutput', - SHOW_EXPORT_TO_LANGUAGE_RESULT = 'mdb.showExportToLanguageResult', + OPEN_PARTICIPANT_CODE_IN_PLAYGROUND: 'mdb.openParticipantCodeInPlayground', + SEND_MESSAGE_TO_PARTICIPANT: 'mdb.sendMessageToParticipant', + SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT: + 'mdb.sendMessageToParticipantFromInput', + ASK_COPILOT_FROM_TREE_ITEM: 'mdb.askCopilotFromTreeItem', + RUN_PARTICIPANT_CODE: 'mdb.runParticipantCode', + CONNECT_WITH_PARTICIPANT: 'mdb.connectWithParticipant', + SELECT_DATABASE_WITH_PARTICIPANT: 'mdb.selectDatabaseWithParticipant', + SELECT_COLLECTION_WITH_PARTICIPANT: 'mdb.selectCollectionWithParticipant', + PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT: 'mdb.participantViewRawSchemaOutput', + SHOW_EXPORT_TO_LANGUAGE_RESULT: 'mdb.showExportToLanguageResult', // MCP Server commands. - START_MCP_SERVER = 'mdb.startMCPServer', - STOP_MCP_SERVER = 'mdb.stopMCPServer', - GET_MCP_SERVER_CONFIG = 'mdb.getMCPServerConfig', -} + START_MCP_SERVER: 'mdb.startMCPServer', + STOP_MCP_SERVER: 'mdb.stopMCPServer', + GET_MCP_SERVER_CONFIG: 'mdb.getMCPServerConfig', +} as const; -export type ExtensionCommand = EXTENSION_COMMANDS; +export type ExtensionCommand = + (typeof EXTENSION_COMMANDS)[keyof typeof EXTENSION_COMMANDS]; export default EXTENSION_COMMANDS; diff --git a/src/connectionController.ts b/src/connectionController.ts index b68a5debf..807ae9a2b 100644 --- a/src/connectionController.ts +++ b/src/connectionController.ts @@ -14,7 +14,10 @@ import { mongoLogId } from 'mongodb-log-writer'; import { extractSecrets } from '@mongodb-js/connection-info'; import { adjustConnectionOptionsBeforeConnect } from '@mongodb-js/connection-form'; -import { CONNECTION_STATUS } from './views/webview-app/extension-app-message-constants'; +import { + CONNECTION_STATUS, + type ConnectionStatus, +} from './views/webview-app/extension-app-message-constants'; import { createLogger } from './logging'; import formatError from './utils/formatError'; import type { StorageController } from './storage'; @@ -44,16 +47,22 @@ interface DataServiceEventTypes { ACTIVE_CONNECTION_CHANGED: []; } -export enum ConnectionTypes { - CONNECTION_FORM = 'CONNECTION_FORM', - CONNECTION_STRING = 'CONNECTION_STRING', - CONNECTION_ID = 'CONNECTION_ID', -} +export const CONNECTION_TYPES = { + CONNECTION_FORM: 'CONNECTION_FORM', + CONNECTION_STRING: 'CONNECTION_STRING', + CONNECTION_ID: 'CONNECTION_ID', +} as const; -export enum NewConnectionType { - NEW_CONNECTION = 'NEW_CONNECTION', - SAVED_CONNECTION = 'SAVED_CONNECTION', -} +export type ConnectionTypes = + (typeof CONNECTION_TYPES)[keyof typeof CONNECTION_TYPES]; + +export const NEW_CONNECTION_TYPE = { + NEW_CONNECTION: 'NEW_CONNECTION', + SAVED_CONNECTION: 'SAVED_CONNECTION', +} as const; + +export type NewConnectionType = + (typeof NEW_CONNECTION_TYPE)[keyof typeof NEW_CONNECTION_TYPE]; interface ConnectionAttemptResult { successfullyConnected: boolean; @@ -341,7 +350,7 @@ export default class ConnectionController { connectionOptions: { connectionString: connectionStringData.toString(), }, - connectionType: ConnectionTypes.CONNECTION_STRING, + connectionType: CONNECTION_TYPES.CONNECTION_STRING, name, })); @@ -689,7 +698,7 @@ export default class ConnectionController { const result = await this._connect( connectionId, - ConnectionTypes.CONNECTION_ID, + CONNECTION_TYPES.CONNECTION_ID, ); /** After successfully connecting with an overridden connection @@ -1147,7 +1156,7 @@ export default class ConnectionController { return url.toString(); } - getConnectionStatus(): CONNECTION_STATUS { + getConnectionStatus(): ConnectionStatus { if (this.isCurrentlyConnected()) { if (this.isDisconnecting()) { return CONNECTION_STATUS.DISCONNECTING; @@ -1208,7 +1217,7 @@ export default class ConnectionController { { label: 'Add new connection', data: { - type: NewConnectionType.NEW_CONNECTION, + type: NEW_CONNECTION_TYPE.NEW_CONNECTION, }, }, ]; @@ -1218,7 +1227,7 @@ export default class ConnectionController { { label: 'Add new connection', data: { - type: NewConnectionType.NEW_CONNECTION, + type: NEW_CONNECTION_TYPE.NEW_CONNECTION, }, }, ...Object.values(this._connections) @@ -1228,7 +1237,7 @@ export default class ConnectionController { .map((item: LoadedConnection) => ({ label: item.name, data: { - type: NewConnectionType.SAVED_CONNECTION, + type: NEW_CONNECTION_TYPE.SAVED_CONNECTION, connectionId: item.id, }, })), @@ -1247,7 +1256,9 @@ export default class ConnectionController { return false; } - if (selectedQuickPickItem.data.type === NewConnectionType.NEW_CONNECTION) { + if ( + selectedQuickPickItem.data.type === NEW_CONNECTION_TYPE.NEW_CONNECTION + ) { return this.connectWithURI(); } diff --git a/src/documentSource.ts b/src/documentSource.ts index 066c96cb6..1797080b7 100644 --- a/src/documentSource.ts +++ b/src/documentSource.ts @@ -1,8 +1,11 @@ -export enum DocumentSource { - DOCUMENT_SOURCE_TREEVIEW = 'treeview', - DOCUMENT_SOURCE_PLAYGROUND = 'playground', - DOCUMENT_SOURCE_COLLECTIONVIEW = 'collectionview', - DOCUMENT_SOURCE_CODELENS = 'codelens', -} +export const DOCUMENT_SOURCE = { + DOCUMENT_SOURCE_TREEVIEW: 'treeview', + DOCUMENT_SOURCE_PLAYGROUND: 'playground', + DOCUMENT_SOURCE_COLLECTIONVIEW: 'collectionview', + DOCUMENT_SOURCE_CODELENS: 'codelens', +} as const; + +export type DocumentSource = + (typeof DOCUMENT_SOURCE)[keyof typeof DOCUMENT_SOURCE]; export type DocumentSourceDetails = 'database' | 'collection' | undefined; diff --git a/src/editors/editDocumentCodeLensProvider.ts b/src/editors/editDocumentCodeLensProvider.ts index ea541dbfc..1f362a678 100644 --- a/src/editors/editDocumentCodeLensProvider.ts +++ b/src/editors/editDocumentCodeLensProvider.ts @@ -3,9 +3,9 @@ import { EJSON } from 'bson'; import type { Document } from 'bson'; import type ConnectionController from '../connectionController'; -import { DocumentSource } from '../documentSource'; +import { DOCUMENT_SOURCE, type DocumentSource } from '../documentSource'; import type { EditDocumentInfo } from '../types/editDocumentInfoType'; -import EXTENSION_COMMANDS from '../commands'; +import EXTENSION_COMMANDS, { type ExtensionCommand } from '../commands'; import { PLAYGROUND_RESULT_URI } from './playgroundResultProvider'; import type { PlaygroundRunResult } from '../types/playgroundType'; @@ -38,14 +38,14 @@ export default class EditDocumentCodeLensProvider resultCodeLensesInfo = this._updateCodeLensesForCursor({ ...data, - source: DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, }); this._codeLensesInfo[data.uri.toString()] = resultCodeLensesInfo; } updateCodeLensesForPlayground(playgroundResult: PlaygroundRunResult): void { - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; let resultCodeLensesInfo: EditDocumentInfo[] = []; if (!playgroundResult || !playgroundResult.content) { @@ -144,7 +144,7 @@ export default class EditDocumentCodeLensProvider const range = new vscode.Range(position, position); const command: { title: string; - command: EXTENSION_COMMANDS; + command: ExtensionCommand; arguments: EditDocumentInfo[]; } = { title: 'Edit Document', diff --git a/src/editors/mongoDBDocumentService.ts b/src/editors/mongoDBDocumentService.ts index 14e955b74..769be2c33 100644 --- a/src/editors/mongoDBDocumentService.ts +++ b/src/editors/mongoDBDocumentService.ts @@ -3,7 +3,7 @@ import type { Document } from 'bson'; import type ConnectionController from '../connectionController'; import { createLogger } from '../logging'; -import { DocumentSource } from '../documentSource'; +import { DOCUMENT_SOURCE, type DocumentSource } from '../documentSource'; import type { EditDocumentInfo } from '../types/editDocumentInfoType'; import formatError from '../utils/formatError'; import type { StatusView } from '../views'; @@ -53,7 +53,7 @@ export default class MongoDBDocumentService { this._telemetryService.track( new DocumentUpdatedTelemetryEvent( - DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, false, ), ); diff --git a/src/editors/queryWithCopilotCodeLensProvider.ts b/src/editors/queryWithCopilotCodeLensProvider.ts index d1a95c7f7..b07eb54c3 100644 --- a/src/editors/queryWithCopilotCodeLensProvider.ts +++ b/src/editors/queryWithCopilotCodeLensProvider.ts @@ -3,7 +3,7 @@ import EXTENSION_COMMANDS from '../commands'; import type { SendMessageToParticipantFromInputOptions } from '../participant/participantTypes'; import { isPlayground } from '../utils/playground'; import { COPILOT_EXTENSION_ID } from '../participant/constants'; -import { DocumentSource } from '../documentSource'; +import { DOCUMENT_SOURCE } from '../documentSource'; export class QueryWithCopilotCodeLensProvider implements vscode.CodeLensProvider @@ -34,7 +34,7 @@ export class QueryWithCopilotCodeLensProvider command: 'query', isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_CODELENS, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_CODELENS, source_details: undefined, }, }; diff --git a/src/explorer/collectionTreeItem.ts b/src/explorer/collectionTreeItem.ts index 72993bce9..9aa088693 100644 --- a/src/explorer/collectionTreeItem.ts +++ b/src/explorer/collectionTreeItem.ts @@ -3,7 +3,7 @@ import path from 'path'; import type { DataService } from 'mongodb-data-service'; import DocumentListTreeItem, { - CollectionTypes, + COLLECTION_TYPES, MAX_DOCUMENTS_VISIBLE, } from './documentListTreeItem'; import formatError from '../utils/formatError'; @@ -19,12 +19,12 @@ function getIconPath( const LIGHT = path.join(getImagesPath(), 'light'); const DARK = path.join(getImagesPath(), 'dark'); - if (type === CollectionTypes.timeseries) { + if (type === COLLECTION_TYPES.timeseries) { return { light: vscode.Uri.file(path.join(LIGHT, 'collection-timeseries.svg')), dark: vscode.Uri.file(path.join(DARK, 'collection-timeseries.svg')), }; - } else if (type === CollectionTypes.collection) { + } else if (type === COLLECTION_TYPES.collection) { if (isExpanded) { return { light: vscode.Uri.file(path.join(LIGHT, 'collection-folder-open.svg')), @@ -158,7 +158,7 @@ export default class CollectionTreeItem }); this.tooltip = - collection.type === CollectionTypes.view + collection.type === COLLECTION_TYPES.view ? 'Read only view' : collection.name; this.iconPath = getIconPath(collection.type, isExpanded); @@ -321,8 +321,8 @@ export default class CollectionTreeItem refreshDocumentCount = async (): Promise => { // Skip the count on views and time-series collections since it will error. if ( - this._type === CollectionTypes.view || - this._type === CollectionTypes.timeseries + this._type === COLLECTION_TYPES.view || + this._type === COLLECTION_TYPES.timeseries ) { this.documentCount = null; return 0; diff --git a/src/explorer/documentListTreeItem.ts b/src/explorer/documentListTreeItem.ts index d9d511620..f37fb0339 100644 --- a/src/explorer/documentListTreeItem.ts +++ b/src/explorer/documentListTreeItem.ts @@ -17,11 +17,14 @@ const log = createLogger('documents tree item'); export const MAX_DOCUMENTS_VISIBLE = 10; export const DOCUMENT_LIST_ITEM = 'documentListTreeItem'; -export enum CollectionTypes { - collection = 'collection', - view = 'view', - timeseries = 'timeseries', -} +export const COLLECTION_TYPES = { + collection: 'collection', + view: 'view', + timeseries: 'timeseries', +} as const; + +export type CollectionTypes = + (typeof COLLECTION_TYPES)[keyof typeof COLLECTION_TYPES]; const ITEM_LABEL = 'Documents'; @@ -53,7 +56,7 @@ const getCollapsableStateForDocumentList = ( isExpanded: boolean, type: string, ): vscode.TreeItemCollapsibleState => { - if (type === CollectionTypes.view) { + if (type === COLLECTION_TYPES.view) { return vscode.TreeItemCollapsibleState.None; } @@ -78,7 +81,7 @@ function getIconPath(): { light: vscode.Uri; dark: vscode.Uri } { } function getTooltip(type: string, documentCount: number | null): string { - const typeString = type === CollectionTypes.view ? 'View' : 'Collection'; + const typeString = type === COLLECTION_TYPES.view ? 'View' : 'Collection'; if (documentCount !== null) { return `${typeString} Documents - ${documentCount}`; } @@ -178,7 +181,7 @@ export default class DocumentListTreeItem } async getChildren(): Promise { - if (!this.isExpanded || this.type === CollectionTypes.view) { + if (!this.isExpanded || this.type === COLLECTION_TYPES.view) { return []; } diff --git a/src/explorer/explorerController.ts b/src/explorer/explorerController.ts index f29154d92..8caff6a10 100644 --- a/src/explorer/explorerController.ts +++ b/src/explorer/explorerController.ts @@ -6,13 +6,17 @@ import { createTrackedTreeView } from '../utils/treeViewHelper'; import type { TelemetryService } from '../telemetry'; export default class ExplorerController { + private _connectionController: ConnectionController; + private _telemetryService: TelemetryService; private _treeController: ExplorerTreeController; private _treeView?: vscode.TreeView; constructor( - private _connectionController: ConnectionController, - private _telemetryService: TelemetryService, + connectionController: ConnectionController, + telemetryService: TelemetryService, ) { + this._connectionController = connectionController; + this._telemetryService = telemetryService; this._treeController = new ExplorerTreeController( this._connectionController, this._telemetryService, diff --git a/src/explorer/explorerTreeController.ts b/src/explorer/explorerTreeController.ts index 135e9a923..fc83ee88b 100644 --- a/src/explorer/explorerTreeController.ts +++ b/src/explorer/explorerTreeController.ts @@ -4,7 +4,7 @@ import type ConnectionController from '../connectionController'; import ConnectionTreeItem from './connectionTreeItem'; import { createLogger } from '../logging'; import { DOCUMENT_ITEM } from './documentTreeItem'; -import { DOCUMENT_LIST_ITEM, CollectionTypes } from './documentListTreeItem'; +import { DOCUMENT_LIST_ITEM, COLLECTION_TYPES } from './documentListTreeItem'; import EXTENSION_COMMANDS from '../commands'; import { sortTreeItemsByLabel } from './treeItemUtils'; import type { LoadedConnection } from '../storage/connectionStorage'; @@ -20,11 +20,16 @@ export default class ExplorerTreeController implements vscode.TreeDataProvider { private _connectionTreeItems: { [key: string]: ConnectionTreeItem }; + private _connectionController: ConnectionController; + private _telemetryService: TelemetryService; constructor( - private _connectionController: ConnectionController, - private _telemetryService: TelemetryService, + connectionController: ConnectionController, + telemetryService: TelemetryService, ) { + this._connectionController = connectionController; + this._telemetryService = telemetryService; + this._onDidChangeTreeData = new vscode.EventEmitter(); this.onDidChangeTreeData = this._onDidChangeTreeData.event; @@ -122,7 +127,7 @@ export default class ExplorerTreeController if ( selectedItem.contextValue === DOCUMENT_LIST_ITEM && - selectedItem.type === CollectionTypes.view + selectedItem.type === COLLECTION_TYPES.view ) { await vscode.commands.executeCommand( EXTENSION_COMMANDS.MDB_VIEW_COLLECTION_DOCUMENTS, diff --git a/src/explorer/fieldTreeItem.ts b/src/explorer/fieldTreeItem.ts index 392c5af26..af73e8151 100644 --- a/src/explorer/fieldTreeItem.ts +++ b/src/explorer/fieldTreeItem.ts @@ -8,25 +8,27 @@ import type TreeItemParent from './treeItemParentInterface'; // types returned by `parseSchema` with `mongodb-schema`. // We have types for elements we have special handing for (icons). // https://docs.mongodb.com/manual/reference/bson-types/ -export enum FieldType { - array = 'Array', - binary = 'Binary', - bool = 'Boolean', - date = 'Date', - decimal = 'Decimal128', - document = 'Document', - int = '32-bit integer', - javascript = 'Javascript', - long = '64-bit integer', - null = 'Null', - number = 'Number', - object = 'Object', - objectId = 'ObjectID', - regex = 'Regular Expression', - string = 'String', - timestamp = 'Timestamp', - undefined = 'Undefined', -} +export const FIELD_TYPES = { + array: 'Array', + binary: 'Binary', + bool: 'Boolean', + date: 'Date', + decimal: 'Decimal128', + document: 'Document', + int: '32-bit integer', + javascript: 'Javascript', + long: '64-bit integer', + null: 'Null', + number: 'Number', + object: 'Object', + objectId: 'ObjectID', + regex: 'Regular Expression', + string: 'String', + timestamp: 'Timestamp', + undefined: 'Undefined', +} as const; + +export type FieldType = (typeof FIELD_TYPES)[keyof typeof FIELD_TYPES]; export type SchemaFieldType = { name: string; @@ -42,10 +44,10 @@ export type SchemaFieldType = { export const fieldIsExpandable = (field: SchemaFieldType): boolean => { return ( field.probability === 1 && - (field.type === FieldType.document || - field.type === FieldType.array || - field.bsonType === FieldType.document || - field.bsonType === FieldType.array) + (field.type === FIELD_TYPES.document || + field.type === FIELD_TYPES.array || + field.bsonType === FIELD_TYPES.document || + field.bsonType === FIELD_TYPES.array) ); }; @@ -75,44 +77,44 @@ export const getIconFileNameForField = ( // The field has polymorphic data types. return 'mixed-type'; } - if (fieldType === FieldType.array) { + if (fieldType === FIELD_TYPES.array) { return 'array'; } - if (fieldType === FieldType.binary) { + if (fieldType === FIELD_TYPES.binary) { return 'binary'; } - if (fieldType === FieldType.bool) { + if (fieldType === FIELD_TYPES.bool) { return 'boolean'; } - if (fieldType === FieldType.date) { + if (fieldType === FIELD_TYPES.date) { return 'date'; } - if (fieldType === FieldType.decimal) { + if (fieldType === FIELD_TYPES.decimal) { return 'double'; } - if (fieldType === FieldType.null) { + if (fieldType === FIELD_TYPES.null) { return 'null'; } if ( - fieldType === FieldType.int || - fieldType === FieldType.long || - fieldType === FieldType.number + fieldType === FIELD_TYPES.int || + fieldType === FIELD_TYPES.long || + fieldType === FIELD_TYPES.number ) { return 'number'; } - if (fieldType === FieldType.object || fieldType === FieldType.document) { + if (fieldType === FIELD_TYPES.object || fieldType === FIELD_TYPES.document) { return 'object'; } - if (fieldType === FieldType.objectId) { + if (fieldType === FIELD_TYPES.objectId) { return 'object-id'; } - if (fieldType === FieldType.regex) { + if (fieldType === FIELD_TYPES.regex) { return 'regex'; } - if (fieldType === FieldType.string) { + if (fieldType === FIELD_TYPES.string) { return 'string'; } - if (fieldType === FieldType.timestamp) { + if (fieldType === FIELD_TYPES.timestamp) { return 'timestamp'; } @@ -210,13 +212,13 @@ export default class FieldTreeItem this._childrenCache = {}; if ( - this.field.bsonType === FieldType.document || - this.field.type === FieldType.document + this.field.bsonType === FIELD_TYPES.document || + this.field.type === FIELD_TYPES.document ) { let subDocumentFields; - if (this.field.type === FieldType.document && this.field.types) { + if (this.field.type === FIELD_TYPES.document && this.field.types) { subDocumentFields = this.field.types[0].fields; - } else if (this.field.bsonType === FieldType.document) { + } else if (this.field.bsonType === FIELD_TYPES.document) { subDocumentFields = this.field.fields; } @@ -239,8 +241,8 @@ export default class FieldTreeItem }); } } else if ( - (this.field.type === FieldType.array || - this.field.bsonType === FieldType.array) && + (this.field.type === FIELD_TYPES.array || + this.field.bsonType === FIELD_TYPES.array) && this.field.types ) { const arrayElement = this.field.types[0]; diff --git a/src/explorer/helpExplorer.ts b/src/explorer/helpExplorer.ts index 9e1e61f99..73b6687f0 100644 --- a/src/explorer/helpExplorer.ts +++ b/src/explorer/helpExplorer.ts @@ -6,8 +6,9 @@ import { createTrackedTreeView } from '../utils/treeViewHelper'; export default class HelpExplorer { _treeController: HelpTree; _treeView?: vscode.TreeView; - - constructor(private _telemetryService: TelemetryService) { + private _telemetryService: TelemetryService; + constructor(telemetryService: TelemetryService) { + this._telemetryService = telemetryService; this._treeController = new HelpTree(); } diff --git a/src/explorer/indexTreeItem.ts b/src/explorer/indexTreeItem.ts index a4a2c6b5b..40e50c158 100644 --- a/src/explorer/indexTreeItem.ts +++ b/src/explorer/indexTreeItem.ts @@ -4,15 +4,18 @@ import path from 'path'; import { getImagesPath } from '../extensionConstants'; import type TreeItemParent from './treeItemParentInterface'; -export enum IndexKeyType { - ASCENDING = 1, - DESCENDING = -1, - TEXT = 'text', - HASHED = 'hashed', - GEO = '2d', // flat, cartesian geometry - GEOSPHERE = '2dsphere', // index assuming a spherical geometry - GEOHAYSTACK = 'geoHaystack', -} +export const INDEX_KEY_TYPES = { + ASCENDING: 1, + DESCENDING: -1, + TEXT: 'text', + HASHED: 'hashed', + GEO: '2d', // flat, cartesian geometry + GEOSPHERE: '2dsphere', // index assuming a spherical geometry + GEOHAYSTACK: 'geoHaystack', +} as const; + +export type IndexKeyType = + (typeof INDEX_KEY_TYPES)[keyof typeof INDEX_KEY_TYPES]; export type IndexModel = { v: number; @@ -24,26 +27,26 @@ export type IndexModel = { }; function getIconNameForIndexKeyType(indexKeyType: IndexKeyType): string { - if (indexKeyType === IndexKeyType.ASCENDING) { + if (indexKeyType === INDEX_KEY_TYPES.ASCENDING) { return 'ascending'; } - if (indexKeyType === IndexKeyType.DESCENDING) { + if (indexKeyType === INDEX_KEY_TYPES.DESCENDING) { return 'descending'; } - if (indexKeyType === IndexKeyType.TEXT) { + if (indexKeyType === INDEX_KEY_TYPES.TEXT) { return 'text'; } - if (indexKeyType === IndexKeyType.HASHED) { + if (indexKeyType === INDEX_KEY_TYPES.HASHED) { return 'hashed'; } if ( - indexKeyType === IndexKeyType.GEO || - indexKeyType === IndexKeyType.GEOHAYSTACK || - indexKeyType === IndexKeyType.GEOSPHERE + indexKeyType === INDEX_KEY_TYPES.GEO || + indexKeyType === INDEX_KEY_TYPES.GEOHAYSTACK || + indexKeyType === INDEX_KEY_TYPES.GEOSPHERE ) { return 'geospatial'; } diff --git a/src/explorer/playgroundsExplorer.ts b/src/explorer/playgroundsExplorer.ts index 84444cd02..c8fbe4f7f 100644 --- a/src/explorer/playgroundsExplorer.ts +++ b/src/explorer/playgroundsExplorer.ts @@ -6,8 +6,10 @@ import { createTrackedTreeView } from '../utils/treeViewHelper'; export default class PlaygroundsExplorer { private _treeController: PlaygroundsTree; private _treeView?: vscode.TreeView; + private _telemetryService: TelemetryService; - constructor(private _telemetryService: TelemetryService) { + constructor(telemetryService: TelemetryService) { + this._telemetryService = telemetryService; this._treeController = new PlaygroundsTree(); } diff --git a/src/extensionConstants.ts b/src/extensionConstants.ts index d9ab184a0..d4914f55e 100644 --- a/src/extensionConstants.ts +++ b/src/extensionConstants.ts @@ -1,9 +1,8 @@ import type { ExtensionContext } from 'vscode'; -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace ext { - export let context: ExtensionContext; -} +export const ext = { + context: undefined as unknown as ExtensionContext, +}; export function getImagesPath(): string { return ext.context.asAbsolutePath('images'); diff --git a/src/language/diagnosticCodes.ts b/src/language/diagnosticCodes.ts index 872310790..4166871f6 100644 --- a/src/language/diagnosticCodes.ts +++ b/src/language/diagnosticCodes.ts @@ -1,5 +1,8 @@ -enum DIAGNOSTIC_CODES { - invalidInteractiveSyntaxes = 'playground.invalidInteractiveSyntaxes', -} +export const DIAGNOSTIC_CODES = { + invalidInteractiveSyntaxes: 'playground.invalidInteractiveSyntaxes', +} as const; + +export type DiagnosticCodes = + (typeof DIAGNOSTIC_CODES)[keyof typeof DIAGNOSTIC_CODES]; export default DIAGNOSTIC_CODES; diff --git a/src/language/languageServerController.ts b/src/language/languageServerController.ts index fa1b26ed3..1b31d7f69 100644 --- a/src/language/languageServerController.ts +++ b/src/language/languageServerController.ts @@ -16,7 +16,7 @@ import type { ShellEvaluateResult, } from '../types/playgroundType'; import type { ClearCompletionsCache } from '../types/completionsCache'; -import { ServerCommands } from './serverCommands'; +import { SERVER_COMMANDS } from './serverCommands'; const log = createLogger('language server controller'); @@ -111,7 +111,7 @@ export default class LanguageServerController { // If the connection to server got closed, server will restart, // but we also need to re-send default configurations // https://jira.mongodb.org/browse/VSCODE-448 - this._client.onNotification(ServerCommands.MONGODB_SERVICE_CREATED, () => { + this._client.onNotification(SERVER_COMMANDS.MONGODB_SERVICE_CREATED, () => { const msg = this._currentConnectionId ? 'MongoDBService restored from an internal error' : 'MongoDBService initialized'; @@ -123,21 +123,27 @@ export default class LanguageServerController { hasConnectionOptions: !!this._currentConnectionOptions, })}`, ); - void this._client.sendRequest(ServerCommands.INITIALIZE_MONGODB_SERVICE, { - extensionPath: this._context.extensionPath, - connectionId: this._currentConnectionId, - connectionString: this._currentConnectionString, - connectionOptions: this._currentConnectionOptions, - }); + void this._client.sendRequest( + SERVER_COMMANDS.INITIALIZE_MONGODB_SERVICE, + { + extensionPath: this._context.extensionPath, + connectionId: this._currentConnectionId, + connectionString: this._currentConnectionString, + connectionOptions: this._currentConnectionOptions, + }, + ); }); - this._client.onNotification(ServerCommands.SHOW_INFO_MESSAGE, (message) => { - log.info('The info message shown to a user', message); - void vscode.window.showInformationMessage(message); - }); + this._client.onNotification( + SERVER_COMMANDS.SHOW_INFO_MESSAGE, + (message) => { + log.info('The info message shown to a user', message); + void vscode.window.showInformationMessage(message); + }, + ); this._client.onNotification( - ServerCommands.SHOW_ERROR_MESSAGE, + SERVER_COMMANDS.SHOW_ERROR_MESSAGE, (message) => { log.info('The error message shown to a user', message); void vscode.window.showErrorMessage(message); @@ -145,7 +151,7 @@ export default class LanguageServerController { ); this._client.onNotification( - ServerCommands.SHOW_CONSOLE_OUTPUT, + SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT, (outputs) => { for (const line of outputs) { this._consoleOutputChannel.appendLine( @@ -184,7 +190,7 @@ export default class LanguageServerController { // to the language server instance to execute scripts from a playground // and return results to the playground controller when ready. const res: ShellEvaluateResult = await this._client.sendRequest( - ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND, + SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND, playgroundExecuteParameters, token, ); @@ -217,7 +223,7 @@ export default class LanguageServerController { this._currentConnectionOptions = connectionOptions; const res = await this._client.sendRequest( - ServerCommands.ACTIVE_CONNECTION_CHANGED, + SERVER_COMMANDS.ACTIVE_CONNECTION_CHANGED, { connectionId, connectionString, @@ -230,14 +236,14 @@ export default class LanguageServerController { async resetCache(clear: ClearCompletionsCache): Promise { log.info('Resetting MongoDBService cache...', clear); await this._client.sendRequest( - ServerCommands.CLEAR_CACHED_COMPLETIONS, + SERVER_COMMANDS.CLEAR_CACHED_COMPLETIONS, clear, ); } async updateCurrentSessionFields(params): Promise { await this._client.sendRequest( - ServerCommands.UPDATE_CURRENT_SESSION_FIELDS, + SERVER_COMMANDS.UPDATE_CURRENT_SESSION_FIELDS, params, ); } diff --git a/src/language/mongoDBService.ts b/src/language/mongoDBService.ts index f6b0e102a..7e767c01b 100644 --- a/src/language/mongoDBService.ts +++ b/src/language/mongoDBService.ts @@ -25,7 +25,7 @@ import { isAtlasStream } from 'mongodb-build-info'; import { Worker as WorkerThreads } from 'worker_threads'; import formatError from '../utils/formatError'; -import { ServerCommands } from './serverCommands'; +import { SERVER_COMMANDS } from './serverCommands'; import type { ShellEvaluateResult, PlaygroundEvaluateParams, @@ -227,7 +227,7 @@ export default class MongoDBService { return new Promise((resolve) => { if (this._currentConnectionId !== params.connectionId) { void this._connection.sendNotification( - ServerCommands.SHOW_ERROR_MESSAGE, + SERVER_COMMANDS.SHOW_ERROR_MESSAGE, "The playground's active connection does not match the extension's active connection. Please reconnect and try again.", ); return resolve(null); @@ -267,11 +267,11 @@ export default class MongoDBService { ); worker?.on('message', ({ name, payload }) => { - if (name === ServerCommands.SHOW_CONSOLE_OUTPUT) { + if (name === SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT) { void this._connection.sendNotification(name, payload); } - if (name === ServerCommands.CODE_EXECUTION_RESULT) { + if (name === SERVER_COMMANDS.CODE_EXECUTION_RESULT) { const { error, data } = payload as { data: ShellEvaluateResult | null; error?: any; @@ -281,7 +281,7 @@ export default class MongoDBService { `WORKER error: ${util.inspect(error)}`, ); void this._connection.sendNotification( - ServerCommands.SHOW_ERROR_MESSAGE, + SERVER_COMMANDS.SHOW_ERROR_MESSAGE, formatError(error).message, ); } @@ -292,7 +292,7 @@ export default class MongoDBService { }); worker.postMessage({ - name: ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND, + name: SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND, data: { codeToEvaluate: params.codeToEvaluate, filePath: params.filePath, diff --git a/src/language/server.ts b/src/language/server.ts index 5717f7512..2f45a22e3 100644 --- a/src/language/server.ts +++ b/src/language/server.ts @@ -16,7 +16,7 @@ import { import { TextDocument } from 'vscode-languageserver-textdocument'; import MongoDBService from './mongoDBService'; -import { ServerCommands } from './serverCommands'; +import { SERVER_COMMANDS } from './serverCommands'; import type { PlaygroundEvaluateParams } from '../types/playgroundType'; import type { ClearCompletionsCache } from '../types/completionsCache'; @@ -78,7 +78,7 @@ connection.onInitialize((params: InitializeParams) => { connection.onInitialized(() => { void connection.sendNotification( - ServerCommands.MONGODB_SERVICE_CREATED, + SERVER_COMMANDS.MONGODB_SERVICE_CREATED, 'An instance of MongoDBService is created', ); @@ -158,25 +158,25 @@ connection.onDidChangeWatchedFiles((/* _change */) => { // Execute a playground. connection.onRequest( - ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND, + SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND, (evaluateParams: PlaygroundEvaluateParams, token: CancellationToken) => { return mongoDBService.evaluate(evaluateParams, token); }, ); // Send default configurations to mongoDBService. -connection.onRequest(ServerCommands.INITIALIZE_MONGODB_SERVICE, (settings) => { +connection.onRequest(SERVER_COMMANDS.INITIALIZE_MONGODB_SERVICE, (settings) => { mongoDBService.initialize(settings); }); // Change NodeDriverServiceProvider active connection. -connection.onRequest(ServerCommands.ACTIVE_CONNECTION_CHANGED, (params) => { +connection.onRequest(SERVER_COMMANDS.ACTIVE_CONNECTION_CHANGED, (params) => { return mongoDBService.activeConnectionChanged(params); }); // Set fields for tests. connection.onRequest( - ServerCommands.UPDATE_CURRENT_SESSION_FIELDS, + SERVER_COMMANDS.UPDATE_CURRENT_SESSION_FIELDS, ({ namespace, schemaFields }) => { return mongoDBService.cacheFields(namespace, schemaFields); }, @@ -184,7 +184,7 @@ connection.onRequest( // Clear cached completions by provided cache names. connection.onRequest( - ServerCommands.CLEAR_CACHED_COMPLETIONS, + SERVER_COMMANDS.CLEAR_CACHED_COMPLETIONS, (clear: ClearCompletionsCache) => { return mongoDBService.clearCachedCompletions(clear); }, diff --git a/src/language/serverCommands.ts b/src/language/serverCommands.ts index 3a7822422..9f629f3e3 100644 --- a/src/language/serverCommands.ts +++ b/src/language/serverCommands.ts @@ -1,17 +1,20 @@ -export enum ServerCommands { - ACTIVE_CONNECTION_CHANGED = 'ACTIVE_CONNECTION_CHANGED', - EXECUTE_CODE_FROM_PLAYGROUND = 'EXECUTE_CODE_FROM_PLAYGROUND', - EXECUTE_RANGE_FROM_PLAYGROUND = 'EXECUTE_RANGE_FROM_PLAYGROUND', - SHOW_ERROR_MESSAGE = 'SHOW_ERROR_MESSAGE', - SHOW_INFO_MESSAGE = 'SHOW_INFO_MESSAGE', - GET_EXPORT_TO_LANGUAGE_MODE = 'GET_EXPORT_TO_LANGUAGE_MODE', - UPDATE_CURRENT_SESSION_FIELDS = 'UPDATE_CURRENT_SESSION_FIELDS', - CLEAR_CACHED_COMPLETIONS = 'CLEAR_CACHED_COMPLETIONS', - MONGODB_SERVICE_CREATED = 'MONGODB_SERVICE_CREATED', - INITIALIZE_MONGODB_SERVICE = 'INITIALIZE_MONGODB_SERVICE', - CODE_EXECUTION_RESULT = 'CODE_EXECUTION_RESULT', - SHOW_CONSOLE_OUTPUT = 'SHOW_CONSOLE_OUTPUT', -} +export const SERVER_COMMANDS = { + ACTIVE_CONNECTION_CHANGED: 'ACTIVE_CONNECTION_CHANGED', + EXECUTE_CODE_FROM_PLAYGROUND: 'EXECUTE_CODE_FROM_PLAYGROUND', + EXECUTE_RANGE_FROM_PLAYGROUND: 'EXECUTE_RANGE_FROM_PLAYGROUND', + SHOW_ERROR_MESSAGE: 'SHOW_ERROR_MESSAGE', + SHOW_INFO_MESSAGE: 'SHOW_INFO_MESSAGE', + GET_EXPORT_TO_LANGUAGE_MODE: 'GET_EXPORT_TO_LANGUAGE_MODE', + UPDATE_CURRENT_SESSION_FIELDS: 'UPDATE_CURRENT_SESSION_FIELDS', + CLEAR_CACHED_COMPLETIONS: 'CLEAR_CACHED_COMPLETIONS', + MONGODB_SERVICE_CREATED: 'MONGODB_SERVICE_CREATED', + INITIALIZE_MONGODB_SERVICE: 'INITIALIZE_MONGODB_SERVICE', + CODE_EXECUTION_RESULT: 'CODE_EXECUTION_RESULT', + SHOW_CONSOLE_OUTPUT: 'SHOW_CONSOLE_OUTPUT', +} as const; + +export type ServerCommands = + (typeof SERVER_COMMANDS)[keyof typeof SERVER_COMMANDS]; export type PlaygroundRunParameters = { codeToEvaluate: string; diff --git a/src/language/worker.ts b/src/language/worker.ts index 0fea36a93..f93e935dc 100644 --- a/src/language/worker.ts +++ b/src/language/worker.ts @@ -1,7 +1,7 @@ import { NodeDriverServiceProvider } from '@mongosh/service-provider-node-driver'; import { ElectronRuntime } from '@mongosh/browser-runtime-electron'; import { parentPort } from 'worker_threads'; -import { ServerCommands } from './serverCommands'; +import { SERVER_COMMANDS } from './serverCommands'; import type { ShellEvaluateResult, @@ -44,7 +44,7 @@ type ExecuteCodeOptions = { function handleEvalPrint(values: EvaluationResult[]): void { parentPort?.postMessage({ - name: ServerCommands.SHOW_CONSOLE_OUTPUT, + name: SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT, payload: values.map((v) => { return typeof v.printable === 'string' ? v.printable @@ -124,9 +124,9 @@ export const execute = async ({ }; const handleMessageFromParentPort = async ({ name, data }): Promise => { - if (name === ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND) { + if (name === SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND) { parentPort?.postMessage({ - name: ServerCommands.CODE_EXECUTION_RESULT, + name: SERVER_COMMANDS.CODE_EXECUTION_RESULT, payload: await execute(data), }); } diff --git a/src/mdbExtensionController.ts b/src/mdbExtensionController.ts index d633f7eb6..1775ffb35 100644 --- a/src/mdbExtensionController.ts +++ b/src/mdbExtensionController.ts @@ -12,7 +12,7 @@ import ConnectionController from './connectionController'; import type ConnectionTreeItem from './explorer/connectionTreeItem'; import type DatabaseTreeItem from './explorer/databaseTreeItem'; import type DocumentListTreeItem from './explorer/documentListTreeItem'; -import { DocumentSource } from './documentSource'; +import { DOCUMENT_SOURCE } from './documentSource'; import type DocumentTreeItem from './explorer/documentTreeItem'; import EditDocumentCodeLensProvider from './editors/editDocumentCodeLensProvider'; import { EditorsController, PlaygroundController } from './editors'; @@ -32,7 +32,7 @@ import { LanguageServerController } from './language'; import launchMongoShell from './commands/launchMongoShell'; import type SchemaTreeItem from './explorer/schemaTreeItem'; import { StatusView } from './views'; -import { StorageController, StorageVariables } from './storage'; +import { StorageController, STORAGE_VARIABLES } from './storage'; import { DeepLinkTelemetryEvent, TelemetryService } from './telemetry'; import type PlaygroundsTreeItem from './explorer/playgroundsTreeItem'; import PlaygroundResultProvider from './editors/playgroundResultProvider'; @@ -249,9 +249,7 @@ export default class MDBExtensionController implements vscode.Disposable { try { if ( - !Object.values(EXTENSION_COMMANDS).includes( - command as EXTENSION_COMMANDS, - ) + !Object.values(EXTENSION_COMMANDS).includes(command as ExtensionCommand) ) { throw new Error( `Unable to execute command '${command}' since it is not registered by the MongoDB extension.`, @@ -772,7 +770,7 @@ export default class MDBExtensionController implements vscode.Disposable { EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, (element: DocumentTreeItem): Promise => { return this._editorsController.openMongoDBDocument({ - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, documentId: element.documentId, namespace: element.namespace, connectionId: this._connectionController.getActiveConnectionId(), @@ -1060,7 +1058,7 @@ export default class MDBExtensionController implements vscode.Disposable { } const hasBeenShownViewAlready = !!this._storageController.get( - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, ); if (hasBeenShownViewAlready) { @@ -1076,7 +1074,7 @@ export default class MDBExtensionController implements vscode.Disposable { } void this._storageController.update( - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, true, ); } diff --git a/src/participant/participant.ts b/src/participant/participant.ts index 42f95c6b7..04181140d 100644 --- a/src/participant/participant.ts +++ b/src/participant/participant.ts @@ -9,7 +9,7 @@ import type ConnectionController from '../connectionController'; import type { LoadedConnection } from '../storage/connectionStorage'; import EXTENSION_COMMANDS from '../commands'; import type { StorageController } from '../storage'; -import { StorageVariables } from '../storage'; +import { STORAGE_VARIABLES } from '../storage'; import { getContentLength, Prompts } from './prompts'; import type { ChatResult } from './constants'; import { @@ -54,7 +54,7 @@ import type { PromptIntent } from './prompts/intent'; import { isPlayground, getSelectedText, getAllText } from '../utils/playground'; import type { DataService } from 'mongodb-data-service'; import { - ParticipantErrorTypes, + PARTICIPANT_ERROR_TYPES, type ExportToPlaygroundError, } from './participantErrorTypes'; import type PlaygroundResultProvider from '../editors/playgroundResultProvider'; @@ -69,7 +69,7 @@ import type { import { DEFAULT_EXPORT_TO_LANGUAGE_DRIVER_SYNTAX } from '../editors/exportToLanguageCodeLensProvider'; import { EXPORT_TO_LANGUAGE_ALIASES } from '../editors/playgroundSelectionCodeActionProvider'; import { CollectionTreeItem, DatabaseTreeItem } from '../explorer'; -import { DocumentSource } from '../documentSource'; +import { DOCUMENT_SOURCE } from '../documentSource'; const log = createLogger('participant'); @@ -241,7 +241,7 @@ export default class ParticipantController { message: `I want to ask questions about the \`${databaseName}\` database.`, isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, source_details: 'database', }, }); @@ -252,7 +252,7 @@ export default class ParticipantController { message: `I want to ask questions about the \`${databaseName}\` database's \`${collectionName}\` collection.`, isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, source_details: 'collection', }, }); @@ -1779,7 +1779,7 @@ export default class ParticipantController { this._telemetryService.track( new ParticipantResponseFailedTelemetryEvent( 'docs', - ParticipantErrorTypes.DOCS_CHATBOT_API, + PARTICIPANT_ERROR_TYPES.DOCS_CHATBOT_API, ), ); @@ -1973,7 +1973,7 @@ export default class ParticipantController { const [request, , stream] = args; try { const hasBeenShownWelcomeMessageAlready = !!this._storageController.get( - StorageVariables.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, + STORAGE_VARIABLES.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, ); if (!hasBeenShownWelcomeMessageAlready) { stream.markdown( @@ -1988,7 +1988,7 @@ Please see our [FAQ](https://www.mongodb.com/docs/generative-ai-faq/) for more i ); await this._storageController.update( - StorageVariables.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, + STORAGE_VARIABLES.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, true, ); } diff --git a/src/participant/participantErrorTypes.ts b/src/participant/participantErrorTypes.ts index d83ce8598..221116f9a 100644 --- a/src/participant/participantErrorTypes.ts +++ b/src/participant/participantErrorTypes.ts @@ -1,10 +1,13 @@ -export enum ParticipantErrorTypes { - CHAT_MODEL_OFF_TOPIC = 'Chat Model Off Topic', - INVALID_PROMPT = 'Invalid Prompt', - FILTERED = 'Filtered by Responsible AI Service', - OTHER = 'Other', - DOCS_CHATBOT_API = 'Docs Chatbot API Issue', -} +export const PARTICIPANT_ERROR_TYPES = { + CHAT_MODEL_OFF_TOPIC: 'Chat Model Off Topic', + INVALID_PROMPT: 'Invalid Prompt', + FILTERED: 'Filtered by Responsible AI Service', + OTHER: 'Other', + DOCS_CHATBOT_API: 'Docs Chatbot API Issue', +} as const; + +export type ParticipantErrorType = + (typeof PARTICIPANT_ERROR_TYPES)[keyof typeof PARTICIPANT_ERROR_TYPES]; export type ExportToPlaygroundError = | 'cancelled' diff --git a/src/participant/prompts/promptHistory.ts b/src/participant/prompts/promptHistory.ts index 86226d71d..0804cfb9d 100644 --- a/src/participant/prompts/promptHistory.ts +++ b/src/participant/prompts/promptHistory.ts @@ -1,5 +1,5 @@ import * as vscode from 'vscode'; -import { ParticipantErrorTypes } from '../participantErrorTypes'; +import { PARTICIPANT_ERROR_TYPES } from '../participantErrorTypes'; import type { ChatResult } from '../constants'; import type { ParticipantResponseType } from '../participantTypes'; @@ -13,7 +13,7 @@ export class PromptHistory { }): vscode.LanguageModelChatMessage | undefined { if ( currentTurn.result.errorDetails?.message === - ParticipantErrorTypes.FILTERED + PARTICIPANT_ERROR_TYPES.FILTERED ) { return undefined; } @@ -83,7 +83,7 @@ export class PromptHistory { if ( nextTurn instanceof vscode.ChatResponseTurn && - nextTurn.result.errorDetails?.message === ParticipantErrorTypes.FILTERED + nextTurn.result.errorDetails?.message === PARTICIPANT_ERROR_TYPES.FILTERED ) { // If the response to this request led to a filtered error, // we do not want to include it in the history diff --git a/src/storage/connectionStorage.ts b/src/storage/connectionStorage.ts index be0d59ac8..50ca7abd2 100644 --- a/src/storage/connectionStorage.ts +++ b/src/storage/connectionStorage.ts @@ -8,12 +8,15 @@ import type { ConnectionOptions } from 'mongodb-data-service'; import { createLogger } from '../logging'; import type StorageController from './storageController'; -import type { SecretStorageLocationType } from './storageController'; -import { - DefaultSavingLocations, - SecretStorageLocation, +import type { + SecretStorageLocationType, StorageLocation, - StorageVariables, +} from './storageController'; +import { + DEFAULT_SAVING_LOCATIONS, + SECRET_STORAGE_LOCATIONS, + STORAGE_LOCATIONS, + STORAGE_VARIABLES, } from './storageController'; import { v4 as uuidv4 } from 'uuid'; @@ -42,11 +45,11 @@ export type PresetSavedConnectionWithSource = PresetSavedConnection & { type StoreConnectionInfoWithConnectionOptions = StoreConnectionInfo & Required>; -type StoreConnectionInfoWithSecretStorageLocation = StoreConnectionInfo & +type StoreConnectionInfoWithSECRET_STORAGE_LOCATIONS = StoreConnectionInfo & Required>; export type LoadedConnection = StoreConnectionInfoWithConnectionOptions & - StoreConnectionInfoWithSecretStorageLocation; + StoreConnectionInfoWithSECRET_STORAGE_LOCATIONS; export class ConnectionStorage { _storageController: StorageController; @@ -133,9 +136,12 @@ export class ConnectionStorage { async saveConnection(connection: LoadedConnection): Promise { if ( - ![StorageLocation.GLOBAL, StorageLocation.WORKSPACE].includes( - connection.storageLocation, - ) + !( + [ + STORAGE_LOCATIONS.GLOBAL, + STORAGE_LOCATIONS.WORKSPACE, + ] as StorageLocation[] + ).includes(connection.storageLocation) ) { return; } @@ -157,9 +163,9 @@ export class ConnectionStorage { connectionWithoutSecrets: StoreConnectionInfo, ): Promise { const variableName = - connectionWithoutSecrets.storageLocation === StorageLocation.GLOBAL - ? StorageVariables.GLOBAL_SAVED_CONNECTIONS - : StorageVariables.WORKSPACE_SAVED_CONNECTIONS; + connectionWithoutSecrets.storageLocation === STORAGE_LOCATIONS.GLOBAL + ? STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS + : STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS; // Get the current saved connections. let savedConnections = this._storageController.get( @@ -211,8 +217,8 @@ export class ConnectionStorage { connectionString: presetConnection.connectionString, }, source: presetConnection.source, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }) satisfies LoadedConnection, ); } @@ -220,12 +226,12 @@ export class ConnectionStorage { async loadConnections(): Promise { const globalAndWorkspaceConnections = Object.values({ ...this._storageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ), ...this._storageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ), }); @@ -265,21 +271,21 @@ export class ConnectionStorage { // See if the connection exists in the saved global or workspace connections // and remove it if it is. const globalStoredConnections = this._storageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); if (globalStoredConnections && globalStoredConnections[connectionId]) { delete globalStoredConnections[connectionId]; void this._storageController.update( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, globalStoredConnections, - StorageLocation.GLOBAL, + STORAGE_LOCATIONS.GLOBAL, ); } const workspaceStoredConnections = this._storageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); if ( workspaceStoredConnections && @@ -287,21 +293,21 @@ export class ConnectionStorage { ) { delete workspaceStoredConnections[connectionId]; void this._storageController.update( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, workspaceStoredConnections, - StorageLocation.WORKSPACE, + STORAGE_LOCATIONS.WORKSPACE, ); } } hasSavedConnections(): boolean { const savedWorkspaceConnections = this._storageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); const savedGlobalConnections = this._storageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); return !!( @@ -316,15 +322,17 @@ export class ConnectionStorage { .getConfiguration('mdb.connectionSaving') .get('defaultConnectionSavingLocation'); - if (defaultConnectionSavingLocation === DefaultSavingLocations.Workspace) { - return StorageLocation.WORKSPACE; + if ( + defaultConnectionSavingLocation === DEFAULT_SAVING_LOCATIONS.Workspace + ) { + return STORAGE_LOCATIONS.WORKSPACE; } - if (defaultConnectionSavingLocation === DefaultSavingLocations.Global) { - return StorageLocation.GLOBAL; + if (defaultConnectionSavingLocation === DEFAULT_SAVING_LOCATIONS.Global) { + return STORAGE_LOCATIONS.GLOBAL; } - return StorageLocation.NONE; + return STORAGE_LOCATIONS.NONE; } getUserAnonymousId(): string { diff --git a/src/storage/index.ts b/src/storage/index.ts index 0c0fcf6ff..e8a426b7e 100644 --- a/src/storage/index.ts +++ b/src/storage/index.ts @@ -1,3 +1,6 @@ -import StorageController, { StorageVariables } from './storageController'; +import StorageController, { + STORAGE_VARIABLES, + STORAGE_LOCATIONS, +} from './storageController'; -export { StorageController, StorageVariables }; +export { StorageController, STORAGE_VARIABLES, STORAGE_LOCATIONS }; diff --git a/src/storage/storageController.ts b/src/storage/storageController.ts index 5d0d389fc..1f4d971a1 100644 --- a/src/storage/storageController.ts +++ b/src/storage/storageController.ts @@ -3,31 +3,41 @@ import { v4 as uuidv4 } from 'uuid'; import type { StoreConnectionInfo } from './connectionStorage'; -export enum StorageVariables { +export const STORAGE_VARIABLES = { // Only exists on globalState. - GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW = 'GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW', - GLOBAL_SAVED_CONNECTIONS = 'GLOBAL_SAVED_CONNECTIONS', + GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW: 'GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW', + GLOBAL_SAVED_CONNECTIONS: 'GLOBAL_SAVED_CONNECTIONS', // Analytics user identify. - GLOBAL_USER_ID = 'GLOBAL_USER_ID', - GLOBAL_ANONYMOUS_ID = 'GLOBAL_ANONYMOUS_ID', + GLOBAL_USER_ID: 'GLOBAL_USER_ID', + GLOBAL_ANONYMOUS_ID: 'GLOBAL_ANONYMOUS_ID', // Only exists on workspaceState. - WORKSPACE_SAVED_CONNECTIONS = 'WORKSPACE_SAVED_CONNECTIONS', - COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE = 'COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE', -} + WORKSPACE_SAVED_CONNECTIONS: 'WORKSPACE_SAVED_CONNECTIONS', + COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE: + 'COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE', +} as const; + +export type StorageVariables = + (typeof STORAGE_VARIABLES)[keyof typeof STORAGE_VARIABLES]; // Typically variables default to 'GLOBAL' scope. -export enum StorageLocation { - GLOBAL = 'GLOBAL', - WORKSPACE = 'WORKSPACE', - NONE = 'NONE', -} +export const STORAGE_LOCATIONS = { + GLOBAL: 'GLOBAL', + WORKSPACE: 'WORKSPACE', + NONE: 'NONE', +} as const; + +export type StorageLocation = + (typeof STORAGE_LOCATIONS)[keyof typeof STORAGE_LOCATIONS]; // Coupled with the `defaultConnectionSavingLocation` configuration in `package.json`. -export enum DefaultSavingLocations { - 'Workspace' = 'Workspace', - 'Global' = 'Global', - 'Session Only' = 'Session Only', -} +export const DEFAULT_SAVING_LOCATIONS = { + Workspace: 'Workspace', + Global: 'Global', + 'Session Only': 'Session Only', +} as const; + +export type DefaultSavingLocations = + (typeof DEFAULT_SAVING_LOCATIONS)[keyof typeof DEFAULT_SAVING_LOCATIONS]; export type ConnectionsFromStorage = { [connectionId: string]: StoreConnectionInfo; @@ -35,7 +45,7 @@ export type ConnectionsFromStorage = { // Keytar is deprecated and no longer used. All new // connections use 'SecretStorage'. -export const SecretStorageLocation = { +export const SECRET_STORAGE_LOCATIONS = { Keytar: 'vscode.Keytar', KeytarSecondAttempt: 'vscode.KeytarSecondAttempt', @@ -43,40 +53,38 @@ export const SecretStorageLocation = { } as const; export type SecretStorageLocationType = - | typeof SecretStorageLocation.Keytar - | typeof SecretStorageLocation.KeytarSecondAttempt - | typeof SecretStorageLocation.SecretStorage; + (typeof SECRET_STORAGE_LOCATIONS)[keyof typeof SECRET_STORAGE_LOCATIONS]; interface StorageVariableContents { - [StorageVariables.GLOBAL_USER_ID]: string; - [StorageVariables.GLOBAL_ANONYMOUS_ID]: string; - [StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW]: boolean; - [StorageVariables.GLOBAL_SAVED_CONNECTIONS]: ConnectionsFromStorage; - [StorageVariables.WORKSPACE_SAVED_CONNECTIONS]: ConnectionsFromStorage; - [StorageVariables.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE]: boolean; + [STORAGE_VARIABLES.GLOBAL_USER_ID]: string; + [STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID]: string; + [STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW]: boolean; + [STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS]: ConnectionsFromStorage; + [STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS]: ConnectionsFromStorage; + [STORAGE_VARIABLES.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE]: boolean; } type StoredVariableName = keyof StorageVariableContents; type StoredItem = StorageVariableContents[T]; export default class StorageController { _storage: { - [StorageLocation.GLOBAL]: vscode.Memento; - [StorageLocation.WORKSPACE]: vscode.Memento; + [STORAGE_LOCATIONS.GLOBAL]: vscode.Memento; + [STORAGE_LOCATIONS.WORKSPACE]: vscode.Memento; }; _secretStorage: vscode.SecretStorage; constructor(context: vscode.ExtensionContext) { this._storage = { - [StorageLocation.GLOBAL]: context.globalState, - [StorageLocation.WORKSPACE]: context.workspaceState, + [STORAGE_LOCATIONS.GLOBAL]: context.globalState, + [STORAGE_LOCATIONS.WORKSPACE]: context.workspaceState, }; this._secretStorage = context.secrets; } get( variableName: T, - storageLocation: StorageLocation = StorageLocation.GLOBAL, + storageLocation: StorageLocation = STORAGE_LOCATIONS.GLOBAL, ): StoredItem { return this._storage[storageLocation].get(variableName); } @@ -85,19 +93,19 @@ export default class StorageController { update( variableName: T, value: StoredItem, - storageLocation: StorageLocation = StorageLocation.GLOBAL, + storageLocation: StorageLocation = STORAGE_LOCATIONS.GLOBAL, ): Thenable { this._storage[storageLocation].update(variableName, value); return Promise.resolve(); } getUserIdentity(): { anonymousId: string } { - let anonymousId = this.get(StorageVariables.GLOBAL_ANONYMOUS_ID); + let anonymousId = this.get(STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID); // The anonymousId becomes required with analytics-node v6. if (!anonymousId) { anonymousId = uuidv4(); - void this.update(StorageVariables.GLOBAL_ANONYMOUS_ID, anonymousId); + void this.update(STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID, anonymousId); } return { anonymousId }; diff --git a/src/telemetry/connectionTelemetry.ts b/src/telemetry/connectionTelemetry.ts index 1c4797070..fa8964f1c 100644 --- a/src/telemetry/connectionTelemetry.ts +++ b/src/telemetry/connectionTelemetry.ts @@ -1,9 +1,12 @@ import type { DataService } from 'mongodb-data-service'; import mongoDBBuildInfo from 'mongodb-build-info'; -import { ConnectionTypes } from '../connectionController'; import { createLogger } from '../logging'; import type { TopologyType } from 'mongodb'; +import { + CONNECTION_TYPES, + type ConnectionTypes, +} from '../connectionController'; const log = createLogger('connection telemetry helper'); // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -123,10 +126,10 @@ export async function getConnectionTelemetryProperties( connectionType: ConnectionTypes, ): Promise { let preparedProperties: NewConnectionTelemetryEventProperties = { - is_used_connect_screen: connectionType === ConnectionTypes.CONNECTION_FORM, + is_used_connect_screen: connectionType === CONNECTION_TYPES.CONNECTION_FORM, is_used_command_palette: - connectionType === ConnectionTypes.CONNECTION_STRING, - is_used_saved_connection: connectionType === ConnectionTypes.CONNECTION_ID, + connectionType === CONNECTION_TYPES.CONNECTION_STRING, + is_used_saved_connection: connectionType === CONNECTION_TYPES.CONNECTION_ID, vscode_mdb_extension_version: version, }; diff --git a/src/telemetry/telemetryEvents.ts b/src/telemetry/telemetryEvents.ts index cfe9a23b3..875907b16 100644 --- a/src/telemetry/telemetryEvents.ts +++ b/src/telemetry/telemetryEvents.ts @@ -1,9 +1,9 @@ import type { ExtensionCommand } from '../commands'; import type { DocumentSourceDetails } from '../documentSource'; -import { DocumentSource } from '../documentSource'; +import { DOCUMENT_SOURCE, type DocumentSource } from '../documentSource'; import type { ExportToPlaygroundError, - ParticipantErrorTypes, + ParticipantErrorType, } from '../participant/participantErrorTypes'; import type { ParticipantCommandType, @@ -422,7 +422,7 @@ export class ParticipantResponseFailedTelemetryEvent error_code?: string; /** The name of the error that caused the failure */ - error_name: ParticipantErrorTypes; + error_name: ParticipantErrorType; /** Additional details about the error if any. */ error_details?: string; @@ -430,7 +430,7 @@ export class ParticipantResponseFailedTelemetryEvent constructor( command: ParticipantResponseType, - errorName: ParticipantErrorTypes, + errorName: ParticipantErrorType, errorCode?: string, errorDetails?: string, ) { @@ -628,7 +628,7 @@ export class PresetConnectionEditedTelemetryEvent constructor(sourceDetails: 'tree_item' | 'header') { this.properties = { - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, source_details: sourceDetails, }; } diff --git a/src/telemetry/telemetryService.ts b/src/telemetry/telemetryService.ts index 5fb5c16bf..e298ae6e5 100644 --- a/src/telemetry/telemetryService.ts +++ b/src/telemetry/telemetryService.ts @@ -10,7 +10,10 @@ import type { ConnectionTypes } from '../connectionController'; import { createLogger } from '../logging'; import { getConnectionTelemetryProperties } from './connectionTelemetry'; import type { StorageController } from '../storage'; -import { ParticipantErrorTypes } from '../participant/participantErrorTypes'; +import { + PARTICIPANT_ERROR_TYPES, + type ParticipantErrorType, +} from '../participant/participantErrorTypes'; import type { ParticipantResponseType } from '../participant/participantTypes'; import type { TelemetryEvent } from './telemetryEvents'; import { @@ -192,7 +195,7 @@ export class TelemetryService { trackParticipantError(err: any, command: ParticipantResponseType): void { let errorCode: string | undefined; - let errorName: ParticipantErrorTypes; + let errorName: ParticipantErrorType; // Making the chat request might fail because // - model does not exist // - user consent not given @@ -209,13 +212,13 @@ export class TelemetryService { const message: string = err.message || err.toString(); if (message.includes('off_topic')) { - errorName = ParticipantErrorTypes.CHAT_MODEL_OFF_TOPIC; + errorName = PARTICIPANT_ERROR_TYPES.CHAT_MODEL_OFF_TOPIC; } else if (message.includes('Filtered by Responsible AI Service')) { - errorName = ParticipantErrorTypes.FILTERED; + errorName = PARTICIPANT_ERROR_TYPES.FILTERED; } else if (message.includes('Prompt failed validation')) { - errorName = ParticipantErrorTypes.INVALID_PROMPT; + errorName = PARTICIPANT_ERROR_TYPES.INVALID_PROMPT; } else { - errorName = ParticipantErrorTypes.OTHER; + errorName = PARTICIPANT_ERROR_TYPES.OTHER; } this.track( diff --git a/src/test/suite/connectionController.test.ts b/src/test/suite/connectionController.test.ts index 01eb20102..473f340b6 100644 --- a/src/test/suite/connectionController.test.ts +++ b/src/test/suite/connectionController.test.ts @@ -8,15 +8,18 @@ import { expect } from 'chai'; import ConnectionString from 'mongodb-connection-string-url'; import ConnectionController, { - ConnectionTypes, + CONNECTION_TYPES, getNotifyDeviceFlowForConnectionAttempt, } from '../../connectionController'; import formatError from '../../utils/formatError'; -import { StorageController, StorageVariables } from '../../storage'; import { - StorageLocation, - DefaultSavingLocations, - SecretStorageLocation, + StorageController, + STORAGE_VARIABLES, + STORAGE_LOCATIONS, +} from '../../storage'; +import { + DEFAULT_SAVING_LOCATIONS, + SECRET_STORAGE_LOCATIONS, } from '../../storage/storageController'; import { StatusView } from '../../views'; import { TelemetryService } from '../../telemetry'; @@ -279,8 +282,8 @@ suite('Connection Controller Test Suite', function () { ): void => { testConnectionController._connections[id] = { connectionOptions: { connectionString }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, name, id, ...otherOptions, @@ -557,8 +560,8 @@ suite('Connection Controller Test Suite', function () { connectionOptions: { connectionString: 'localhost:3000', }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; // Should persist as this is a saved connection. @@ -575,7 +578,10 @@ suite('Connection Controller Test Suite', function () { test('the connection model loads both global and workspace stored connection models', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); @@ -586,7 +592,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -614,14 +620,17 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.loadSavedConnections(); await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(globalStoreConnections)).to.have.lengthOf(1); @@ -633,7 +642,7 @@ suite('Connection Controller Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, ); expect(workspaceStoreConnections).to.be.undefined; @@ -645,15 +654,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -665,8 +674,8 @@ suite('Connection Controller Test Suite', function () { ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(globalStoreConnections).to.be.undefined; @@ -678,8 +687,8 @@ suite('Connection Controller Test Suite', function () { id: '25', name: 'tester', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }, }; @@ -696,15 +705,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -758,7 +767,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations['Session Only'], + DEFAULT_SAVING_LOCATIONS['Session Only'], ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -766,15 +775,15 @@ suite('Connection Controller Test Suite', function () { const objectString = JSON.stringify(undefined); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(JSON.stringify(globalStoreConnections)).to.equal(objectString); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(JSON.stringify(workspaceStoreConnections)).to.equal(objectString); @@ -819,15 +828,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -839,8 +848,8 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.removeSavedConnection(connectionId); const postWorkspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(postWorkspaceStoreConnections)).to.have.lengthOf(0); @@ -850,14 +859,17 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.loadSavedConnections(); await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(globalStoreConnections)).to.have.lengthOf(1); @@ -867,8 +879,8 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.removeSavedConnection(connectionId); const postGlobalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(postGlobalStoreConnections)).to.have.lengthOf(0); @@ -895,15 +907,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -943,15 +955,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -1019,7 +1031,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -1089,8 +1101,8 @@ suite('Connection Controller Test Suite', function () { id, name: `test${i}`, connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; } @@ -1151,8 +1163,8 @@ suite('Connection Controller Test Suite', function () { id: connectionId, name: 'asdfasdg', connectionOptions: { connectionString: testDatabaseURI2WithTimeout }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; void testConnectionController.connectWithConnectionId(connectionId); @@ -1175,8 +1187,8 @@ suite('Connection Controller Test Suite', function () { id: connectionId, name: 'asdfasdg', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; sandbox.replace( @@ -1206,8 +1218,8 @@ suite('Connection Controller Test Suite', function () { const connectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: StorageLocation.GLOBAL, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.GLOBAL, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://lena:secrer@localhost:27017/?readPreference=primary&ssl=false', @@ -1307,7 +1319,7 @@ suite('Connection Controller Test Suite', function () { expect( savedConnections.every( ({ secretStorageLocation }) => - secretStorageLocation === SecretStorageLocation.SecretStorage, + secretStorageLocation === SECRET_STORAGE_LOCATIONS.SecretStorage, ), ).to.be.true; @@ -1359,7 +1371,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-4', name: 'localhost:27089', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.SecretStorage, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27080/?readPreference=primary&ssl=false', @@ -1367,8 +1379,8 @@ suite('Connection Controller Test Suite', function () { }; testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === StorageLocation.WORKSPACE || - key === StorageVariables.WORKSPACE_SAVED_CONNECTIONS + storage === STORAGE_LOCATIONS.WORKSPACE || + key === STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS ) { return {}; } @@ -1378,7 +1390,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-1', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.Keytar, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.Keytar, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -1388,7 +1400,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-2', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.KeytarSecondAttempt, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.KeytarSecondAttempt, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -1422,8 +1434,8 @@ suite('Connection Controller Test Suite', function () { test.skip('should track SAVED_CONNECTIONS_LOADED event on load of saved connections', async () => { testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === StorageLocation.WORKSPACE || - key === StorageVariables.WORKSPACE_SAVED_CONNECTIONS + storage === STORAGE_LOCATIONS.WORKSPACE || + key === STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS ) { return {}; } @@ -1433,7 +1445,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-1', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.SecretStorage, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -1443,7 +1455,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-2', name: 'localhost:27088', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.SecretStorage, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27088/?readPreference=primary&ssl=false', @@ -1453,7 +1465,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-3', name: 'localhost:27088', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.Keytar, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.Keytar, connectionOptions: { connectionString: 'mongodb://localhost:27088/?readPreference=primary&ssl=false', @@ -1463,7 +1475,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-4', name: 'localhost:27088', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.KeytarSecondAttempt, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.KeytarSecondAttempt, connectionOptions: { connectionString: 'mongodb://localhost:27088/?readPreference=primary&ssl=false', @@ -1567,14 +1579,14 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Global, + DEFAULT_SAVING_LOCATIONS.Global, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI_USER, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, ); expect(workspaceStoreConnections).to.not.be.empty; @@ -1697,7 +1709,7 @@ suite('Connection Controller Test Suite', function () { }); expect(fakeConnect).to.have.been.calledWith( connections[0].id, - ConnectionTypes.CONNECTION_ID, + CONNECTION_TYPES.CONNECTION_ID, ); connections = testConnectionController.getSavedConnections(); expect(connections).to.have.lengthOf(1); diff --git a/src/test/suite/editors/collectionDocumentsProvider.test.ts b/src/test/suite/editors/collectionDocumentsProvider.test.ts index a4a2e0d03..5ce610b7a 100644 --- a/src/test/suite/editors/collectionDocumentsProvider.test.ts +++ b/src/test/suite/editors/collectionDocumentsProvider.test.ts @@ -3,8 +3,7 @@ import assert from 'assert'; import { beforeEach, afterEach } from 'mocha'; import sinon from 'sinon'; import type { DataService } from 'mongodb-data-service'; - -import { DocumentSource } from '../../../documentSource'; +import { DOCUMENT_SOURCE } from '../../../documentSource'; import CollectionDocumentsOperationsStore from '../../../editors/collectionDocumentsOperationsStore'; import CollectionDocumentsProvider, { VIEW_COLLECTION_SCHEME, @@ -14,8 +13,8 @@ import EditDocumentCodeLensProvider from '../../../editors/editDocumentCodeLensP import { StatusView } from '../../../views'; import { StorageController } from '../../../storage'; import { - SecretStorageLocation, - StorageLocation, + SECRET_STORAGE_LOCATIONS, + STORAGE_LOCATIONS, } from '../../../storage/storageController'; import { TelemetryService } from '../../../telemetry'; import { TEST_DATABASE_URI } from '../dbTestHelper'; @@ -288,7 +287,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!firstCollectionFirstCommandArguments); assert( firstCollectionFirstCommandArguments[0].source === - DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, ); assert( firstCollectionFirstCommandArguments[0].namespace === @@ -358,7 +357,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!secondCollectionFirstCommandArguments); assert( secondCollectionFirstCommandArguments[0].source === - DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, ); assert( secondCollectionFirstCommandArguments[0].namespace === @@ -419,15 +418,15 @@ suite('Collection Documents Provider Test Suite', () => { id: firstConnectionId, name: 'localhost', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }, [secondConnectionId]: { id: secondConnectionId, name: 'compass', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }, }; @@ -477,7 +476,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!firstCollectionFirstCommandArguments); assert( firstCollectionFirstCommandArguments[0].source === - DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, ); assert( firstCollectionFirstCommandArguments[0].namespace === @@ -552,7 +551,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!secondCollectionFirstCommandArguments); assert( secondCollectionFirstCommandArguments[0].source === - DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, ); assert( secondCollectionFirstCommandArguments[0].namespace === diff --git a/src/test/suite/editors/editDocumentCodeLensProvider.test.ts b/src/test/suite/editors/editDocumentCodeLensProvider.test.ts index b82b313c4..0645a5f4f 100644 --- a/src/test/suite/editors/editDocumentCodeLensProvider.test.ts +++ b/src/test/suite/editors/editDocumentCodeLensProvider.test.ts @@ -6,7 +6,7 @@ import sinon from 'sinon'; import util from 'util'; import ConnectionController from '../../../connectionController'; -import { DocumentSource } from '../../../documentSource'; +import { DOCUMENT_SOURCE } from '../../../documentSource'; import EditDocumentCodeLensProvider from '../../../editors/editDocumentCodeLensProvider'; import { mockTextEditor } from '../stubs'; import { StatusView } from '../../../views'; @@ -56,7 +56,7 @@ suite('Edit Document Code Lens Provider Test Suite', () => { }, ], namespace: 'db.coll', - source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND, }; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); @@ -90,7 +90,7 @@ suite('Edit Document Code Lens Provider Test Suite', () => { name: 'test name', }, namespace: 'db.coll', - source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND, }; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); @@ -99,8 +99,9 @@ suite('Edit Document Code Lens Provider Test Suite', () => { 'getActiveConnectionId', fakeActiveConnectionId, ); - const result = - testCodeLensProvider._updateCodeLensesForDocument(playgroundResult); + const result = testCodeLensProvider._updateCodeLensesForDocument( + playgroundResult as any, + ); assert(!!result); const codeLensesInfo = result[0]; diff --git a/src/test/suite/editors/mongoDBDocumentService.test.ts b/src/test/suite/editors/mongoDBDocumentService.test.ts index 5dd1e47cd..3ed87a982 100644 --- a/src/test/suite/editors/mongoDBDocumentService.test.ts +++ b/src/test/suite/editors/mongoDBDocumentService.test.ts @@ -5,7 +5,7 @@ import { EJSON } from 'bson'; import sinon from 'sinon'; import ConnectionController from '../../../connectionController'; -import { DocumentSource } from '../../../documentSource'; +import { DOCUMENT_SOURCE } from '../../../documentSource'; import formatError from '../../../utils/formatError'; import MongoDBDocumentService from '../../../editors/mongoDBDocumentService'; @@ -52,7 +52,7 @@ suite('MongoDB Document Service Test Suite', () => { const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const document: { _id: string; price?: number } = { _id: '123' }; const newDocument = { _id: '123', price: 5000 }; - const source = DocumentSource.DOCUMENT_SOURCE_TREEVIEW; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); sandbox.replace( @@ -103,7 +103,7 @@ suite('MongoDB Document Service Test Suite', () => { }, }, }; - const source = DocumentSource.DOCUMENT_SOURCE_TREEVIEW; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); sandbox.replace( @@ -144,7 +144,7 @@ suite('MongoDB Document Service Test Suite', () => { const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const line = 1; const documents = [{ _id: '123' }]; - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; const fakeGetActiveDataService = sandbox.fake.returns({ find: () => { @@ -194,7 +194,7 @@ suite('MongoDB Document Service Test Suite', () => { }, }, ]; - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; const fakeGetActiveDataService = sandbox.fake.returns({ find: () => { @@ -236,7 +236,7 @@ suite('MongoDB Document Service Test Suite', () => { const connectionId = 'tasty_sandwhich'; const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const newDocument = { _id: '123', price: 5000 }; - const source = DocumentSource.DOCUMENT_SOURCE_TREEVIEW; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; const fakeActiveConnectionId = sandbox.fake.returns(null); sandbox.replace( @@ -273,7 +273,7 @@ suite('MongoDB Document Service Test Suite', () => { const connectionId = 'tasty_sandwhich'; const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const newDocument = { _id: '123', price: 5000 }; - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; const fakeActiveConnectionId = sandbox.fake.returns('berlin.coctails'); sandbox.replace( @@ -310,7 +310,7 @@ suite('MongoDB Document Service Test Suite', () => { const connectionId = '123'; const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const line = 1; - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; const fakeGetActiveConnectionId = sandbox.fake.returns('345'); sandbox.replace( diff --git a/src/test/suite/explorer/collectionTreeItem.test.ts b/src/test/suite/explorer/collectionTreeItem.test.ts index b90d5caa8..cade03be9 100644 --- a/src/test/suite/explorer/collectionTreeItem.test.ts +++ b/src/test/suite/explorer/collectionTreeItem.test.ts @@ -3,7 +3,7 @@ import type { DataService } from 'mongodb-data-service'; import CollectionTreeItem from '../../../explorer/collectionTreeItem'; import type { CollectionDetailsType } from '../../../explorer/collectionTreeItem'; -import { CollectionTypes } from '../../../explorer/documentListTreeItem'; +import { COLLECTION_TYPES } from '../../../explorer/documentListTreeItem'; import { ext } from '../../../extensionConstants'; import { ExtensionContextStub, DataServiceStub } from '../stubs'; @@ -16,7 +16,7 @@ function getTestCollectionTreeItem( return new CollectionTreeItem({ collection: { name: 'testColName', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, databaseName: 'testDbName', dataService: {} as DataService, @@ -81,7 +81,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionViewTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: CollectionTypes.view, + type: COLLECTION_TYPES.view, } as unknown as CollectionDetailsType, }); @@ -98,7 +98,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, }); const collectionIconPath = testCollectionCollectionTreeItem.iconPath; @@ -120,7 +120,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionTimeSeriesTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: CollectionTypes.timeseries, + type: COLLECTION_TYPES.timeseries, } as unknown as CollectionDetailsType, }); const viewIconPath = testCollectionTimeSeriesTreeItem.iconPath; @@ -136,7 +136,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, }); const collectionIconPath = testCollectionCollectionTreeItem.iconPath; diff --git a/src/test/suite/explorer/documentListTreeItem.test.ts b/src/test/suite/explorer/documentListTreeItem.test.ts index f60e6396f..168ec31e1 100644 --- a/src/test/suite/explorer/documentListTreeItem.test.ts +++ b/src/test/suite/explorer/documentListTreeItem.test.ts @@ -6,7 +6,7 @@ import type { DataService } from 'mongodb-data-service'; const { contributes } = require('../../../../package.json'); import DocumentListTreeItem, { - CollectionTypes, + COLLECTION_TYPES, formatDocCount, MAX_DOCUMENTS_VISIBLE, } from '../../../explorer/documentListTreeItem'; @@ -21,7 +21,7 @@ function getTestDocumentListTreeItem( return new DocumentListTreeItem({ collectionName: 'collectionName', databaseName: 'mock_db_name', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, dataService: dataServiceStub as unknown as DataService, isExpanded: false, maxDocumentsToShow: MAX_DOCUMENTS_VISIBLE, @@ -82,7 +82,7 @@ suite('DocumentListTreeItem Test Suite', () => { test('a "view" type of document list does not show a dropdown', () => { const testDocumentListTreeItem = getTestDocumentListTreeItem({ - type: CollectionTypes.view, + type: COLLECTION_TYPES.view, }); assert.strictEqual( @@ -181,7 +181,7 @@ suite('DocumentListTreeItem Test Suite', () => { test('it shows a documents icon', () => { const testCollectionViewTreeItem = getTestDocumentListTreeItem({ collectionName: 'mock_collection_name_4', - type: CollectionTypes.view, + type: COLLECTION_TYPES.view, }); const viewIconPath = testCollectionViewTreeItem.iconPath; @@ -192,7 +192,7 @@ suite('DocumentListTreeItem Test Suite', () => { const testDocumentListTreeItem = getTestDocumentListTreeItem({ collectionName: 'mock_collection_name_4', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, }); const collectionIconPath = testDocumentListTreeItem.iconPath; diff --git a/src/test/suite/explorer/explorerController.test.ts b/src/test/suite/explorer/explorerController.test.ts index 4f6a516fa..82e5b44f4 100644 --- a/src/test/suite/explorer/explorerController.test.ts +++ b/src/test/suite/explorer/explorerController.test.ts @@ -6,9 +6,9 @@ import { connect, createConnectionAttempt } from 'mongodb-data-service'; import { mongoLogId } from 'mongodb-log-writer'; import { - DefaultSavingLocations, - SecretStorageLocation, - StorageLocation, + DEFAULT_SAVING_LOCATIONS, + SECRET_STORAGE_LOCATIONS, + STORAGE_LOCATIONS, } from '../../../storage/storageController'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { TEST_DATABASE_URI } from '../dbTestHelper'; @@ -31,7 +31,7 @@ suite('Explorer Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations['Session Only'], + DEFAULT_SAVING_LOCATIONS['Session Only'], ); sandbox.stub(vscode.window, 'showInformationMessage'); sandbox.stub(vscode.window, 'showErrorMessage'); @@ -47,7 +47,7 @@ suite('Explorer Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); // Reset our connections. await mdbTestExtension.testExtensionController._connectionController.disconnect(); @@ -68,8 +68,8 @@ suite('Explorer Controller Test Suite', function () { id: 'testConnectionId', connectionOptions: { connectionString: 'mongodb://localhost' }, name: 'testConnectionName', - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }, }; testConnectionController._connectionAttempt = createConnectionAttempt({ @@ -213,8 +213,8 @@ suite('Explorer Controller Test Suite', function () { testConnectionController._connections[connectionId].connectionOptions, name: 'aaa', id: 'aaa', - storageLocation: StorageLocation.WORKSPACE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.WORKSPACE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; testConnectionController._connections.zzz = { @@ -222,8 +222,8 @@ suite('Explorer Controller Test Suite', function () { testConnectionController._connections[connectionId].connectionOptions, name: 'zzz', id: 'zzz', - storageLocation: StorageLocation.WORKSPACE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.WORKSPACE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; const connectionsItems = await treeController.getChildren(); diff --git a/src/test/suite/explorer/indexTreeItem.test.ts b/src/test/suite/explorer/indexTreeItem.test.ts index c440ca33e..2f834cecb 100644 --- a/src/test/suite/explorer/indexTreeItem.test.ts +++ b/src/test/suite/explorer/indexTreeItem.test.ts @@ -2,7 +2,7 @@ import assert from 'assert'; import IndexTreeItem, { IndexFieldTreeItem, - IndexKeyType, + INDEX_KEY_TYPES, } from '../../../explorer/indexTreeItem'; import type * as vscode from 'vscode'; @@ -33,7 +33,7 @@ suite('IndexTreeItem Test Suite', () => { test('it has an icon for the index type', () => { const testIndexFieldTreeItem = new IndexFieldTreeItem({ indexKey: 'locations', - indexKeyType: IndexKeyType.GEOSPHERE, + indexKeyType: INDEX_KEY_TYPES.GEOSPHERE, }); const iconPath = testIndexFieldTreeItem.iconPath as { diff --git a/src/test/suite/explorer/schemaTreeItem.test.ts b/src/test/suite/explorer/schemaTreeItem.test.ts index 66e964b75..5626f5c04 100644 --- a/src/test/suite/explorer/schemaTreeItem.test.ts +++ b/src/test/suite/explorer/schemaTreeItem.test.ts @@ -188,10 +188,10 @@ suite('SchemaTreeItem Test Suite', function () { "Unable to parse schema: Cannot use 'in' operator to search for 'Symbol(Symbol.iterator)' in invalid schema to parse"; assert.strictEqual( - (error).message, + (error as Error).message, expectedMessage, `Expected error message to be "${expectedMessage}" found "${ - (error).message + (error as Error).message }"`, ); } diff --git a/src/test/suite/language/mongoDBService.test.ts b/src/test/suite/language/mongoDBService.test.ts index 95339be6d..a44a8c47b 100644 --- a/src/test/suite/language/mongoDBService.test.ts +++ b/src/test/suite/language/mongoDBService.test.ts @@ -22,7 +22,7 @@ import MongoDBService, { import { mdbTestExtension } from '../stubbableMdbExtension'; import { StreamStub } from '../stubs'; import DIAGNOSTIC_CODES from '../../../language/diagnosticCodes'; -import { ServerCommands } from '../../../language/serverCommands'; +import { SERVER_COMMANDS } from '../../../language/serverCommands'; import LINKS from '../../../utils/links'; import Sinon from 'sinon'; @@ -2965,7 +2965,7 @@ suite('MongoDBService Test Suite', () => { consoleOutputs = []; Sinon.stub(connection, 'sendNotification') - .withArgs(ServerCommands.SHOW_CONSOLE_OUTPUT) + .withArgs(SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT) .callsFake((_, params) => Promise.resolve(void consoleOutputs.push(...params)), ); diff --git a/src/test/suite/mcp/mcpConnectionErrorHandler.test.ts b/src/test/suite/mcp/mcpConnectionErrorHandler.test.ts index 95ff3ac57..94ff0d5ea 100644 --- a/src/test/suite/mcp/mcpConnectionErrorHandler.test.ts +++ b/src/test/suite/mcp/mcpConnectionErrorHandler.test.ts @@ -12,14 +12,15 @@ import type { } from 'mongodb-mcp-server'; import { ErrorCodes } from 'mongodb-mcp-server'; +type MongoDBErrorCode = + | typeof ErrorCodes.NotConnectedToMongoDB + | typeof ErrorCodes.MisconfiguredConnectionString; + class MongoDBError extends Error { - constructor( - public code: - | ErrorCodes.NotConnectedToMongoDB - | ErrorCodes.MisconfiguredConnectionString, - message: string, - ) { + code: MongoDBErrorCode; + constructor(code: MongoDBErrorCode, message: string) { super(message); + this.code = code; } } diff --git a/src/test/suite/mdbExtensionController.test.ts b/src/test/suite/mdbExtensionController.test.ts index bfdf2449e..bef475668 100644 --- a/src/test/suite/mdbExtensionController.test.ts +++ b/src/test/suite/mdbExtensionController.test.ts @@ -9,7 +9,6 @@ import type { Document, Filter } from 'mongodb'; import { CollectionTreeItem, - CollectionTypes, ConnectionTreeItem, DatabaseTreeItem, DocumentTreeItem, @@ -22,14 +21,15 @@ import IndexListTreeItem from '../../explorer/indexListTreeItem'; import { mdbTestExtension } from './stubbableMdbExtension'; import { mockTextEditor } from './stubs'; import { - SecretStorageLocation, - StorageLocation, - StorageVariables, + STORAGE_LOCATIONS, + SECRET_STORAGE_LOCATIONS, + STORAGE_VARIABLES, } from '../../storage/storageController'; import { VIEW_COLLECTION_SCHEME } from '../../editors/collectionDocumentsProvider'; import type { CollectionDetailsType } from '../../explorer/collectionTreeItem'; import { expect } from 'chai'; import { DeepLinkTelemetryEvent } from '../../telemetry'; +import { COLLECTION_TYPES } from '../../explorer/documentListTreeItem'; const testDatabaseURI = 'mongodb://localhost:27088'; @@ -55,7 +55,7 @@ function getTestCollectionTreeItem( return new CollectionTreeItem({ collection: { name: 'testColName', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, databaseName: 'testDbName', dataService: {} as DataService, @@ -719,7 +719,7 @@ suite('MDBExtensionController Test Suite', function () { const testCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'doesntExistColName', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, dataService: testConnectionController.getActiveDataService() ?? undefined, @@ -750,7 +750,7 @@ suite('MDBExtensionController Test Suite', function () { const testCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'orange', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, }); const inputBoxResolvesStub = sandbox.stub(); @@ -859,8 +859,8 @@ suite('MDBExtensionController Test Suite', function () { id: 'blueBerryPancakesAndTheSmellOfBacon', connectionOptions: { connectionString: 'mongodb://localhost' }, name: 'NAAAME', - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; const testTreeItem = getTestConnectionTreeItem({ @@ -890,8 +890,8 @@ suite('MDBExtensionController Test Suite', function () { id: 'blueBerryPancakesAndTheSmellOfBacon', name: 'NAAAME', connectionOptions: { connectionString: 'mongodb://localhost' }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; const testTreeItem = getTestConnectionTreeItem({ @@ -1312,7 +1312,7 @@ suite('MDBExtensionController Test Suite', function () { const collectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'pineapple', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, databaseName: 'plants', }); @@ -1645,7 +1645,7 @@ suite('MDBExtensionController Test Suite', function () { assert(fakeUpdate.called); assert.strictEqual( fakeUpdate.firstCall.args[0], - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, ); assert.strictEqual( fakeUpdate.firstCall.args[0], @@ -1690,7 +1690,7 @@ suite('MDBExtensionController Test Suite', function () { assert(fakeUpdate.called); assert.strictEqual( fakeUpdate.firstCall.args[0], - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, ); assert.strictEqual( fakeUpdate.firstCall.args[0], diff --git a/src/test/suite/participant/participant.test.ts b/src/test/suite/participant/participant.test.ts index 3ecafbfa5..d7bced565 100644 --- a/src/test/suite/participant/participant.test.ts +++ b/src/test/suite/participant/participant.test.ts @@ -23,8 +23,8 @@ import { TEST_DATABASE_URI } from '../dbTestHelper'; import type { ChatResult } from '../../../participant/constants'; import { CHAT_PARTICIPANT_ID } from '../../../participant/constants'; import { - SecretStorageLocation, - StorageLocation, + SECRET_STORAGE_LOCATIONS, + STORAGE_LOCATIONS, } from '../../../storage/storageController'; import type { LoadedConnection } from '../../../storage/connectionStorage'; import { ChatMetadataStore } from '../../../participant/chatMetadata'; @@ -34,7 +34,7 @@ import { Prompts } from '../../../participant/prompts'; import { createMarkdownLink } from '../../../participant/markdown'; import EXTENSION_COMMANDS from '../../../commands'; import { getContentLength } from '../../../participant/prompts/promptBase'; -import { ParticipantErrorTypes } from '../../../participant/participantErrorTypes'; +import { PARTICIPANT_ERROR_TYPES } from '../../../participant/participantErrorTypes'; import * as model from '../../../participant/model'; import { createChatRequestTurn, @@ -47,8 +47,8 @@ import type { ParticipantRequestType, SendMessageToParticipantOptions, } from '../../../participant/participantTypes'; -import { DocumentSource } from '../../../documentSource'; import { TelemetryService } from '../../../telemetry'; +import { DOCUMENT_SOURCE } from '../../../documentSource'; // The Copilot's model in not available in tests, // therefore we need to mock its methods and returning values. @@ -57,8 +57,8 @@ const MAX_TOTAL_PROMPT_LENGTH_MOCK = 16000; const loadedConnection = { id: 'id', name: 'localhost', - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost' }, }; @@ -1942,7 +1942,7 @@ Schema: message: `I want to ask questions about the \`${mockDatabaseItem.databaseName}\` database.`, isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, source_details: 'database', }, }, @@ -1973,7 +1973,7 @@ Schema: message: `I want to ask questions about the \`${mockCollectionItem.databaseName}\` database's \`${mockCollectionItem.collectionName}\` collection.`, isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, source_details: 'collection', }, }, @@ -2638,7 +2638,7 @@ Schema: createChatResponseTurn('/query', undefined, { result: { errorDetails: { - message: ParticipantErrorTypes.FILTERED, + message: PARTICIPANT_ERROR_TYPES.FILTERED, }, metadata: {}, }, diff --git a/src/test/suite/storage/connectionStorage.test.ts b/src/test/suite/storage/connectionStorage.test.ts index d2338b449..9b5b49385 100644 --- a/src/test/suite/storage/connectionStorage.test.ts +++ b/src/test/suite/storage/connectionStorage.test.ts @@ -3,11 +3,14 @@ import * as vscode from 'vscode'; import { afterEach, beforeEach } from 'mocha'; import { expect } from 'chai'; -import { StorageController, StorageVariables } from '../../../storage'; import { - StorageLocation, - DefaultSavingLocations, - SecretStorageLocation, + StorageController, + STORAGE_VARIABLES, + STORAGE_LOCATIONS, +} from '../../../storage'; +import { + DEFAULT_SAVING_LOCATIONS, + SECRET_STORAGE_LOCATIONS, } from '../../../storage/storageController'; import { ExtensionContextStub } from '../stubs'; import { @@ -66,7 +69,10 @@ suite('Connection Storage Test Suite', function () { test('it loads both global and workspace stored connections', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), @@ -78,7 +84,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionStorage.saveConnection( @@ -104,15 +110,18 @@ suite('Connection Storage Test Suite', function () { test('when a connection is added it is saved to the global storage', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(globalStoreConnections).length).to.equal(1); @@ -124,7 +133,7 @@ suite('Connection Storage Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, ); expect(workspaceStoreConnections).to.equal(undefined); @@ -135,15 +144,15 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections).length).to.equal(1); @@ -155,8 +164,8 @@ suite('Connection Storage Test Suite', function () { ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(globalStoreConnections).to.equal(undefined); @@ -168,7 +177,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations['Session Only'], + DEFAULT_SAVING_LOCATIONS['Session Only'], ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), @@ -176,15 +185,15 @@ suite('Connection Storage Test Suite', function () { const objectString = JSON.stringify(undefined); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(JSON.stringify(globalStoreConnections)).to.equal(objectString); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(JSON.stringify(workspaceStoreConnections)).to.equal(objectString); @@ -195,7 +204,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); const connectionId = 'pie'; await testConnectionStorage.saveConnection( @@ -203,8 +212,8 @@ suite('Connection Storage Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections).length).to.equal(1); @@ -212,8 +221,8 @@ suite('Connection Storage Test Suite', function () { await testConnectionStorage.removeConnection(connectionId); const postWorkspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(postWorkspaceStoreConnections).length).to.equal(0); }); @@ -221,15 +230,18 @@ suite('Connection Storage Test Suite', function () { test('when a connection is removed it is also removed from global storage', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); const connectionId = 'pineapple'; await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, connectionId), ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(globalStoreConnections).length).to.equal(1); @@ -237,8 +249,8 @@ suite('Connection Storage Test Suite', function () { await testConnectionStorage.removeConnection(connectionId); const postGlobalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(postGlobalStoreConnections).length).to.equal(0); @@ -263,7 +275,7 @@ suite('Connection Storage Test Suite', function () { const oldSavedConnectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: StorageLocation.GLOBAL, + storageLocation: STORAGE_LOCATIONS.GLOBAL, connectionModel: { _id: '4', isFavorite: false, @@ -295,8 +307,8 @@ suite('Connection Storage Test Suite', function () { const connectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: StorageLocation.GLOBAL, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.GLOBAL, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -475,7 +487,7 @@ suite('Connection Storage Test Suite', function () { expect( savedConnections.every( ({ secretStorageLocation }) => - secretStorageLocation === SecretStorageLocation.SecretStorage, + secretStorageLocation === SECRET_STORAGE_LOCATIONS.SecretStorage, ), ).to.equal(true); @@ -491,7 +503,7 @@ suite('Connection Storage Test Suite', function () { id: 'random-connection-4', name: 'localhost:27089', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.SecretStorage, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27080/?readPreference=primary&ssl=false', @@ -499,8 +511,8 @@ suite('Connection Storage Test Suite', function () { }; testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === StorageLocation.WORKSPACE || - key === StorageVariables.WORKSPACE_SAVED_CONNECTIONS + storage === STORAGE_LOCATIONS.WORKSPACE || + key === STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS ) { return {}; } @@ -510,7 +522,7 @@ suite('Connection Storage Test Suite', function () { id: 'random-connection-1', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.Keytar, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.Keytar, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -520,7 +532,7 @@ suite('Connection Storage Test Suite', function () { id: 'random-connection-2', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.KeytarSecondAttempt, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.KeytarSecondAttempt, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -552,7 +564,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionStorage.saveConnection( diff --git a/src/test/suite/storage/storageController.test.ts b/src/test/suite/storage/storageController.test.ts index 6d0c4f20c..1cb621e15 100644 --- a/src/test/suite/storage/storageController.test.ts +++ b/src/test/suite/storage/storageController.test.ts @@ -1,8 +1,8 @@ import assert from 'assert'; import StorageController, { - StorageVariables, - StorageLocation, + STORAGE_VARIABLES, + STORAGE_LOCATIONS, } from '../../../storage/storageController'; import { ExtensionContextStub } from '../stubs'; @@ -10,14 +10,14 @@ suite('Storage Controller Test Suite', () => { test('getting a variable gets it from the global context store', () => { const extensionContextStub = new ExtensionContextStub(); extensionContextStub._globalState = { - [StorageVariables.GLOBAL_SAVED_CONNECTIONS]: { + [STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS]: { collOne: { name: 'this_gonna_get_saved' }, }, }; const testStorageController = new StorageController(extensionContextStub); const testVal = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); assert( testVal.collOne.name === 'this_gonna_get_saved', @@ -28,14 +28,14 @@ suite('Storage Controller Test Suite', () => { test('getting a variable from the workspace state gets it from the workspace context store', () => { const extensionContextStub = new ExtensionContextStub(); extensionContextStub._workspaceState = { - [StorageVariables.WORKSPACE_SAVED_CONNECTIONS]: { + [STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS]: { collTwo: { name: 'i_cant_believe_its_gonna_save_this' }, }, }; const testStorageController = new StorageController(extensionContextStub); const testVal = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); assert( testVal.collTwo.name === 'i_cant_believe_its_gonna_save_this', @@ -51,7 +51,7 @@ suite('Storage Controller Test Suite', () => { test('getUserIdentity adds anonymousId to the global storage and returns it to telemetry', () => { const userIdentity = testStorageController.getUserIdentity(); const anonymousId = testStorageController.get( - StorageVariables.GLOBAL_ANONYMOUS_ID, + STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID, ); assert.deepStrictEqual(userIdentity, { anonymousId }); }); diff --git a/src/test/suite/stubbableMdbExtension.ts b/src/test/suite/stubbableMdbExtension.ts index ce6dd7161..a3143e901 100644 --- a/src/test/suite/stubbableMdbExtension.ts +++ b/src/test/suite/stubbableMdbExtension.ts @@ -1,12 +1,7 @@ import type MDBExtensionController from '../../mdbExtensionController'; import type { ExtensionContextStub } from './stubs'; -// This interface has the instance of the extension we use for testing. -// This should be used for integration tests and higher level extension -// command testing that cannot be done on a more isolated level. - -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace mdbTestExtension { - export let extensionContextStub: ExtensionContextStub; - export let testExtensionController: MDBExtensionController; -} +export const mdbTestExtension = {} as { + extensionContextStub: ExtensionContextStub; + testExtensionController: MDBExtensionController; +}; diff --git a/src/test/suite/telemetry/connectionTelemetry.test.ts b/src/test/suite/telemetry/connectionTelemetry.test.ts index 7f61ea761..0ac623baa 100644 --- a/src/test/suite/telemetry/connectionTelemetry.test.ts +++ b/src/test/suite/telemetry/connectionTelemetry.test.ts @@ -4,7 +4,7 @@ import { expect } from 'chai'; import sinon from 'sinon'; import type { DataService } from 'mongodb-data-service'; -import { ConnectionTypes } from '../../../connectionController'; +import { CONNECTION_TYPES } from '../../../connectionController'; import { getConnectionTelemetryProperties } from '../../../telemetry/connectionTelemetry'; import { TEST_DATABASE_URI } from '../dbTestHelper'; @@ -62,7 +62,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_public_cloud).to.equal(true); expect(instanceTelemetry.public_cloud_name).to.equal('Azure'); @@ -95,7 +95,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_public_cloud).to.equal(false); }); @@ -130,7 +130,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_atlas).to.equal(false); expect(instanceTelemetry.atlas_hostname).to.equal(null); @@ -168,7 +168,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_atlas).to.equal(true); expect(instanceTelemetry.atlas_hostname).to.equal( @@ -208,7 +208,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_atlas).to.equal(true); expect(instanceTelemetry.atlas_hostname).to.equal( @@ -247,7 +247,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_localhost).to.equal(true); }); @@ -281,7 +281,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.is_localhost).to.equal(false); expect(instanceTelemetry.is_atlas_url).to.equal(false); @@ -316,7 +316,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_used_connect_screen).to.equal(true); expect(instanceTelemetry.is_used_command_palette).to.equal(false); @@ -350,7 +350,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.is_used_connect_screen).to.equal(false); expect(instanceTelemetry.is_used_command_palette).to.equal(true); @@ -384,7 +384,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_ID, + CONNECTION_TYPES.CONNECTION_ID, ); expect(instanceTelemetry.is_used_connect_screen).to.equal(false); expect(instanceTelemetry.is_used_command_palette).to.equal(false); @@ -420,7 +420,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.is_localhost).to.equal(false); }); @@ -452,7 +452,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.is_localhost).to.equal(true); }); @@ -490,7 +490,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.server_version).to.equal('4.3.9'); expect(instanceTelemetry.server_arch).to.equal('debian'); @@ -530,7 +530,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.server_version).to.equal('4.3.2'); expect(instanceTelemetry.server_arch).to.equal('darwin'); @@ -564,7 +564,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.auth_strategy).to.equal('DEFAULT'); }); @@ -596,7 +596,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.auth_strategy).to.equal('NONE'); }); @@ -630,7 +630,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.auth_strategy).to.equal('SCRAM-SHA-1'); }); @@ -655,7 +655,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { test('track new connection event fetches the connection instance information', async () => { const instanceTelemetry = await getConnectionTelemetryProperties( dataServ, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.is_localhost).to.equal(true); diff --git a/src/test/suite/telemetry/telemetryService.test.ts b/src/test/suite/telemetry/telemetryService.test.ts index 3cc74aa29..e5282ee7c 100644 --- a/src/test/suite/telemetry/telemetryService.test.ts +++ b/src/test/suite/telemetry/telemetryService.test.ts @@ -9,8 +9,7 @@ import sinon from 'sinon'; import type { SinonSpy } from 'sinon'; import sinonChai from 'sinon-chai'; -import { ConnectionTypes } from '../../../connectionController'; -import { DocumentSource } from '../../../documentSource'; +import { DOCUMENT_SOURCE } from '../../../documentSource'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { DatabaseTreeItem, DocumentTreeItem } from '../../../explorer'; import { DataServiceStub } from '../stubs'; @@ -25,6 +24,7 @@ import { SavedConnectionsLoadedTelemetryEvent, } from '../../../telemetry'; import type { SegmentProperties } from '../../../telemetry/telemetryService'; +import { CONNECTION_TYPES } from '../../../connectionController'; // eslint-disable-next-line @typescript-eslint/no-var-requires const { version } = require('../../../../package.json'); @@ -156,7 +156,7 @@ suite('Telemetry Controller Test Suite', () => { test('track new connection event when connecting via connection string', async () => { await testTelemetryService.trackNewConnection( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -177,7 +177,7 @@ suite('Telemetry Controller Test Suite', () => { test('track new connection event when connecting via connection form', async () => { await testTelemetryService.trackNewConnection( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -198,7 +198,7 @@ suite('Telemetry Controller Test Suite', () => { test('track new connection event when connecting via saved connection', async () => { await testTelemetryService.trackNewConnection( dataServiceStub, - ConnectionTypes.CONNECTION_ID, + CONNECTION_TYPES.CONNECTION_ID, ); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -217,7 +217,7 @@ suite('Telemetry Controller Test Suite', () => { }); test('track document saved form a tree-view event', () => { - const source = DocumentSource.DOCUMENT_SOURCE_TREEVIEW; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; testTelemetryService.track( new DocumentUpdatedTelemetryEvent(source, true), ); @@ -236,7 +236,7 @@ suite('Telemetry Controller Test Suite', () => { }); test('track document opened form playground results', () => { - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; testTelemetryService.track(new DocumentEditedTelemetryEvent(source)); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, diff --git a/src/utils/playground.ts b/src/utils/playground.ts index 4099d3794..2421f1b9a 100644 --- a/src/utils/playground.ts +++ b/src/utils/playground.ts @@ -8,7 +8,11 @@ import { createLogger } from '../logging'; const log = createLogger('playground utils'); export class FileStat implements vscode.FileStat { - constructor(private fsStat: fs.Stats) {} + private fsStat: fs.Stats; + + constructor(fsStat: fs.Stats) { + this.fsStat = fsStat; + } get type(): vscode.FileType { if (this.fsStat.isFile()) { diff --git a/src/views/webview-app/extension-app-message-constants.ts b/src/views/webview-app/extension-app-message-constants.ts index 80a197347..7e49d5cbb 100644 --- a/src/views/webview-app/extension-app-message-constants.ts +++ b/src/views/webview-app/extension-app-message-constants.ts @@ -1,13 +1,16 @@ import type { ConnectionOptions } from 'mongodb-data-service'; import type { FileChooserOptions } from './use-connection-form'; -export enum CONNECTION_STATUS { - LOADING = 'LOADING', // When the connection status has not yet been shared from the extension. - CONNECTED = 'CONNECTED', - CONNECTING = 'CONNECTING', - DISCONNECTING = 'DISCONNECTING', - DISCONNECTED = 'DISCONNECTED', -} +export const CONNECTION_STATUS = { + LOADING: 'LOADING', // When the connection status has not yet been shared from the extension. + CONNECTED: 'CONNECTED', + CONNECTING: 'CONNECTING', + DISCONNECTING: 'DISCONNECTING', + DISCONNECTED: 'DISCONNECTED', +} as const; + +export type ConnectionStatus = + (typeof CONNECTION_STATUS)[keyof typeof CONNECTION_STATUS]; export const VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID = 'VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID'; @@ -15,45 +18,45 @@ export const VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID = export const VSCODE_EXTENSION_OIDC_DEVICE_AUTH_ID = 'VSCODE_EXTENSION_OIDC_DEVICE_AUTH_ID'; -export enum MESSAGE_TYPES { - CONNECT = 'CONNECT', - CANCEL_CONNECT = 'CANCEL_CONNECT', - CONNECT_RESULT = 'CONNECT_RESULT', - CONNECTION_FORM_OPENED = 'CONNECTION_FORM_OPENED', - OPEN_FILE_CHOOSER = 'OPEN_FILE_CHOOSER', - OPEN_FILE_CHOOSER_RESULT = 'OPEN_FILE_CHOOSER_RESULT', - CONNECTION_STATUS_MESSAGE = 'CONNECTION_STATUS_MESSAGE', - OPEN_EDIT_CONNECTION = 'OPEN_EDIT_CONNECTION', - EDIT_CONNECTION_AND_CONNECT = 'EDIT_CONNECTION_AND_CONNECT', - EXTENSION_LINK_CLICKED = 'EXTENSION_LINK_CLICKED', - CREATE_NEW_PLAYGROUND = 'CREATE_NEW_PLAYGROUND', - GET_CONNECTION_STATUS = 'GET_CONNECTION_STATUS', - OPEN_CONNECTION_STRING_INPUT = 'OPEN_CONNECTION_STRING_INPUT', - OPEN_TRUSTED_LINK = 'OPEN_TRUSTED_LINK', - RENAME_ACTIVE_CONNECTION = 'RENAME_ACTIVE_CONNECTION', - THEME_CHANGED = 'THEME_CHANGED', -} +export const MESSAGE_TYPES = { + CONNECT: 'CONNECT', + CANCEL_CONNECT: 'CANCEL_CONNECT', + CONNECT_RESULT: 'CONNECT_RESULT', + CONNECTION_FORM_OPENED: 'CONNECTION_FORM_OPENED', + OPEN_FILE_CHOOSER: 'OPEN_FILE_CHOOSER', + OPEN_FILE_CHOOSER_RESULT: 'OPEN_FILE_CHOOSER_RESULT', + CONNECTION_STATUS_MESSAGE: 'CONNECTION_STATUS_MESSAGE', + OPEN_EDIT_CONNECTION: 'OPEN_EDIT_CONNECTION', + EDIT_CONNECTION_AND_CONNECT: 'EDIT_CONNECTION_AND_CONNECT', + EXTENSION_LINK_CLICKED: 'EXTENSION_LINK_CLICKED', + CREATE_NEW_PLAYGROUND: 'CREATE_NEW_PLAYGROUND', + GET_CONNECTION_STATUS: 'GET_CONNECTION_STATUS', + OPEN_CONNECTION_STRING_INPUT: 'OPEN_CONNECTION_STRING_INPUT', + OPEN_TRUSTED_LINK: 'OPEN_TRUSTED_LINK', + RENAME_ACTIVE_CONNECTION: 'RENAME_ACTIVE_CONNECTION', + THEME_CHANGED: 'THEME_CHANGED', +} as const; interface BasicWebviewMessage { command: string; } export interface CreateNewPlaygroundMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CREATE_NEW_PLAYGROUND; + command: typeof MESSAGE_TYPES.CREATE_NEW_PLAYGROUND; } export interface ConnectionFormOpenedMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECTION_FORM_OPENED; + command: typeof MESSAGE_TYPES.CONNECTION_FORM_OPENED; } export interface ConnectionStatusMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE; - connectionStatus: CONNECTION_STATUS; + command: typeof MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE; + connectionStatus: ConnectionStatus; activeConnectionName: string; } export interface OpenEditConnectionMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_EDIT_CONNECTION; + command: typeof MESSAGE_TYPES.OPEN_EDIT_CONNECTION; connection: { id: string; name: string; @@ -62,7 +65,7 @@ export interface OpenEditConnectionMessage extends BasicWebviewMessage { } export interface EditConnectionAndConnectMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT; + command: typeof MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT; connectionInfo: { id: string; connectionOptions: ConnectionOptions; @@ -70,13 +73,13 @@ export interface EditConnectionAndConnectMessage extends BasicWebviewMessage { } export interface OpenFileChooserMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_FILE_CHOOSER; + command: typeof MESSAGE_TYPES.OPEN_FILE_CHOOSER; fileChooserOptions: FileChooserOptions; requestId: string; } export interface ConnectMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECT; + command: typeof MESSAGE_TYPES.CONNECT; connectionInfo: { id: string; connectionOptions: ConnectionOptions; @@ -84,11 +87,11 @@ export interface ConnectMessage extends BasicWebviewMessage { } export interface CancelConnectMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CANCEL_CONNECT; + command: typeof MESSAGE_TYPES.CANCEL_CONNECT; } export interface ConnectResultsMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECT_RESULT; + command: typeof MESSAGE_TYPES.CONNECT_RESULT; connectionSuccess: boolean; connectionMessage: string; connectionId: string; @@ -99,36 +102,36 @@ export type FileChooserResult = | { canceled: false; filePath?: string }; export interface OpenFileChooserResultMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_FILE_CHOOSER_RESULT; + command: typeof MESSAGE_TYPES.OPEN_FILE_CHOOSER_RESULT; fileChooserResult: FileChooserResult; requestId: string; } export interface GetConnectionStatusMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.GET_CONNECTION_STATUS; + command: typeof MESSAGE_TYPES.GET_CONNECTION_STATUS; } export interface OpenConnectionStringInputMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT; + command: typeof MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT; } export interface LinkClickedMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED; + command: typeof MESSAGE_TYPES.EXTENSION_LINK_CLICKED; screen: string; linkId: string; } export interface OpenTrustedLinkMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_TRUSTED_LINK; + command: typeof MESSAGE_TYPES.OPEN_TRUSTED_LINK; linkTo: string; } export interface RenameConnectionMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION; + command: typeof MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION; } export interface ThemeChangedMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.THEME_CHANGED; + command: typeof MESSAGE_TYPES.THEME_CHANGED; darkMode: boolean; } diff --git a/src/views/webview-app/use-connection-form.ts b/src/views/webview-app/use-connection-form.ts index c36c40219..cd0bc746e 100644 --- a/src/views/webview-app/use-connection-form.ts +++ b/src/views/webview-app/use-connection-form.ts @@ -13,14 +13,17 @@ import { MESSAGE_TYPES } from './extension-app-message-constants'; import type { MessageFromExtensionToWebview } from './extension-app-message-constants'; import type { ElectronFileDialogOptions } from '@mongodb-js/compass-components'; -export enum FILE_CHOOSER_MODE { - OPEN = 'open', - SAVE = 'save', -} +export const FILE_CHOOSER_MODE = { + OPEN: 'open', + SAVE: 'save', +} as const; + +type FileChooserMode = + (typeof FILE_CHOOSER_MODE)[keyof typeof FILE_CHOOSER_MODE]; export type FileChooserOptions = { electronFileDialogOptions?: Partial; - mode: FILE_CHOOSER_MODE; + mode: FileChooserMode; }; type ConnectionInfo = { diff --git a/src/views/webview-app/use-connection-status.ts b/src/views/webview-app/use-connection-status.ts index e7cfe3b38..ab163de69 100644 --- a/src/views/webview-app/use-connection-status.ts +++ b/src/views/webview-app/use-connection-status.ts @@ -3,16 +3,17 @@ import { CONNECTION_STATUS, type MessageFromExtensionToWebview, MESSAGE_TYPES, + type ConnectionStatus, } from './extension-app-message-constants'; import vscode from './vscode-api'; const CONNECTION_STATUS_POLLING_FREQ_MS = 1000; const useConnectionStatus = (): { - connectionStatus: CONNECTION_STATUS; + connectionStatus: ConnectionStatus; connectionName: string; } => { - const [connectionStatus, setConnectionStatus] = useState( + const [connectionStatus, setConnectionStatus] = useState( CONNECTION_STATUS.LOADING, ); const [connectionName, setConnectionName] = useState(''); diff --git a/src/views/webviewController.ts b/src/views/webviewController.ts index 8c4d6f80d..a337f7980 100644 --- a/src/views/webviewController.ts +++ b/src/views/webviewController.ts @@ -4,7 +4,7 @@ import crypto from 'crypto'; import type { ConnectionOptions } from 'mongodb-data-service'; import type ConnectionController from '../connectionController'; -import { ConnectionTypes } from '../connectionController'; +import { CONNECTION_TYPES } from '../connectionController'; import { createLogger } from '../logging'; import EXTENSION_COMMANDS from '../commands'; import type { MessageFromWebviewToExtension } from './webview-app/extension-app-message-constants'; @@ -201,7 +201,7 @@ export default class WebviewController { : await this._connectionController.saveNewConnectionAndConnect({ connectionId: connection.id, connectionOptions: connection.connectionOptions, - connectionType: ConnectionTypes.CONNECTION_FORM, + connectionType: CONNECTION_TYPES.CONNECTION_FORM, }); try { diff --git a/tsconfig.json b/tsconfig.json index f5e24209f..420a6f039 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,7 +11,8 @@ "rootDir": "src", "esModuleInterop": true, "skipLibCheck": true, - "strict": true /* enable all strict type-checking options */ + "strict": true /* enable all strict type-checking options */, + "erasableSyntaxOnly": true /* Additional Checks */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ From d1b2b7a723ed6c9bc07761b97f0c945e3061e9bc Mon Sep 17 00:00:00 2001 From: gagik Date: Wed, 12 Nov 2025 15:09:02 +0100 Subject: [PATCH 3/5] chore: cleanup scripts --- package.json | 8 ++++---- scripts/check-vsix-size.ts | 2 ++ scripts/generate-constants.ts | 7 +++++-- scripts/precommit.ts | 2 +- scripts/update-grammar.ts | 2 ++ tsconfig.test.json | 10 ++++++++++ 6 files changed, 24 insertions(+), 7 deletions(-) create mode 100644 tsconfig.test.json diff --git a/package.json b/package.json index e53797b58..78557cebe 100644 --- a/package.json +++ b/package.json @@ -53,8 +53,8 @@ "pretest": "npm run compile", "test": "npm run test-webview && npm run test-extension", "test-extension": "cross-env NODE_OPTIONS=--no-force-async-hooks-checks xvfb-maybe node ./out/test/runTest.js", - "test-webview": "mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/setup-webview.ts src/test/suite/views/webview-app/**/*.test.tsx", - "ai-accuracy-tests": "mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/ai-accuracy-tests/test-setup.ts ./src/test/ai-accuracy-tests/ai-accuracy-tests.ts", + "test-webview": "cross-env NODE_OPTIONS='--no-experimental-strip-types' mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/setup-webview.ts src/test/suite/views/webview-app/**/*.test.tsx", + "ai-accuracy-tests": "cross-env NODE_OPTIONS='--no-experimental-strip-types' mocha -r ts-node/register --grep=\"${MOCHA_GREP}\" --file ./src/test/ai-accuracy-tests/test-setup.ts ./src/test/ai-accuracy-tests/ai-accuracy-tests.ts", "analyze-bundle": "webpack --mode production --analyze", "vscode:prepublish": "npm run clean && npm run compile:constants && npm run compile:resources && webpack --mode production", "check": "npm run lint && npm run depcheck", @@ -1407,7 +1407,7 @@ "@mongodb-js/connection-form": "^1.52.3", "@mongodb-js/connection-info": "^0.21.0", "@mongodb-js/device-id": "^0.3.2", - "@mongodb-js/mongodb-constants": "^0.16.0", + "@mongodb-js/mongodb-constants": "^0.16.1", "@mongosh/browser-runtime-electron": "^3.24.0", "@mongosh/i18n": "^2.16.0", "@mongosh/service-provider-node-driver": "^3.17.1", @@ -1446,7 +1446,7 @@ "@mongodb-js/oidc-mock-provider": "^0.11.5", "@mongodb-js/oidc-plugin": "^2.0.5", "@mongodb-js/prettier-config-devtools": "^1.0.2", - "@mongodb-js/sbom-tools": "^0.8.1", + "@mongodb-js/sbom-tools": "^0.8.5", "@mongodb-js/signing-utils": "^0.4.4", "@mongosh/service-provider-core": "^3.6.0", "@testing-library/react": "^14.3.1", diff --git a/scripts/check-vsix-size.ts b/scripts/check-vsix-size.ts index 0a84981ee..61395c2e9 100644 --- a/scripts/check-vsix-size.ts +++ b/scripts/check-vsix-size.ts @@ -1,6 +1,8 @@ import fs from 'fs'; import path from 'path'; +const __dirname = path.dirname(new URL(import.meta.url).pathname); + const version = JSON.parse( fs.readFileSync(path.resolve(__dirname, '..', 'package.json')).toString(), ).version; diff --git a/scripts/generate-constants.ts b/scripts/generate-constants.ts index 6004adb6f..0b1c7ea86 100644 --- a/scripts/generate-constants.ts +++ b/scripts/generate-constants.ts @@ -1,4 +1,4 @@ -#! /usr/bin/env ts-node +#! /usr/bin/env node import ora from 'ora'; import fs from 'fs'; @@ -8,15 +8,18 @@ import { config } from 'dotenv'; import { promisify } from 'util'; const writeFile = promisify(fs.writeFile); +const __dirname = path.dirname(new URL(import.meta.url).pathname); const ROOT_DIR = path.join(__dirname, '..'); const ui = ora('Generate constants file').start(); config({ path: resolve(__dirname, '../.env') }); +const segmentKey = process.env.SEGMENT_KEY || 'test-segment-key'; + (async () => { await writeFile( `${ROOT_DIR}/constants.json`, - JSON.stringify({ segmentKey: process.env.SEGMENT_KEY }, null, 2), + JSON.stringify({ segmentKey }, null, 2), ); ui.succeed('The constants file has been generated'); })().catch((error) => { diff --git a/scripts/precommit.ts b/scripts/precommit.ts index 34492dbb5..b9627c068 100644 --- a/scripts/precommit.ts +++ b/scripts/precommit.ts @@ -1,4 +1,4 @@ -#! /usr/bin/env ts-node +#! /usr/bin/env node /* eslint-disable no-console */ import path from 'path'; diff --git a/scripts/update-grammar.ts b/scripts/update-grammar.ts index d6c470e43..8637638bd 100644 --- a/scripts/update-grammar.ts +++ b/scripts/update-grammar.ts @@ -12,6 +12,8 @@ import { STAGE_OPERATORS, } from '@mongodb-js/mongodb-constants'; +const __dirname = path.dirname(new URL(import.meta.url).pathname); + const writeFile = promisify(fs.writeFile); const SYNTAXES_DIR = path.join(__dirname, '..', 'syntaxes'); diff --git a/tsconfig.test.json b/tsconfig.test.json new file mode 100644 index 000000000..94d139f03 --- /dev/null +++ b/tsconfig.test.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "ts-node": { + "transpileOnly": true, + "compilerOptions": { + "module": "commonjs", + "jsx": "react" + } + } +} From e08e24ad71d3701dd829494bcfa0727a8378caba Mon Sep 17 00:00:00 2001 From: gagik Date: Wed, 12 Nov 2025 15:09:21 +0100 Subject: [PATCH 4/5] chore: package-lock --- package-lock.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index da155d029..605afc1d8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,7 @@ "@mongodb-js/connection-form": "^1.52.3", "@mongodb-js/connection-info": "^0.21.0", "@mongodb-js/device-id": "^0.3.2", - "@mongodb-js/mongodb-constants": "^0.16.0", + "@mongodb-js/mongodb-constants": "^0.16.1", "@mongosh/browser-runtime-electron": "^3.24.0", "@mongosh/i18n": "^2.16.0", "@mongosh/service-provider-node-driver": "^3.17.1", @@ -55,7 +55,7 @@ "@mongodb-js/oidc-mock-provider": "^0.11.5", "@mongodb-js/oidc-plugin": "^2.0.5", "@mongodb-js/prettier-config-devtools": "^1.0.2", - "@mongodb-js/sbom-tools": "^0.8.1", + "@mongodb-js/sbom-tools": "^0.8.5", "@mongodb-js/signing-utils": "^0.4.4", "@mongosh/service-provider-core": "^3.6.0", "@testing-library/react": "^14.3.1", @@ -8018,9 +8018,9 @@ } }, "node_modules/@mongodb-js/mongodb-constants": { - "version": "0.16.0", - "resolved": "https://registry.npmjs.org/@mongodb-js/mongodb-constants/-/mongodb-constants-0.16.0.tgz", - "integrity": "sha512-+sX23v00L/8w9yjTgNpLS19u6QwVtatQ+Z/4BIk+LAdkEUzw/1Ra7EMw7KpEIHbwmQKSG8KFymJwBPMUKlDKGw==", + "version": "0.16.1", + "resolved": "https://registry.npmjs.org/@mongodb-js/mongodb-constants/-/mongodb-constants-0.16.1.tgz", + "integrity": "sha512-dm9low2Fp0fSftUYFslTMNpXQuoVm1qOH9vpswQBn5GmtlW11VdaK1EKFI33BR/kusNq6bQhqeqtRiNdTNTD5w==", "license": "Apache-2.0", "dependencies": { "semver": "^7.7.1" @@ -8170,9 +8170,9 @@ } }, "node_modules/@mongodb-js/sbom-tools": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/@mongodb-js/sbom-tools/-/sbom-tools-0.8.1.tgz", - "integrity": "sha512-m1nVOJfenkVoGkfMJ14vOb2/CgxVfThpZl7RFz2WZ/MODF/piLkokZqrMb+au2s8t2016bpjyGa3xGbp1RBdZw==", + "version": "0.8.5", + "resolved": "https://registry.npmjs.org/@mongodb-js/sbom-tools/-/sbom-tools-0.8.5.tgz", + "integrity": "sha512-JhOlTaddbFy6RC1MrxjYhsMI2zRvMDTlxlChq+3Fum6DKLyf0gHKYl72Ek2w04fG+Cq3HPBfkz6wZO48AAPC1Q==", "dev": true, "license": "Apache-2.0", "dependencies": { From e1fc338bdf1d9b2f3f2514f46c23e48137bb5a44 Mon Sep 17 00:00:00 2001 From: gagik Date: Wed, 12 Nov 2025 15:17:08 +0100 Subject: [PATCH 5/5] chore: precommit hook --- package.json | 4 ++-- scripts/generate-icon-font.ts | 8 ++++---- scripts/precommit.ts | 6 +++++- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 78557cebe..9d0083cb8 100644 --- a/package.json +++ b/package.json @@ -67,11 +67,11 @@ "presnyk-test": "echo \"Creating backup for package-lock.json.\"; cp package-lock.json original-package-lock.json", "snyk-test": "node scripts/snyk-test.js", "postsnyk-test": "echo \"Restoring original package-lock.json.\"; mv original-package-lock.json package-lock.json", - "generate-icon-font": "ts-node ./scripts/generate-icon-font.ts", + "generate-icon-font": "node ./scripts/generate-icon-font.ts", "generate-vulnerability-report": "mongodb-sbom-tools generate-vulnerability-report --snyk-reports=.sbom/snyk-test-result.json --dependencies=.sbom/dependencies.json --fail-on=high", "create-vulnerability-tickets": "mongodb-sbom-tools generate-vulnerability-report --snyk-reports=.sbom/snyk-test-result.json --dependencies=.sbom/dependencies.json --create-jira-issues", "prepare": "husky", - "precommit": "ts-node ./scripts/precommit.ts" + "precommit": "node ./scripts/precommit.ts" }, "engines": { "vscode": "^1.101.1", diff --git a/scripts/generate-icon-font.ts b/scripts/generate-icon-font.ts index 290479c5c..363f2e4b1 100644 --- a/scripts/generate-icon-font.ts +++ b/scripts/generate-icon-font.ts @@ -1,7 +1,7 @@ -import webfont from 'webfont'; +import { webfont } from 'webfont'; import fs from 'fs/promises'; -import { GlyphData } from 'webfont/dist/src/types'; import prettier from 'prettier'; +import path from 'path'; /** Icons to include in the generated icon font */ const INCLUDED_ICONS = [ @@ -61,14 +61,14 @@ async function main(): Promise { const prettierConfig = await prettier.resolveConfig('./.prettierrc.json'); await fs.writeFile( './package.json', - prettier.format(JSON.stringify(currentConfiguration), { + await prettier.format(JSON.stringify(currentConfiguration), { ...prettierConfig, parser: 'json-stringify', }), ); } -function getUnicodeHex(glyph: GlyphData): string { +function getUnicodeHex(glyph: any): string { if (glyph.metadata?.unicode == undefined) { throw new Error('No unicode defined'); } diff --git a/scripts/precommit.ts b/scripts/precommit.ts index b9627c068..7afcc5449 100644 --- a/scripts/precommit.ts +++ b/scripts/precommit.ts @@ -4,8 +4,12 @@ import path from 'path'; import { promisify } from 'util'; import { execFile } from 'child_process'; +import prettier from '@mongodb-js/prettier-config-devtools/.prettierrc.json' with { type: 'json' }; const execFileAsync = promisify(execFile); +import { createRequire } from 'module'; +const require = createRequire(import.meta.url); + async function main(fileList: string[]) { if (fileList.length === 0) { console.log('No files to re-format. Skipping ...'); @@ -20,7 +24,7 @@ async function main(fileList: string[]) { await execFileAsync('npx', [ 'prettier', '--config', - require.resolve('@mongodb-js/prettier-config-devtools/.prettierrc.json'), + require.resolve(prettier), // Silently ignore files that are of format that is not supported by prettier. '--ignore-unknown', '--write',