diff --git a/.github/workflows/test-and-build.yaml b/.github/workflows/test-and-build.yaml index 68c37f732..0e4b4e13c 100644 --- a/.github/workflows/test-and-build.yaml +++ b/.github/workflows/test-and-build.yaml @@ -31,13 +31,25 @@ jobs: with: fetch-depth: 0 + - name: Get VS Code Node.js version + id: get-vscode-node-version + shell: bash + run: | + # Fetch Node.js version from VS Code's .nvmrc, default to 22.20.0 if unavailable + NODE_VERSION=$(curl -fsSL https://raw.githubusercontent.com/microsoft/vscode/main/.nvmrc | tr -d '[:space:]') + if [ -z "$NODE_VERSION" ]; then + NODE_VERSION="22.20.0" + fi + echo "Using Node.js version for VS Code extension tests: $NODE_VERSION" + echo "vscode-node-version=$NODE_VERSION" >> $GITHUB_OUTPUT + - name: Setup pnpm uses: pnpm/action-setup@v4 - name: Setup Node.js Environment uses: actions/setup-node@v4 with: - node-version: 22.15.1 + node-version: ${{ steps.get-vscode-node-version.outputs.vscode-node-version }} cache: pnpm - name: Run tests and build diff --git a/package.json b/package.json index 111fbca3d..f51e20db3 100644 --- a/package.json +++ b/package.json @@ -42,10 +42,10 @@ "scripts": { "clean": "rimraf -g ./out/* ./dist/*", "lint": "eslint . && prettier --check .", - "update-grammar": "ts-node ./scripts/update-grammar.ts", + "update-grammar": "node ./scripts/update-grammar.ts", "precompile": "pnpm run clean", "compile": "npm-run-all compile:*", - "compile:constants": "ts-node ./scripts/generate-constants.ts", + "compile:constants": "node ./scripts/generate-constants.ts", "compile:resources": "pnpm run update-grammar", "compile:extension": "tsc -p ./", "compile:extension-bundles": "webpack --mode development", @@ -63,15 +63,15 @@ "depcheck": "depcheck", "package": "cross-env NODE_OPTIONS='--require ./scripts/no-npm-list-fail.js' vsce package --githubBranch main", "local-install": "pnpm 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 .", "snyk-test": "node scripts/snyk-test.js", - "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/check-vsix-size.ts b/scripts/check-vsix-size.ts index 0a84981ee..bcbda1cc1 100644 --- a/scripts/check-vsix-size.ts +++ b/scripts/check-vsix-size.ts @@ -1,5 +1,8 @@ import fs from 'fs'; import path from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); const version = JSON.parse( fs.readFileSync(path.resolve(__dirname, '..', 'package.json')).toString(), diff --git a/scripts/generate-constants.ts b/scripts/generate-constants.ts index 4da51b7dc..552b02bea 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'; @@ -6,8 +6,10 @@ import path from 'path'; import { resolve } from 'path'; import { config } from 'dotenv'; import { promisify } from 'util'; +import { fileURLToPath } from 'url'; const writeFile = promisify(fs.writeFile); +const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.join(__dirname, '..'); const ui = ora('Generate constants file').start(); 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 34492dbb5..7afcc5449 100644 --- a/scripts/precommit.ts +++ b/scripts/precommit.ts @@ -1,11 +1,15 @@ -#! /usr/bin/env ts-node +#! /usr/bin/env node /* eslint-disable no-console */ 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', diff --git a/scripts/update-grammar.ts b/scripts/update-grammar.ts index d6c470e43..d783e13e4 100644 --- a/scripts/update-grammar.ts +++ b/scripts/update-grammar.ts @@ -3,6 +3,7 @@ import mkdirp from 'mkdirp'; import ora from 'ora'; import fs from 'fs'; import { promisify } from 'util'; +import { fileURLToPath } from 'url'; import { ACCUMULATORS, @@ -12,6 +13,8 @@ import { STAGE_OPERATORS, } from '@mongodb-js/mongodb-constants'; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + const writeFile = promisify(fs.writeFile); const SYNTAXES_DIR = path.join(__dirname, '..', 'syntaxes'); diff --git a/src/commands/index.ts b/src/commands/index.ts index 6d0439853..3e8a4aae6 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,96 +1,99 @@ -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', +export const ExtensionCommand = { + mdbConnect: 'mdb.connect', + mdbConnectWithUri: 'mdb.connectWithURI', + mdbOpenOverviewPage: 'mdb.openOverviewPage', + mdbDisconnect: 'mdb.disconnect', + mdbRemoveConnection: 'mdb.removeConnection', - OPEN_MONGODB_ISSUE_REPORTER = 'mdb.openMongoDBIssueReporter', + openMongodbIssueReporter: 'mdb.openMongoDBIssueReporter', - MDB_OPEN_MDB_SHELL = 'mdb.openMongoDBShell', - MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW = 'mdb.treeViewOpenMongoDBShell', + mdbOpenMdbShell: 'mdb.openMongoDBShell', + mdbOpenMdbShellFromTreeView: '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', + mdbCreatePlayground: 'mdb.createPlayground', + mdbCreatePlaygroundFromOverviewPage: + 'mdb.createNewPlaygroundFromOverviewPage', + mdbRunSelectedPlaygroundBlocks: 'mdb.runSelectedPlaygroundBlocks', + mdbRunAllPlaygroundBlocks: 'mdb.runAllPlaygroundBlocks', + mdbRunAllOrSelectedPlaygroundBlocks: 'mdb.runPlayground', + mdbExportCodeToPlayground: 'mdb.exportCodeToPlayground', - MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX = 'mdb.fixThisInvalidInteractiveSyntax', - MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX = 'mdb.fixAllInvalidInteractiveSyntax', + mdbFixThisInvalidInteractiveSyntax: 'mdb.fixThisInvalidInteractiveSyntax', + mdbFixAllInvalidInteractiveSyntax: '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', + mdbSelectTargetForExportToLanguage: 'mdb.selectTargetForExportToLanguage', + mdbExportToLanguage: 'mdb.exportToLanguage', + mdbChangeDriverSyntaxForExportToLanguage: + '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', + mdbOpenMongodbDocumentFromCodeLens: 'mdb.openMongoDBDocumentFromCodeLens', + mdbOpenMongodbDocumentFromTree: 'mdb.openMongoDBDocumentFromTree', + mdbSaveMongodbDocument: 'mdb.saveMongoDBDocument', - MDB_CHANGE_ACTIVE_CONNECTION = 'mdb.changeActiveConnection', + mdbChangeActiveConnection: 'mdb.changeActiveConnection', - MDB_CODELENS_SHOW_MORE_DOCUMENTS = 'mdb.codeLens.showMoreDocumentsClicked', + mdbCodelensShowMoreDocuments: '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', + mdbAddConnection: 'mdb.addConnection', + mdbAddConnectionWithUri: 'mdb.addConnectionWithURI', + mdbRefreshPlaygroundsFromTreeView: 'mdb.refreshPlaygroundsFromTreeView', + mdbOpenPlaygroundFromTreeView: 'mdb.openPlaygroundFromTreeView', + mdbConnectToConnectionTreeView: 'mdb.connectToConnectionTreeItem', + mdbCreatePlaygroundFromTreeView: 'mdb.createNewPlaygroundFromTreeView', + mdbCreatePlaygroundFromTreeItem: 'mdb.createNewPlaygroundFromTreeItem', + mdbDisconnectFromConnectionTreeView: 'mdb.disconnectFromConnectionTreeItem', + mdbEditConnection: 'mdb.editConnection', + mdbRefreshConnection: 'mdb.refreshConnection', + mdbCopyConnectionString: 'mdb.copyConnectionString', + mdbEditPresetConnections: 'mdb.editPresetConnections', + mdbRemoveConnectionTreeView: 'mdb.treeItemRemoveConnection', + mdbRenameConnection: 'mdb.renameConnection', + mdbAddDatabase: 'mdb.addDatabase', + mdbSearchForDocuments: 'mdb.searchForDocuments', + mdbCopyDatabaseName: 'mdb.copyDatabaseName', + mdbDropDatabase: 'mdb.dropDatabase', + mdbRefreshDatabase: 'mdb.refreshDatabase', + mdbAddCollection: 'mdb.addCollection', + mdbCopyCollectionName: 'mdb.copyCollectionName', + mdbDropCollection: 'mdb.dropCollection', + mdbViewCollectionDocuments: 'mdb.viewCollectionDocuments', + mdbRefreshCollection: 'mdb.refreshCollection', + mdbRefreshDocumentList: 'mdb.refreshDocumentList', + mdbInsertDocumentFromTreeView: 'mdb.insertDocumentFromTreeView', + mdbRefreshSchema: 'mdb.refreshSchema', + mdbCopySchemaFieldName: 'mdb.copySchemaFieldName', + mdbRefreshIndexes: 'mdb.refreshIndexes', + mdbCreateIndexTreeView: 'mdb.createIndexFromTreeView', + mdbInsertObjectidToEditor: 'mdb.insertObjectIdToEditor', + mdbGenerateObjectidToClipboard: 'mdb.generateObjectIdToClipboard', + mdbCopyDocumentContentsFromTreeView: 'mdb.copyDocumentContentsFromTreeView', + mdbCloneDocumentFromTreeView: 'mdb.cloneDocumentFromTreeView', + mdbDeleteDocumentFromTreeView: 'mdb.deleteDocumentFromTreeView', + mdbAddStreamProcessor: 'mdb.addStreamProcessor', + mdbStartStreamProcessor: 'mdb.startStreamProcessor', + mdbStopStreamProcessor: 'mdb.stopStreamProcessor', + mdbDropStreamProcessor: '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', + openParticipantCodeInPlayground: 'mdb.openParticipantCodeInPlayground', + sendMessageToParticipant: 'mdb.sendMessageToParticipant', + sendMessageToParticipantFromInput: 'mdb.sendMessageToParticipantFromInput', + askCopilotFromTreeItem: 'mdb.askCopilotFromTreeItem', + runParticipantCode: 'mdb.runParticipantCode', + connectWithParticipant: 'mdb.connectWithParticipant', + selectDatabaseWithParticipant: 'mdb.selectDatabaseWithParticipant', + selectCollectionWithParticipant: 'mdb.selectCollectionWithParticipant', + participantOpenRawSchemaOutput: 'mdb.participantViewRawSchemaOutput', + showExportToLanguageResult: 'mdb.showExportToLanguageResult', // MCP Server commands. - START_MCP_SERVER = 'mdb.startMCPServer', - STOP_MCP_SERVER = 'mdb.stopMCPServer', - GET_MCP_SERVER_CONFIG = 'mdb.getMCPServerConfig', -} + startMcpServer: 'mdb.startMCPServer', + stopMcpServer: 'mdb.stopMCPServer', + getMcpServerConfig: 'mdb.getMCPServerConfig', +} as const; -export type ExtensionCommand = EXTENSION_COMMANDS; +export type ExtensionCommand = + (typeof ExtensionCommand)[keyof typeof ExtensionCommand]; -export default EXTENSION_COMMANDS; +export default ExtensionCommand; diff --git a/src/connectionController.ts b/src/connectionController.ts index 87c7ecf15..daef43fad 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 ConnectionType = { + connectionForm: 'CONNECTION_FORM', + connectionString: 'CONNECTION_STRING', + connectionId: 'CONNECTION_ID', +} as const; -export enum NewConnectionType { - NEW_CONNECTION = 'NEW_CONNECTION', - SAVED_CONNECTION = 'SAVED_CONNECTION', -} +export type ConnectionTypes = + (typeof ConnectionType)[keyof typeof ConnectionType]; + +export const NewConnectionType = { + newConnection: 'NEW_CONNECTION', + savedConnection: 'SAVED_CONNECTION', +} as const; + +export type NewConnectionType = + (typeof NewConnectionType)[keyof typeof NewConnectionType]; interface ConnectionAttemptResult { successfullyConnected: boolean; @@ -341,7 +350,7 @@ export default class ConnectionController { connectionOptions: { connectionString: connectionStringData.toString(), }, - connectionType: ConnectionTypes.CONNECTION_STRING, + connectionType: ConnectionType.connectionString, name, })); @@ -689,7 +698,7 @@ export default class ConnectionController { const result = await this._connect( connectionId, - ConnectionTypes.CONNECTION_ID, + ConnectionType.connectionId, ); /** After successfully connecting with an overridden connection @@ -1148,20 +1157,20 @@ export default class ConnectionController { return url.toString(); } - getConnectionStatus(): CONNECTION_STATUS { + getConnectionStatus(): ConnectionStatus { if (this.isCurrentlyConnected()) { if (this.isDisconnecting()) { - return CONNECTION_STATUS.DISCONNECTING; + return CONNECTION_STATUS.disconnecting; } - return CONNECTION_STATUS.CONNECTED; + return CONNECTION_STATUS.connected; } if (this.isConnecting()) { - return CONNECTION_STATUS.CONNECTING; + return CONNECTION_STATUS.connecting; } - return CONNECTION_STATUS.DISCONNECTED; + return CONNECTION_STATUS.disconnected; } getConnectionStatusStringForConnection(connectionId: string): string { @@ -1209,7 +1218,7 @@ export default class ConnectionController { { label: 'Add new connection', data: { - type: NewConnectionType.NEW_CONNECTION, + type: NewConnectionType.newConnection, }, }, ]; @@ -1219,7 +1228,7 @@ export default class ConnectionController { { label: 'Add new connection', data: { - type: NewConnectionType.NEW_CONNECTION, + type: NewConnectionType.newConnection, }, }, ...Object.values(this._connections) @@ -1229,7 +1238,7 @@ export default class ConnectionController { .map((item: LoadedConnection) => ({ label: item.name, data: { - type: NewConnectionType.SAVED_CONNECTION, + type: NewConnectionType.savedConnection, connectionId: item.id, }, })), @@ -1248,7 +1257,7 @@ export default class ConnectionController { return false; } - if (selectedQuickPickItem.data.type === NewConnectionType.NEW_CONNECTION) { + if (selectedQuickPickItem.data.type === NewConnectionType.newConnection) { return this.connectWithURI(); } diff --git a/src/documentSource.ts b/src/documentSource.ts index 066c96cb6..dc7b52196 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 DocumentSource = { + treeview: 'treeview', + playground: 'playground', + collectionview: 'collectionview', + codelens: 'codelens', +} as const; + +export type DocumentSource = + (typeof DocumentSource)[keyof typeof DocumentSource]; export type DocumentSourceDetails = 'database' | 'collection' | undefined; diff --git a/src/editors/activeConnectionCodeLensProvider.ts b/src/editors/activeConnectionCodeLensProvider.ts index f22c5db15..916e72e86 100644 --- a/src/editors/activeConnectionCodeLensProvider.ts +++ b/src/editors/activeConnectionCodeLensProvider.ts @@ -1,6 +1,6 @@ import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import type ConnectionController from '../connectionController'; import { isPlayground } from '../utils/playground'; import { getDBFromConnectionString } from '../utils/connection-string-db'; @@ -57,7 +57,7 @@ export default class ActiveConnectionCodeLensProvider codeLens.command = { title: message, - command: EXTENSION_COMMANDS.MDB_CHANGE_ACTIVE_CONNECTION, + command: ExtensionCommand.mdbChangeActiveConnection, arguments: [], }; diff --git a/src/editors/collectionDocumentsCodeLensProvider.ts b/src/editors/collectionDocumentsCodeLensProvider.ts index ad41bc93e..e5a05c91a 100644 --- a/src/editors/collectionDocumentsCodeLensProvider.ts +++ b/src/editors/collectionDocumentsCodeLensProvider.ts @@ -1,6 +1,6 @@ import { URLSearchParams } from 'url'; import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import type CollectionDocumentsOperationStore from './collectionDocumentsOperationsStore'; import { @@ -91,7 +91,7 @@ export default class CollectionDocumentsCodeLensProvider codeLens.command = { title: commandTitle, tooltip: commandTooltip, - command: EXTENSION_COMMANDS.MDB_CODELENS_SHOW_MORE_DOCUMENTS, + command: ExtensionCommand.mdbCodelensShowMoreDocuments, arguments: [{ operationId, connectionId, namespace }], }; diff --git a/src/editors/editDocumentCodeLensProvider.ts b/src/editors/editDocumentCodeLensProvider.ts index ea541dbfc..976c77002 100644 --- a/src/editors/editDocumentCodeLensProvider.ts +++ b/src/editors/editDocumentCodeLensProvider.ts @@ -5,7 +5,7 @@ import type { Document } from 'bson'; import type ConnectionController from '../connectionController'; import { DocumentSource } from '../documentSource'; import type { EditDocumentInfo } from '../types/editDocumentInfoType'; -import EXTENSION_COMMANDS from '../commands'; +import { 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: DocumentSource.collectionview, }); this._codeLensesInfo[data.uri.toString()] = resultCodeLensesInfo; } updateCodeLensesForPlayground(playgroundResult: PlaygroundRunResult): void { - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DocumentSource.playground; let resultCodeLensesInfo: EditDocumentInfo[] = []; if (!playgroundResult || !playgroundResult.content) { @@ -144,11 +144,11 @@ 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', - command: EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS, + command: ExtensionCommand.mdbOpenMongodbDocumentFromCodeLens, arguments: [item], }; diff --git a/src/editors/editorsController.ts b/src/editors/editorsController.ts index 6a01a341b..8390f0dff 100644 --- a/src/editors/editorsController.ts +++ b/src/editors/editorsController.ts @@ -24,7 +24,7 @@ import formatError from '../utils/formatError'; import { MemoryFileSystemProvider } from './memoryFileSystemProvider'; import MongoDBDocumentService, { DOCUMENT_ID_URI_IDENTIFIER, - DOCUMENT_SOURCE_URI_IDENTIFIER, + URI_IDENTIFIER, VIEW_DOCUMENT_SCHEME, } from './mongoDBDocumentService'; import type PlaygroundController from './playgroundController'; @@ -196,7 +196,7 @@ export default class EditorsController { const connectionIdUriQuery = `${CONNECTION_ID_URI_IDENTIFIER}=${activeConnectionId}`; const documentIdReference = this._documentIdStore.add(data.documentId); const documentIdUriQuery = `${DOCUMENT_ID_URI_IDENTIFIER}=${documentIdReference}`; - const documentSourceUriQuery = `${DOCUMENT_SOURCE_URI_IDENTIFIER}=${data.source}`; + const documentSourceUriQuery = `${URI_IDENTIFIER}=${data.source}`; const fileTitle = encodeURIComponent( getFileDisplayNameForDocument(data.documentId, data.namespace), @@ -234,9 +234,7 @@ export default class EditorsController { const connectionId = uriParams.get(CONNECTION_ID_URI_IDENTIFIER); const documentIdReference = uriParams.get(DOCUMENT_ID_URI_IDENTIFIER) || ''; const documentId = this._documentIdStore.get(documentIdReference); - const source = uriParams.get( - DOCUMENT_SOURCE_URI_IDENTIFIER, - ) as DocumentSource; + const source = uriParams.get(URI_IDENTIFIER) as DocumentSource; if ( editor.document.uri.scheme !== 'VIEW_DOCUMENT_SCHEME' || diff --git a/src/editors/exportToLanguageCodeLensProvider.ts b/src/editors/exportToLanguageCodeLensProvider.ts index 126890199..ad6b16634 100644 --- a/src/editors/exportToLanguageCodeLensProvider.ts +++ b/src/editors/exportToLanguageCodeLensProvider.ts @@ -1,6 +1,6 @@ import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import { isExportToLanguageResult } from '../types/playgroundType'; import type PlaygroundResultProvider from './playgroundResultProvider'; @@ -51,8 +51,7 @@ export default class ExportToLanguageCodeLensProvider .includeDriverSyntax ? 'Exclude Driver Syntax' : 'Include Driver Syntax', - command: - EXTENSION_COMMANDS.MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE, + command: ExtensionCommand.mdbChangeDriverSyntaxForExportToLanguage, arguments: [ !this._playgroundResultProvider._playgroundResult.includeDriverSyntax, ], diff --git a/src/editors/mongoDBDocumentService.ts b/src/editors/mongoDBDocumentService.ts index 14e955b74..4cedfc30b 100644 --- a/src/editors/mongoDBDocumentService.ts +++ b/src/editors/mongoDBDocumentService.ts @@ -15,7 +15,7 @@ const log = createLogger('document controller'); export const DOCUMENT_ID_URI_IDENTIFIER = 'documentId'; -export const DOCUMENT_SOURCE_URI_IDENTIFIER = 'source'; +export const URI_IDENTIFIER = 'source'; export const VIEW_DOCUMENT_SCHEME = 'VIEW_DOCUMENT_SCHEME'; @@ -52,10 +52,7 @@ export default class MongoDBDocumentService { const errorMessage = `Unable to save document: ${message}`; this._telemetryService.track( - new DocumentUpdatedTelemetryEvent( - DocumentSource.DOCUMENT_SOURCE_TREEVIEW, - false, - ), + new DocumentUpdatedTelemetryEvent(DocumentSource.treeview, false), ); throw new Error(errorMessage); diff --git a/src/editors/playgroundDiagnosticsCodeActionProvider.ts b/src/editors/playgroundDiagnosticsCodeActionProvider.ts index 5a1dd6d66..1ba5ad679 100644 --- a/src/editors/playgroundDiagnosticsCodeActionProvider.ts +++ b/src/editors/playgroundDiagnosticsCodeActionProvider.ts @@ -2,8 +2,8 @@ import * as vscode from 'vscode'; import type { Diagnostic } from 'vscode-languageserver/node'; -import EXTENSION_COMMANDS from '../commands'; -import DIAGNOSTIC_CODES from './../language/diagnosticCodes'; +import ExtensionCommand from '../commands'; +import DiagnosticCode from './../language/diagnosticCodes'; export default class PlaygroundDiagnosticsCodeActionProvider implements vscode.CodeActionProvider @@ -32,15 +32,14 @@ export default class PlaygroundDiagnosticsCodeActionProvider for (const diagnostic of diagnostics) { switch (diagnostic.code) { - case DIAGNOSTIC_CODES.invalidInteractiveSyntaxes: + case DiagnosticCode.invalidInteractiveSyntaxes: { const fix = new vscode.CodeAction( 'Fix this interactive syntax problem', vscode.CodeActionKind.QuickFix, ); fix.command = { - command: - EXTENSION_COMMANDS.MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX, + command: ExtensionCommand.mdbFixThisInvalidInteractiveSyntax, title: 'Fix invalid interactive syntax', arguments: [ { @@ -60,7 +59,7 @@ export default class PlaygroundDiagnosticsCodeActionProvider const allDiagnostics = vscode.languages .getDiagnostics(document.uri) - .filter((d) => d.code === DIAGNOSTIC_CODES.invalidInteractiveSyntaxes); + .filter((d) => d.code === DiagnosticCode.invalidInteractiveSyntaxes); if (allDiagnostics.length > 1) { const fix = new vscode.CodeAction( @@ -69,7 +68,7 @@ export default class PlaygroundDiagnosticsCodeActionProvider ); fix.command = { - command: EXTENSION_COMMANDS.MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX, + command: ExtensionCommand.mdbFixAllInvalidInteractiveSyntax, title: 'Fix invalid interactive syntax', arguments: [ { diff --git a/src/editors/playgroundSelectionCodeActionProvider.ts b/src/editors/playgroundSelectionCodeActionProvider.ts index 59361c003..89b3f7c65 100644 --- a/src/editors/playgroundSelectionCodeActionProvider.ts +++ b/src/editors/playgroundSelectionCodeActionProvider.ts @@ -1,6 +1,6 @@ import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import { isPlayground, getSelectedText } from '../utils/playground'; import { COPILOT_CHAT_EXTENSION_ID } from '../participant/constants'; @@ -47,7 +47,7 @@ export default class PlaygroundSelectionCodeActionProvider let codeActions: vscode.CodeAction[] = [ this.createCodeAction({ title: 'Run selected playground blocks', - command: EXTENSION_COMMANDS.MDB_RUN_SELECTED_PLAYGROUND_BLOCKS, + command: ExtensionCommand.mdbRunSelectedPlaygroundBlocks, }), ]; @@ -61,7 +61,7 @@ export default class PlaygroundSelectionCodeActionProvider ...EXPORT_TO_LANGUAGE_ALIASES.map(({ id, alias }) => this.createCodeAction({ title: `Export To ${alias}`, - command: EXTENSION_COMMANDS.MDB_EXPORT_TO_LANGUAGE, + command: ExtensionCommand.mdbExportToLanguage, arguments: [id], }), ), diff --git a/src/editors/queryWithCopilotCodeLensProvider.ts b/src/editors/queryWithCopilotCodeLensProvider.ts index d1a95c7f7..8499fda33 100644 --- a/src/editors/queryWithCopilotCodeLensProvider.ts +++ b/src/editors/queryWithCopilotCodeLensProvider.ts @@ -1,5 +1,5 @@ import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import type { SendMessageToParticipantFromInputOptions } from '../participant/participantTypes'; import { isPlayground } from '../utils/playground'; import { COPILOT_EXTENSION_ID } from '../participant/constants'; @@ -34,7 +34,7 @@ export class QueryWithCopilotCodeLensProvider command: 'query', isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_CODELENS, + source: DocumentSource.codelens, source_details: undefined, }, }; @@ -42,7 +42,7 @@ export class QueryWithCopilotCodeLensProvider return [ new vscode.CodeLens(new vscode.Range(0, 0, 0, 0), { title: '✨ Generate query with MongoDB Copilot', - command: EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, + command: ExtensionCommand.sendMessageToParticipantFromInput, arguments: [options], }), ]; diff --git a/src/explorer/collectionTreeItem.ts b/src/explorer/collectionTreeItem.ts index 72993bce9..d87d221f3 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, + CollectionType, 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 === CollectionType.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 === CollectionType.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 === CollectionType.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 === CollectionType.view || + this._type === CollectionType.timeseries ) { this.documentCount = null; return 0; diff --git a/src/explorer/documentListTreeItem.ts b/src/explorer/documentListTreeItem.ts index d9d511620..3d5d7b2b4 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 CollectionType = { + collection: 'collection', + view: 'view', + timeseries: 'timeseries', +} as const; + +export type CollectionType = + (typeof CollectionType)[keyof typeof CollectionType]; const ITEM_LABEL = 'Documents'; @@ -53,7 +56,7 @@ const getCollapsableStateForDocumentList = ( isExpanded: boolean, type: string, ): vscode.TreeItemCollapsibleState => { - if (type === CollectionTypes.view) { + if (type === CollectionType.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 === CollectionType.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 === CollectionType.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..214e08327 100644 --- a/src/explorer/explorerTreeController.ts +++ b/src/explorer/explorerTreeController.ts @@ -4,8 +4,8 @@ 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 EXTENSION_COMMANDS from '../commands'; +import { DOCUMENT_LIST_ITEM, CollectionType } from './documentListTreeItem'; +import ExtensionCommand from '../commands'; import { sortTreeItemsByLabel } from './treeItemUtils'; import type { LoadedConnection } from '../storage/connectionStorage'; import { @@ -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; @@ -115,17 +120,17 @@ export default class ExplorerTreeController if (selectedItem.contextValue === DOCUMENT_ITEM) { await vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, + ExtensionCommand.mdbOpenMongodbDocumentFromTree, event.selection[0], ); } if ( selectedItem.contextValue === DOCUMENT_LIST_ITEM && - selectedItem.type === CollectionTypes.view + selectedItem.type === CollectionType.view ) { await vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_VIEW_COLLECTION_DOCUMENTS, + ExtensionCommand.mdbViewCollectionDocuments, event.selection[0], ); } diff --git a/src/explorer/fieldTreeItem.ts b/src/explorer/fieldTreeItem.ts index 392c5af26..18f7fec71 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 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', +} as const; + +export type FieldType = (typeof FieldType)[keyof typeof FieldType]; export type SchemaFieldType = { name: string; 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/index.ts b/src/explorer/index.ts index 849da95a3..abef82889 100644 --- a/src/explorer/index.ts +++ b/src/explorer/index.ts @@ -2,7 +2,7 @@ import CollectionTreeItem from './collectionTreeItem'; import ExplorerController from './explorerController'; import ConnectionTreeItem from './connectionTreeItem'; import DatabaseTreeItem from './databaseTreeItem'; -import { CollectionTypes } from './documentListTreeItem'; +import { CollectionType } from './documentListTreeItem'; import DocumentTreeItem from './documentTreeItem'; import HelpExplorer from './helpExplorer'; import SchemaTreeItem from './schemaTreeItem'; @@ -11,7 +11,7 @@ import StreamProcessorTreeItem from './streamProcessorTreeItem'; export { CollectionTreeItem, - CollectionTypes, + CollectionType, ConnectionTreeItem, DatabaseTreeItem, DocumentTreeItem, diff --git a/src/explorer/indexTreeItem.ts b/src/explorer/indexTreeItem.ts index a4a2c6b5b..e9ceec88c 100644 --- a/src/explorer/indexTreeItem.ts +++ b/src/explorer/indexTreeItem.ts @@ -4,15 +4,17 @@ 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 IndexKeyType = { + 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 IndexKeyType)[keyof typeof IndexKeyType]; export type IndexModel = { v: number; @@ -24,26 +26,26 @@ export type IndexModel = { }; function getIconNameForIndexKeyType(indexKeyType: IndexKeyType): string { - if (indexKeyType === IndexKeyType.ASCENDING) { + if (indexKeyType === IndexKeyType.ascending) { return 'ascending'; } - if (indexKeyType === IndexKeyType.DESCENDING) { + if (indexKeyType === IndexKeyType.descending) { return 'descending'; } - if (indexKeyType === IndexKeyType.TEXT) { + if (indexKeyType === IndexKeyType.text) { return 'text'; } - if (indexKeyType === IndexKeyType.HASHED) { + if (indexKeyType === IndexKeyType.hashed) { return 'hashed'; } if ( - indexKeyType === IndexKeyType.GEO || - indexKeyType === IndexKeyType.GEOHAYSTACK || - indexKeyType === IndexKeyType.GEOSPHERE + indexKeyType === IndexKeyType.geo || + indexKeyType === IndexKeyType.geohaystack || + indexKeyType === IndexKeyType.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/explorer/playgroundsTree.ts b/src/explorer/playgroundsTree.ts index 69df02ee6..17da0a631 100644 --- a/src/explorer/playgroundsTree.ts +++ b/src/explorer/playgroundsTree.ts @@ -3,7 +3,7 @@ import PlaygroundsTreeHeader from './playgroundsTreeHeader'; import { PLAYGROUND_ITEM } from './playgroundsTreeItem'; import { createLogger } from '../logging'; import PlaygroundsTreeItem from './playgroundsTreeItem'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import { getPlaygrounds } from '../utils/playground'; const log = createLogger('playgrounds tree'); @@ -75,7 +75,7 @@ export default class PlaygroundsTree if (selectedItem.contextValue === PLAYGROUND_ITEM) { await vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW, + ExtensionCommand.mdbOpenPlaygroundFromTreeView, selectedItem, ); } 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..57cb759b7 100644 --- a/src/language/diagnosticCodes.ts +++ b/src/language/diagnosticCodes.ts @@ -1,5 +1,8 @@ -enum DIAGNOSTIC_CODES { - invalidInteractiveSyntaxes = 'playground.invalidInteractiveSyntaxes', -} +export const DiagnosticCode = { + invalidInteractiveSyntaxes: 'playground.invalidInteractiveSyntaxes', +} as const; -export default DIAGNOSTIC_CODES; +export type DiagnosticCodes = + (typeof DiagnosticCode)[keyof typeof DiagnosticCode]; + +export default DiagnosticCode; diff --git a/src/language/languageServerController.ts b/src/language/languageServerController.ts index fa1b26ed3..dcc0a60dd 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 { ServerCommand } 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(ServerCommand.mongodbServiceCreated, () => { const msg = this._currentConnectionId ? 'MongoDBService restored from an internal error' : 'MongoDBService initialized'; @@ -123,7 +123,7 @@ export default class LanguageServerController { hasConnectionOptions: !!this._currentConnectionOptions, })}`, ); - void this._client.sendRequest(ServerCommands.INITIALIZE_MONGODB_SERVICE, { + void this._client.sendRequest(ServerCommand.initializeMongodbService, { extensionPath: this._context.extensionPath, connectionId: this._currentConnectionId, connectionString: this._currentConnectionString, @@ -131,31 +131,25 @@ export default class LanguageServerController { }); }); - this._client.onNotification(ServerCommands.SHOW_INFO_MESSAGE, (message) => { + this._client.onNotification(ServerCommand.showInfoMessage, (message) => { log.info('The info message shown to a user', message); void vscode.window.showInformationMessage(message); }); - this._client.onNotification( - ServerCommands.SHOW_ERROR_MESSAGE, - (message) => { - log.info('The error message shown to a user', message); - void vscode.window.showErrorMessage(message); - }, - ); + this._client.onNotification(ServerCommand.showErrorMessage, (message) => { + log.info('The error message shown to a user', message); + void vscode.window.showErrorMessage(message); + }); - this._client.onNotification( - ServerCommands.SHOW_CONSOLE_OUTPUT, - (outputs) => { - for (const line of outputs) { - this._consoleOutputChannel.appendLine( - typeof line === 'string' ? line : util.inspect(line), - ); - } + this._client.onNotification(ServerCommand.showConsoleOutput, (outputs) => { + for (const line of outputs) { + this._consoleOutputChannel.appendLine( + typeof line === 'string' ? line : util.inspect(line), + ); + } - this._consoleOutputChannel.show(true); - }, - ); + this._consoleOutputChannel.show(true); + }); } deactivate(): Thenable | undefined { @@ -184,7 +178,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, + ServerCommand.executeCodeFromPlayground, playgroundExecuteParameters, token, ); @@ -217,7 +211,7 @@ export default class LanguageServerController { this._currentConnectionOptions = connectionOptions; const res = await this._client.sendRequest( - ServerCommands.ACTIVE_CONNECTION_CHANGED, + ServerCommand.activeConnectionChanged, { connectionId, connectionString, @@ -229,15 +223,12 @@ export default class LanguageServerController { async resetCache(clear: ClearCompletionsCache): Promise { log.info('Resetting MongoDBService cache...', clear); - await this._client.sendRequest( - ServerCommands.CLEAR_CACHED_COMPLETIONS, - clear, - ); + await this._client.sendRequest(ServerCommand.clearCachedCompletions, clear); } async updateCurrentSessionFields(params): Promise { await this._client.sendRequest( - ServerCommands.UPDATE_CURRENT_SESSION_FIELDS, + ServerCommand.updateCurrentSessionFields, params, ); } diff --git a/src/language/mongoDBService.ts b/src/language/mongoDBService.ts index f6b0e102a..28ee99990 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 { ServerCommand } from './serverCommands'; import type { ShellEvaluateResult, PlaygroundEvaluateParams, @@ -36,7 +36,7 @@ import { Visitor } from './visitor'; import type { CompletionState, NamespaceState } from './visitor'; import LINKS from '../utils/links'; -import DIAGNOSTIC_CODES from './diagnosticCodes'; +import DiagnosticCode from './diagnosticCodes'; import { getDBFromConnectionString } from '../utils/connection-string-db'; const PROJECT = '$project'; @@ -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, + ServerCommand.showErrorMessage, "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 === ServerCommand.showConsoleOutput) { void this._connection.sendNotification(name, payload); } - if (name === ServerCommands.CODE_EXECUTION_RESULT) { + if (name === ServerCommand.codeExecutionResult) { 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, + ServerCommand.showErrorMessage, formatError(error).message, ); } @@ -292,7 +292,7 @@ export default class MongoDBService { }); worker.postMessage({ - name: ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND, + name: ServerCommand.executeCodeFromPlayground, data: { codeToEvaluate: params.codeToEvaluate, filePath: params.filePath, @@ -1163,7 +1163,7 @@ export default class MongoDBService { diagnostics.push({ severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: i, character: startCharacter }, end: { line: i, character: endCharacter }, diff --git a/src/language/server.ts b/src/language/server.ts index 5717f7512..662779fa5 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 { ServerCommand } 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, + ServerCommand.mongodbServiceCreated, 'An instance of MongoDBService is created', ); @@ -158,25 +158,25 @@ connection.onDidChangeWatchedFiles((/* _change */) => { // Execute a playground. connection.onRequest( - ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND, + ServerCommand.executeCodeFromPlayground, (evaluateParams: PlaygroundEvaluateParams, token: CancellationToken) => { return mongoDBService.evaluate(evaluateParams, token); }, ); // Send default configurations to mongoDBService. -connection.onRequest(ServerCommands.INITIALIZE_MONGODB_SERVICE, (settings) => { +connection.onRequest(ServerCommand.initializeMongodbService, (settings) => { mongoDBService.initialize(settings); }); // Change NodeDriverServiceProvider active connection. -connection.onRequest(ServerCommands.ACTIVE_CONNECTION_CHANGED, (params) => { +connection.onRequest(ServerCommand.activeConnectionChanged, (params) => { return mongoDBService.activeConnectionChanged(params); }); // Set fields for tests. connection.onRequest( - ServerCommands.UPDATE_CURRENT_SESSION_FIELDS, + ServerCommand.updateCurrentSessionFields, ({ 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, + ServerCommand.clearCachedCompletions, (clear: ClearCompletionsCache) => { return mongoDBService.clearCachedCompletions(clear); }, diff --git a/src/language/serverCommands.ts b/src/language/serverCommands.ts index 3a7822422..6bc0a3100 100644 --- a/src/language/serverCommands.ts +++ b/src/language/serverCommands.ts @@ -1,17 +1,19 @@ -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 ServerCommand = { + activeConnectionChanged: 'ACTIVE_CONNECTION_CHANGED', + executeCodeFromPlayground: 'EXECUTE_CODE_FROM_PLAYGROUND', + executeRangeFromPlayground: 'EXECUTE_RANGE_FROM_PLAYGROUND', + showErrorMessage: 'SHOW_ERROR_MESSAGE', + showInfoMessage: 'SHOW_INFO_MESSAGE', + getExportToLanguageMode: 'GET_EXPORT_TO_LANGUAGE_MODE', + updateCurrentSessionFields: 'UPDATE_CURRENT_SESSION_FIELDS', + clearCachedCompletions: 'CLEAR_CACHED_COMPLETIONS', + mongodbServiceCreated: 'MONGODB_SERVICE_CREATED', + initializeMongodbService: 'INITIALIZE_MONGODB_SERVICE', + codeExecutionResult: 'CODE_EXECUTION_RESULT', + showConsoleOutput: 'SHOW_CONSOLE_OUTPUT', +} as const; + +export type ServerCommands = (typeof ServerCommand)[keyof typeof ServerCommand]; export type PlaygroundRunParameters = { codeToEvaluate: string; diff --git a/src/language/worker.ts b/src/language/worker.ts index 0fea36a93..c39783004 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 { ServerCommand } from './serverCommands'; import type { ShellEvaluateResult, @@ -44,7 +44,7 @@ type ExecuteCodeOptions = { function handleEvalPrint(values: EvaluationResult[]): void { parentPort?.postMessage({ - name: ServerCommands.SHOW_CONSOLE_OUTPUT, + name: ServerCommand.showConsoleOutput, 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 === ServerCommand.executeCodeFromPlayground) { parentPort?.postMessage({ - name: ServerCommands.CODE_EXECUTION_RESULT, + name: ServerCommand.codeExecutionResult, payload: await execute(data), }); } diff --git a/src/mdbExtensionController.ts b/src/mdbExtensionController.ts index d83db3bb3..ea71c6eb9 100644 --- a/src/mdbExtensionController.ts +++ b/src/mdbExtensionController.ts @@ -25,14 +25,13 @@ import { } from './explorer'; import ExportToLanguageCodeLensProvider from './editors/exportToLanguageCodeLensProvider'; import { type ExportToLanguageResult } from './types/playgroundType'; -import type { ExtensionCommand } from './commands'; import type FieldTreeItem from './explorer/fieldTreeItem'; import type IndexListTreeItem from './explorer/indexListTreeItem'; 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, StorageVariable } from './storage'; import { DeepLinkTelemetryEvent, TelemetryService } from './telemetry'; import type PlaygroundsTreeItem from './explorer/playgroundsTreeItem'; import PlaygroundResultProvider from './editors/playgroundResultProvider'; @@ -49,7 +48,7 @@ import type { SendMessageToParticipantFromInputOptions, ParticipantCommand, } from './participant/participantTypes'; -import EXTENSION_COMMANDS from './commands'; +import ExtensionCommand from './commands'; import { COPILOT_EXTENSION_ID } from './participant/constants'; import { CommandRunTelemetryEvent, @@ -62,92 +61,92 @@ import { MCPController } from './mcp/mcpController'; // Deep link command filtering: Commands are explicitly categorized as allowed or disallowed. // We use tests in mdbExtensionController.test.ts to enforce these lists being disjoint and complete. export const DEEP_LINK_ALLOWED_COMMANDS = [ - EXTENSION_COMMANDS.MDB_CONNECT, - EXTENSION_COMMANDS.MDB_CONNECT_WITH_URI, - EXTENSION_COMMANDS.MDB_OPEN_OVERVIEW_PAGE, - EXTENSION_COMMANDS.MDB_DISCONNECT, - EXTENSION_COMMANDS.OPEN_MONGODB_ISSUE_REPORTER, - EXTENSION_COMMANDS.MDB_OPEN_MDB_SHELL, - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND, - EXTENSION_COMMANDS.MDB_RUN_SELECTED_PLAYGROUND_BLOCKS, - EXTENSION_COMMANDS.MDB_RUN_ALL_PLAYGROUND_BLOCKS, - EXTENSION_COMMANDS.MDB_RUN_ALL_OR_SELECTED_PLAYGROUND_BLOCKS, - EXTENSION_COMMANDS.MDB_EXPORT_CODE_TO_PLAYGROUND, - EXTENSION_COMMANDS.MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX, - EXTENSION_COMMANDS.MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX, - EXTENSION_COMMANDS.MDB_SELECT_TARGET_FOR_EXPORT_TO_LANGUAGE, - EXTENSION_COMMANDS.MDB_EXPORT_TO_LANGUAGE, - EXTENSION_COMMANDS.MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE, - EXTENSION_COMMANDS.MDB_SAVE_MONGODB_DOCUMENT, - EXTENSION_COMMANDS.MDB_CHANGE_ACTIVE_CONNECTION, - EXTENSION_COMMANDS.MDB_CODELENS_SHOW_MORE_DOCUMENTS, - EXTENSION_COMMANDS.MDB_ADD_CONNECTION, - EXTENSION_COMMANDS.MDB_ADD_CONNECTION_WITH_URI, - EXTENSION_COMMANDS.MDB_EDIT_CONNECTION, - EXTENSION_COMMANDS.MDB_REFRESH_CONNECTION, - EXTENSION_COMMANDS.MDB_COPY_CONNECTION_STRING, - EXTENSION_COMMANDS.MDB_EDIT_PRESET_CONNECTIONS, - EXTENSION_COMMANDS.MDB_RENAME_CONNECTION, - EXTENSION_COMMANDS.MDB_ADD_DATABASE, - EXTENSION_COMMANDS.MDB_SEARCH_FOR_DOCUMENTS, - EXTENSION_COMMANDS.MDB_COPY_DATABASE_NAME, - EXTENSION_COMMANDS.MDB_REFRESH_DATABASE, - EXTENSION_COMMANDS.MDB_ADD_COLLECTION, - EXTENSION_COMMANDS.MDB_COPY_COLLECTION_NAME, - EXTENSION_COMMANDS.MDB_VIEW_COLLECTION_DOCUMENTS, - EXTENSION_COMMANDS.MDB_REFRESH_COLLECTION, - EXTENSION_COMMANDS.MDB_REFRESH_DOCUMENT_LIST, - - EXTENSION_COMMANDS.MDB_REFRESH_SCHEMA, - EXTENSION_COMMANDS.MDB_COPY_SCHEMA_FIELD_NAME, - EXTENSION_COMMANDS.MDB_REFRESH_INDEXES, - EXTENSION_COMMANDS.MDB_INSERT_OBJECTID_TO_EDITOR, - EXTENSION_COMMANDS.MDB_GENERATE_OBJECTID_TO_CLIPBOARD, - - EXTENSION_COMMANDS.MDB_ADD_STREAM_PROCESSOR, - EXTENSION_COMMANDS.MDB_START_STREAM_PROCESSOR, - EXTENSION_COMMANDS.MDB_STOP_STREAM_PROCESSOR, - - EXTENSION_COMMANDS.START_MCP_SERVER, - EXTENSION_COMMANDS.STOP_MCP_SERVER, - EXTENSION_COMMANDS.GET_MCP_SERVER_CONFIG, + ExtensionCommand.mdbConnect, + ExtensionCommand.mdbConnectWithUri, + ExtensionCommand.mdbOpenOverviewPage, + ExtensionCommand.mdbDisconnect, + ExtensionCommand.openMongodbIssueReporter, + ExtensionCommand.mdbOpenMdbShell, + ExtensionCommand.mdbCreatePlayground, + ExtensionCommand.mdbRunSelectedPlaygroundBlocks, + ExtensionCommand.mdbRunAllPlaygroundBlocks, + ExtensionCommand.mdbRunAllOrSelectedPlaygroundBlocks, + ExtensionCommand.mdbExportCodeToPlayground, + ExtensionCommand.mdbFixThisInvalidInteractiveSyntax, + ExtensionCommand.mdbFixAllInvalidInteractiveSyntax, + ExtensionCommand.mdbSelectTargetForExportToLanguage, + ExtensionCommand.mdbExportToLanguage, + ExtensionCommand.mdbChangeDriverSyntaxForExportToLanguage, + ExtensionCommand.mdbSaveMongodbDocument, + ExtensionCommand.mdbChangeActiveConnection, + ExtensionCommand.mdbCodelensShowMoreDocuments, + ExtensionCommand.mdbAddConnection, + ExtensionCommand.mdbAddConnectionWithUri, + ExtensionCommand.mdbEditConnection, + ExtensionCommand.mdbRefreshConnection, + ExtensionCommand.mdbCopyConnectionString, + ExtensionCommand.mdbEditPresetConnections, + ExtensionCommand.mdbRenameConnection, + ExtensionCommand.mdbAddDatabase, + ExtensionCommand.mdbSearchForDocuments, + ExtensionCommand.mdbCopyDatabaseName, + ExtensionCommand.mdbRefreshDatabase, + ExtensionCommand.mdbAddCollection, + ExtensionCommand.mdbCopyCollectionName, + ExtensionCommand.mdbViewCollectionDocuments, + ExtensionCommand.mdbRefreshCollection, + ExtensionCommand.mdbRefreshDocumentList, + + ExtensionCommand.mdbRefreshSchema, + ExtensionCommand.mdbCopySchemaFieldName, + ExtensionCommand.mdbRefreshIndexes, + ExtensionCommand.mdbInsertObjectidToEditor, + ExtensionCommand.mdbGenerateObjectidToClipboard, + + ExtensionCommand.mdbAddStreamProcessor, + ExtensionCommand.mdbStartStreamProcessor, + ExtensionCommand.mdbStopStreamProcessor, + + ExtensionCommand.startMcpServer, + ExtensionCommand.stopMcpServer, + ExtensionCommand.getMcpServerConfig, ] as const; export const DEEP_LINK_DISALLOWED_COMMANDS = [ // Participant commands - internal APIs designed for chat UI only - EXTENSION_COMMANDS.RUN_PARTICIPANT_CODE, - EXTENSION_COMMANDS.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, - EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, - EXTENSION_COMMANDS.SELECT_DATABASE_WITH_PARTICIPANT, - EXTENSION_COMMANDS.SELECT_COLLECTION_WITH_PARTICIPANT, - EXTENSION_COMMANDS.PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT, - EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT, - EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, - EXTENSION_COMMANDS.SHOW_EXPORT_TO_LANGUAGE_RESULT, + ExtensionCommand.runParticipantCode, + ExtensionCommand.openParticipantCodeInPlayground, + ExtensionCommand.connectWithParticipant, + ExtensionCommand.selectDatabaseWithParticipant, + ExtensionCommand.selectCollectionWithParticipant, + ExtensionCommand.participantOpenRawSchemaOutput, + ExtensionCommand.sendMessageToParticipant, + ExtensionCommand.sendMessageToParticipantFromInput, + ExtensionCommand.showExportToLanguageResult, // Destructive operations - EXTENSION_COMMANDS.MDB_DROP_DATABASE, - EXTENSION_COMMANDS.MDB_DROP_COLLECTION, - EXTENSION_COMMANDS.MDB_DROP_STREAM_PROCESSOR, - EXTENSION_COMMANDS.MDB_REMOVE_CONNECTION, + ExtensionCommand.mdbDropDatabase, + ExtensionCommand.mdbDropCollection, + ExtensionCommand.mdbDropStreamProcessor, + ExtensionCommand.mdbRemoveConnection, // Location-specific items - not intended to be accessed in other ways - EXTENSION_COMMANDS.MDB_DELETE_DOCUMENT_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_REMOVE_CONNECTION_TREE_VIEW, - EXTENSION_COMMANDS.MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_REFRESH_PLAYGROUNDS_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_CONNECT_TO_CONNECTION_TREE_VIEW, - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_TREE_ITEM, - EXTENSION_COMMANDS.MDB_DISCONNECT_FROM_CONNECTION_TREE_VIEW, - EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, - EXTENSION_COMMANDS.MDB_INSERT_DOCUMENT_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_COPY_DOCUMENT_CONTENTS_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_CLONE_DOCUMENT_FROM_TREE_VIEW, - EXTENSION_COMMANDS.ASK_COPILOT_FROM_TREE_ITEM, - EXTENSION_COMMANDS.MDB_CREATE_INDEX_TREE_VIEW, - EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS, - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE, + ExtensionCommand.mdbDeleteDocumentFromTreeView, + ExtensionCommand.mdbRemoveConnectionTreeView, + ExtensionCommand.mdbOpenMdbShellFromTreeView, + ExtensionCommand.mdbRefreshPlaygroundsFromTreeView, + ExtensionCommand.mdbOpenPlaygroundFromTreeView, + ExtensionCommand.mdbConnectToConnectionTreeView, + ExtensionCommand.mdbCreatePlaygroundFromTreeView, + ExtensionCommand.mdbCreatePlaygroundFromTreeItem, + ExtensionCommand.mdbDisconnectFromConnectionTreeView, + ExtensionCommand.mdbOpenMongodbDocumentFromTree, + ExtensionCommand.mdbInsertDocumentFromTreeView, + ExtensionCommand.mdbCopyDocumentContentsFromTreeView, + ExtensionCommand.mdbCloneDocumentFromTreeView, + ExtensionCommand.askCopilotFromTreeItem, + ExtensionCommand.mdbCreateIndexTreeView, + ExtensionCommand.mdbOpenMongodbDocumentFromCodeLens, + ExtensionCommand.mdbCreatePlaygroundFromOverviewPage, ] as const; // This class is the top-level controller for our extension. @@ -340,9 +339,7 @@ export default class MDBExtensionController implements vscode.Disposable { try { if ( - !Object.values(EXTENSION_COMMANDS).includes( - command as EXTENSION_COMMANDS, - ) + !Object.values(ExtensionCommand).includes(command as ExtensionCommand) ) { throw new Error( `Unable to execute command '${command}' since it is not registered by the MongoDB extension.`, @@ -350,9 +347,9 @@ export default class MDBExtensionController implements vscode.Disposable { } if ( - ( - DEEP_LINK_DISALLOWED_COMMANDS as readonly EXTENSION_COMMANDS[] - ).includes(command as EXTENSION_COMMANDS) + (DEEP_LINK_DISALLOWED_COMMANDS as readonly ExtensionCommand[]).includes( + command as ExtensionCommand, + ) ) { throw new Error( `Command '${command}' cannot be invoked via deep links.`, @@ -371,29 +368,29 @@ export default class MDBExtensionController implements vscode.Disposable { // Register our extension's commands. These are the event handlers and // control the functionality of our extension. // ------ CONNECTION ------ // - this.registerCommand(EXTENSION_COMMANDS.MDB_OPEN_OVERVIEW_PAGE, () => { + this.registerCommand(ExtensionCommand.mdbOpenOverviewPage, () => { this._webviewController.openWebview(this._context); return Promise.resolve(true); }); - this.registerCommand(EXTENSION_COMMANDS.MDB_CONNECT, () => { + this.registerCommand(ExtensionCommand.mdbConnect, () => { this._webviewController.openWebview(this._context); return Promise.resolve(true); }); - this.registerCommand(EXTENSION_COMMANDS.MDB_CONNECT_WITH_URI, (params) => { + this.registerCommand(ExtensionCommand.mdbConnectWithUri, (params) => { return this._connectionController.connectWithURI(params); }); - this.registerCommand(EXTENSION_COMMANDS.MDB_DISCONNECT, () => + this.registerCommand(ExtensionCommand.mdbDisconnect, () => this._connectionController.disconnect(), ); - this.registerCommand(EXTENSION_COMMANDS.MDB_REMOVE_CONNECTION, (params) => + this.registerCommand(ExtensionCommand.mdbRemoveConnection, (params) => this._connectionController.onRemoveMongoDBConnection(params), ); - this.registerCommand(EXTENSION_COMMANDS.MDB_CHANGE_ACTIVE_CONNECTION, () => + this.registerCommand(ExtensionCommand.mdbChangeActiveConnection, () => this._connectionController.changeActiveConnection(), ); this.registerCommand( - EXTENSION_COMMANDS.OPEN_MONGODB_ISSUE_REPORTER, + ExtensionCommand.openMongodbIssueReporter, async () => { return await vscode.commands.executeCommand( 'workbench.action.openIssueReporter', @@ -406,67 +403,65 @@ export default class MDBExtensionController implements vscode.Disposable { ); // ------ SHELL ------ // - this.registerCommand(EXTENSION_COMMANDS.MDB_OPEN_MDB_SHELL, () => + this.registerCommand(ExtensionCommand.mdbOpenMdbShell, () => launchMongoShell(this._connectionController), ); - this.registerCommand( - EXTENSION_COMMANDS.MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW, - () => launchMongoShell(this._connectionController), + this.registerCommand(ExtensionCommand.mdbOpenMdbShellFromTreeView, () => + launchMongoShell(this._connectionController), ); // ------ PLAYGROUND ------ // - this.registerCommand(EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND, () => + this.registerCommand(ExtensionCommand.mdbCreatePlayground, () => this._playgroundController.createPlayground(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE, + ExtensionCommand.mdbCreatePlaygroundFromOverviewPage, () => this._playgroundController.createPlayground(), ); - this.registerCommand( - EXTENSION_COMMANDS.MDB_RUN_SELECTED_PLAYGROUND_BLOCKS, - () => this._playgroundController.runSelectedPlaygroundBlocks(), + this.registerCommand(ExtensionCommand.mdbRunSelectedPlaygroundBlocks, () => + this._playgroundController.runSelectedPlaygroundBlocks(), ); - this.registerCommand(EXTENSION_COMMANDS.MDB_RUN_ALL_PLAYGROUND_BLOCKS, () => + this.registerCommand(ExtensionCommand.mdbRunAllPlaygroundBlocks, () => this._playgroundController.runAllPlaygroundBlocks(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_RUN_ALL_OR_SELECTED_PLAYGROUND_BLOCKS, + ExtensionCommand.mdbRunAllOrSelectedPlaygroundBlocks, () => this._playgroundController.runAllOrSelectedPlaygroundBlocks(), ); - this.registerCommand(EXTENSION_COMMANDS.MDB_EXPORT_CODE_TO_PLAYGROUND, () => + this.registerCommand(ExtensionCommand.mdbExportCodeToPlayground, () => this._participantController.exportCodeToPlayground(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX, + ExtensionCommand.mdbFixThisInvalidInteractiveSyntax, (data) => this._playgroundController.fixThisInvalidInteractiveSyntax(data), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX, + ExtensionCommand.mdbFixAllInvalidInteractiveSyntax, (data) => this._playgroundController.fixAllInvalidInteractiveSyntax(data), ); // ------ EXPORT TO LANGUAGE ------ // this.registerCommand( - EXTENSION_COMMANDS.MDB_SELECT_TARGET_FOR_EXPORT_TO_LANGUAGE, + ExtensionCommand.mdbSelectTargetForExportToLanguage, () => this._participantController.selectTargetForExportToLanguage(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_EXPORT_TO_LANGUAGE, + ExtensionCommand.mdbExportToLanguage, (language: string) => this._participantController.exportPlaygroundToLanguage(language), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE, + ExtensionCommand.mdbChangeDriverSyntaxForExportToLanguage, (includeDriverSyntax: boolean) => this._participantController.changeDriverSyntaxForExportToLanguage( includeDriverSyntax, ), ); this.registerParticipantCommand( - EXTENSION_COMMANDS.SHOW_EXPORT_TO_LANGUAGE_RESULT, + ExtensionCommand.showExportToLanguageResult, (data: ExportToLanguageResult) => { return this._playgroundController.showExportToLanguageResult(data); }, @@ -474,7 +469,7 @@ export default class MDBExtensionController implements vscode.Disposable { // ------ DOCUMENTS ------ // this.registerCommand( - EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS, + ExtensionCommand.mdbOpenMongodbDocumentFromCodeLens, (data: EditDocumentInfo) => { this._telemetryService.track( new DocumentEditedTelemetryEvent(data.source), @@ -483,7 +478,7 @@ export default class MDBExtensionController implements vscode.Disposable { return this._editorsController.openMongoDBDocument(data); }, ); - this.registerCommand(EXTENSION_COMMANDS.MDB_SAVE_MONGODB_DOCUMENT, () => + this.registerCommand(ExtensionCommand.mdbSaveMongodbDocument, () => this._editorsController.saveMongoDBDocument(), ); @@ -492,7 +487,7 @@ export default class MDBExtensionController implements vscode.Disposable { // ------ CHAT PARTICIPANT ------ // this.registerParticipantCommand( - EXTENSION_COMMANDS.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, + ExtensionCommand.openParticipantCodeInPlayground, ({ runnableContent }: RunParticipantCodeCommandArgs) => { return this._playgroundController.createPlaygroundFromParticipantCode({ text: runnableContent, @@ -500,14 +495,14 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerParticipantCommand( - EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT, + ExtensionCommand.sendMessageToParticipant, async (options: SendMessageToParticipantOptions) => { await this._participantController.sendMessageToParticipant(options); return true; }, ); this.registerParticipantCommand( - EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, + ExtensionCommand.sendMessageToParticipantFromInput, async (options: SendMessageToParticipantFromInputOptions) => { await this._participantController.sendMessageToParticipantFromInput( options, @@ -516,14 +511,14 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerParticipantCommand( - EXTENSION_COMMANDS.ASK_COPILOT_FROM_TREE_ITEM, + ExtensionCommand.askCopilotFromTreeItem, async (treeItem: DatabaseTreeItem | CollectionTreeItem) => { await this._participantController.askCopilotFromTreeItem(treeItem); return true; }, ); this.registerParticipantCommand( - EXTENSION_COMMANDS.RUN_PARTICIPANT_CODE, + ExtensionCommand.runParticipantCode, ({ runnableContent }: RunParticipantCodeCommandArgs) => { return this._playgroundController.evaluateParticipantCode( runnableContent, @@ -531,13 +526,13 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, + ExtensionCommand.connectWithParticipant, (data: { id?: string; command?: string }) => { return this._participantController.connectWithParticipant(data); }, ); this.registerCommand( - EXTENSION_COMMANDS.SELECT_DATABASE_WITH_PARTICIPANT, + ExtensionCommand.selectDatabaseWithParticipant, (data: { chatId: string; command: ParticipantCommand; @@ -547,7 +542,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.SELECT_COLLECTION_WITH_PARTICIPANT, + ExtensionCommand.selectCollectionWithParticipant, (data: any) => { return this._participantController.selectCollectionWithParticipant( data, @@ -555,7 +550,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT, + ExtensionCommand.participantOpenRawSchemaOutput, async ({ schema }: OpenSchemaCommandArgs) => { const document = await vscode.workspace.openTextDocument({ language: 'json', @@ -603,7 +598,7 @@ export default class MDBExtensionController implements vscode.Disposable { registerEditorCommands(): void { this.registerCommand( - EXTENSION_COMMANDS.MDB_CODELENS_SHOW_MORE_DOCUMENTS, + ExtensionCommand.mdbCodelensShowMoreDocuments, ({ operationId, connectionId, namespace }) => { return this._editorsController.onViewMoreCollectionDocuments( operationId, @@ -615,15 +610,15 @@ export default class MDBExtensionController implements vscode.Disposable { } registerTreeViewCommands(): void { - this.registerCommand(EXTENSION_COMMANDS.MDB_ADD_CONNECTION, () => { + this.registerCommand(ExtensionCommand.mdbAddConnection, () => { this._webviewController.openWebview(this._context); return Promise.resolve(true); }); - this.registerCommand(EXTENSION_COMMANDS.MDB_ADD_CONNECTION_WITH_URI, () => + this.registerCommand(ExtensionCommand.mdbAddConnectionWithUri, () => this._connectionController.connectWithURI(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CONNECT_TO_CONNECTION_TREE_VIEW, + ExtensionCommand.mdbConnectToConnectionTreeView, async (connectionTreeItem: ConnectionTreeItem) => { const { successfullyConnected } = await this._connectionController.connectWithConnectionId( @@ -633,7 +628,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_DISCONNECT_FROM_CONNECTION_TREE_VIEW, + ExtensionCommand.mdbDisconnectFromConnectionTreeView, () => { // In order for this command to be activated, the connection must // be the active connection, so we can just generally disconnect. @@ -641,7 +636,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_CONNECTION, + ExtensionCommand.mdbRefreshConnection, async (connectionTreeItem: ConnectionTreeItem): Promise => { connectionTreeItem.resetCache(); this._explorerController.refresh(); @@ -656,14 +651,14 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_EDIT_PRESET_CONNECTIONS, + ExtensionCommand.mdbEditPresetConnections, async (element: ConnectionTreeItem | undefined) => { await this._connectionController.openPresetConnectionsSettings(element); return true; }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_COPY_CONNECTION_STRING, + ExtensionCommand.mdbCopyConnectionString, async (element: ConnectionTreeItem): Promise => { const connectionString = this._connectionController.copyConnectionStringByConnectionId( @@ -677,14 +672,14 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REMOVE_CONNECTION_TREE_VIEW, + ExtensionCommand.mdbRemoveConnectionTreeView, (element: ConnectionTreeItem) => this._connectionController.onRemoveMongoDBConnection({ id: element.connectionId, }), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_EDIT_CONNECTION, + ExtensionCommand.mdbEditConnection, (element: ConnectionTreeItem) => { const connectionOptions = this._connectionController.getConnectionConnectionOptions( @@ -709,12 +704,12 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_RENAME_CONNECTION, + ExtensionCommand.mdbRenameConnection, (element: ConnectionTreeItem) => this._connectionController.renameConnection(element.connectionId), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_ADD_DATABASE, + ExtensionCommand.mdbAddDatabase, async (element: ConnectionTreeItem): Promise => { if (!element) { void vscode.window.showErrorMessage( @@ -757,7 +752,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_COPY_DATABASE_NAME, + ExtensionCommand.mdbCopyDatabaseName, async (element: DatabaseTreeItem) => { await vscode.env.clipboard.writeText(element.databaseName); void vscode.window.showInformationMessage('Copied to clipboard.'); @@ -766,7 +761,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_DROP_DATABASE, + ExtensionCommand.mdbDropDatabase, async (element: DatabaseTreeItem): Promise => { const successfullyDroppedDatabase = await element.onDropDatabaseClicked(); @@ -785,7 +780,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_DATABASE, + ExtensionCommand.mdbRefreshDatabase, async (databaseTreeItem: DatabaseTreeItem): Promise => { databaseTreeItem.resetCache(); this._explorerController.refresh(); @@ -798,7 +793,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_ADD_COLLECTION, + ExtensionCommand.mdbAddCollection, async (element: DatabaseTreeItem): Promise => { if (this._connectionController.isDisconnecting()) { void vscode.window.showErrorMessage( @@ -814,7 +809,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_COPY_COLLECTION_NAME, + ExtensionCommand.mdbCopyCollectionName, async (element: CollectionTreeItem): Promise => { await vscode.env.clipboard.writeText(element.collectionName); void vscode.window.showInformationMessage('Copied to clipboard.'); @@ -823,7 +818,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_DROP_COLLECTION, + ExtensionCommand.mdbDropCollection, async (element: CollectionTreeItem): Promise => { const successfullyDroppedCollection = await element.onDropCollectionClicked(); @@ -842,7 +837,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_VIEW_COLLECTION_DOCUMENTS, + ExtensionCommand.mdbViewCollectionDocuments, ( element: CollectionTreeItem | DocumentListTreeItem, ): Promise => { @@ -852,7 +847,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_COLLECTION, + ExtensionCommand.mdbRefreshCollection, async (collectionTreeItem: CollectionTreeItem): Promise => { collectionTreeItem.resetCache(); this._explorerController.refresh(); @@ -862,7 +857,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_SEARCH_FOR_DOCUMENTS, + ExtensionCommand.mdbSearchForDocuments, (element: DocumentListTreeItem): Promise => this._playgroundController.createPlaygroundForSearch( element.databaseName, @@ -870,10 +865,10 @@ export default class MDBExtensionController implements vscode.Disposable { ), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, + ExtensionCommand.mdbOpenMongodbDocumentFromTree, (element: DocumentTreeItem): Promise => { return this._editorsController.openMongoDBDocument({ - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DocumentSource.treeview, documentId: element.documentId, namespace: element.namespace, connectionId: this._connectionController.getActiveConnectionId(), @@ -882,7 +877,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_DOCUMENT_LIST, + ExtensionCommand.mdbRefreshDocumentList, async (documentsListTreeItem: DocumentListTreeItem): Promise => { await documentsListTreeItem.resetCache(); this._explorerController.refresh(); @@ -892,7 +887,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_INSERT_DOCUMENT_FROM_TREE_VIEW, + ExtensionCommand.mdbInsertDocumentFromTreeView, async ( documentsListTreeItem: DocumentListTreeItem | CollectionTreeItem, ): Promise => { @@ -903,7 +898,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_SCHEMA, + ExtensionCommand.mdbRefreshSchema, async (schemaTreeItem: SchemaTreeItem): Promise => { schemaTreeItem.resetCache(); this._explorerController.refresh(); @@ -913,7 +908,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_COPY_SCHEMA_FIELD_NAME, + ExtensionCommand.mdbCopySchemaFieldName, async (fieldTreeItem: FieldTreeItem): Promise => { await vscode.env.clipboard.writeText(fieldTreeItem.getFieldName()); void vscode.window.showInformationMessage('Copied to clipboard.'); @@ -922,7 +917,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_INDEXES, + ExtensionCommand.mdbRefreshIndexes, (indexListTreeItem: IndexListTreeItem): Promise => { indexListTreeItem.resetCache(); this._explorerController.refresh(); @@ -931,7 +926,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CREATE_INDEX_TREE_VIEW, + ExtensionCommand.mdbCreateIndexTreeView, (indexListTreeItem: IndexListTreeItem): Promise => { return this._playgroundController.createPlaygroundForNewIndex( indexListTreeItem.databaseName, @@ -939,26 +934,25 @@ export default class MDBExtensionController implements vscode.Disposable { ); }, ); - this.registerCommand( - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_TREE_VIEW, - () => this._playgroundController.createPlayground(), + this.registerCommand(ExtensionCommand.mdbCreatePlaygroundFromTreeView, () => + this._playgroundController.createPlayground(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_TREE_ITEM, + ExtensionCommand.mdbCreatePlaygroundFromTreeItem, (treeItem: DatabaseTreeItem | CollectionTreeItem) => this._playgroundController.createPlaygroundFromTreeItem(treeItem), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_PLAYGROUNDS_FROM_TREE_VIEW, + ExtensionCommand.mdbRefreshPlaygroundsFromTreeView, () => this._playgroundsExplorer.refresh(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW, + ExtensionCommand.mdbOpenPlaygroundFromTreeView, (playgroundsTreeItem: PlaygroundsTreeItem) => this._playgroundController.openPlayground(playgroundsTreeItem.filePath), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_COPY_DOCUMENT_CONTENTS_FROM_TREE_VIEW, + ExtensionCommand.mdbCopyDocumentContentsFromTreeView, async (documentTreeItem: DocumentTreeItem): Promise => { const documentContents = await documentTreeItem.getStringifiedEJSONDocumentContents(); @@ -969,7 +963,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CLONE_DOCUMENT_FROM_TREE_VIEW, + ExtensionCommand.mdbCloneDocumentFromTreeView, async (documentTreeItem: DocumentTreeItem): Promise => { const documentContents = await documentTreeItem.getJSStringDocumentContents(); @@ -985,7 +979,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_DELETE_DOCUMENT_FROM_TREE_VIEW, + ExtensionCommand.mdbDeleteDocumentFromTreeView, async (documentTreeItem: DocumentTreeItem): Promise => { const successfullyDropped = await documentTreeItem.onDeleteDocumentClicked(); @@ -1004,7 +998,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_INSERT_OBJECTID_TO_EDITOR, + ExtensionCommand.mdbInsertObjectidToEditor, async (): Promise => { const editor = vscode.window.activeTextEditor; @@ -1028,7 +1022,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_GENERATE_OBJECTID_TO_CLIPBOARD, + ExtensionCommand.mdbGenerateObjectidToClipboard, async (): Promise => { await vscode.env.clipboard.writeText(generateId().toHexString()); void vscode.window.showInformationMessage('Copied to clipboard.'); @@ -1039,7 +1033,7 @@ export default class MDBExtensionController implements vscode.Disposable { this.registerAtlasStreamsTreeViewCommands(); this.registerCommand( - EXTENSION_COMMANDS.START_MCP_SERVER, + ExtensionCommand.startMcpServer, async (): Promise => { await this._mcpController.startServer(); return true; @@ -1047,7 +1041,7 @@ export default class MDBExtensionController implements vscode.Disposable { ); this.registerCommand( - EXTENSION_COMMANDS.STOP_MCP_SERVER, + ExtensionCommand.stopMcpServer, async (): Promise => { await this._mcpController.stopServer(); return true; @@ -1055,7 +1049,7 @@ export default class MDBExtensionController implements vscode.Disposable { ); this.registerCommand( - EXTENSION_COMMANDS.GET_MCP_SERVER_CONFIG, + ExtensionCommand.getMcpServerConfig, (): Promise => { return this._mcpController.openServerConfig(); }, @@ -1064,7 +1058,7 @@ export default class MDBExtensionController implements vscode.Disposable { registerAtlasStreamsTreeViewCommands(): void { this.registerCommand( - EXTENSION_COMMANDS.MDB_ADD_STREAM_PROCESSOR, + ExtensionCommand.mdbAddStreamProcessor, async (element: ConnectionTreeItem): Promise => { if (!element) { void vscode.window.showErrorMessage( @@ -1107,7 +1101,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_START_STREAM_PROCESSOR, + ExtensionCommand.mdbStartStreamProcessor, async (element: StreamProcessorTreeItem): Promise => { const started = await element.onStartClicked(); if (started) { @@ -1121,7 +1115,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_STOP_STREAM_PROCESSOR, + ExtensionCommand.mdbStopStreamProcessor, async (element: StreamProcessorTreeItem): Promise => { const stopped = await element.onStopClicked(); if (stopped) { @@ -1135,7 +1129,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_DROP_STREAM_PROCESSOR, + ExtensionCommand.mdbDropStreamProcessor, async (element: StreamProcessorTreeItem): Promise => { const dropped = await element.onDropClicked(); if (dropped) { @@ -1161,7 +1155,7 @@ export default class MDBExtensionController implements vscode.Disposable { } const hasBeenShownViewAlready = !!this._storageController.get( - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + StorageVariable.globalHasBeenShownInitialView, ); if (hasBeenShownViewAlready) { @@ -1171,13 +1165,11 @@ export default class MDBExtensionController implements vscode.Disposable { if (!this._connectionStorage.hasSavedConnections()) { // Only show the overview page if there are no saved connections. - void vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_OPEN_OVERVIEW_PAGE, - ); + void vscode.commands.executeCommand(ExtensionCommand.mdbOpenOverviewPage); } void this._storageController.update( - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + StorageVariable.globalHasBeenShownInitialView, true, ); } diff --git a/src/participant/participant.ts b/src/participant/participant.ts index 42f95c6b7..96f5bbd1e 100644 --- a/src/participant/participant.ts +++ b/src/participant/participant.ts @@ -7,9 +7,9 @@ import util from 'util'; import { createLogger } from '../logging'; import type ConnectionController from '../connectionController'; import type { LoadedConnection } from '../storage/connectionStorage'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import type { StorageController } from '../storage'; -import { StorageVariables } from '../storage'; +import { StorageVariable } 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, + ParticipantErrorType, type ExportToPlaygroundError, } from './participantErrorTypes'; import type PlaygroundResultProvider from '../editors/playgroundResultProvider'; @@ -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: DocumentSource.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: DocumentSource.treeview, source_details: 'collection', }, }); @@ -340,12 +340,12 @@ export default class ParticipantController { runnableContent, }; stream.button({ - command: EXTENSION_COMMANDS.RUN_PARTICIPANT_CODE, + command: ExtensionCommand.runParticipantCode, title: vscode.l10n.t('▶️ Run'), arguments: [commandArgs], }); stream.button({ - command: EXTENSION_COMMANDS.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, + command: ExtensionCommand.openParticipantCodeInPlayground, title: vscode.l10n.t('Open in playground'), arguments: [commandArgs], }); @@ -615,7 +615,7 @@ export default class ParticipantController { .slice(0, MAX_MARKDOWN_LIST_LENGTH) .map((conn: LoadedConnection) => createMarkdownLink({ - commandId: EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, + commandId: ExtensionCommand.connectWithParticipant, data: { id: conn.id, command, @@ -624,7 +624,7 @@ export default class ParticipantController { }), ), createMarkdownLink({ - commandId: EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, + commandId: ExtensionCommand.connectWithParticipant, name: 'Show more', data: { command, @@ -785,7 +785,7 @@ export default class ParticipantController { databases.slice(0, MAX_MARKDOWN_LIST_LENGTH).forEach((db) => stream.markdown( createMarkdownLink({ - commandId: EXTENSION_COMMANDS.SELECT_DATABASE_WITH_PARTICIPANT, + commandId: ExtensionCommand.selectDatabaseWithParticipant, data: { command, chatId: ChatMetadataStore.getChatIdFromHistoryOrNewChatId( @@ -807,7 +807,7 @@ export default class ParticipantController { context.history, ), }, - commandId: EXTENSION_COMMANDS.SELECT_DATABASE_WITH_PARTICIPANT, + commandId: ExtensionCommand.selectDatabaseWithParticipant, name: 'Show more', }), ); @@ -830,7 +830,7 @@ export default class ParticipantController { collections.slice(0, MAX_MARKDOWN_LIST_LENGTH).forEach((coll) => stream.markdown( createMarkdownLink({ - commandId: EXTENSION_COMMANDS.SELECT_COLLECTION_WITH_PARTICIPANT, + commandId: ExtensionCommand.selectCollectionWithParticipant, data: { command, chatId: ChatMetadataStore.getChatIdFromHistoryOrNewChatId( @@ -846,7 +846,7 @@ export default class ParticipantController { if (collections.length > MAX_MARKDOWN_LIST_LENGTH) { stream.markdown( createMarkdownLink({ - commandId: EXTENSION_COMMANDS.SELECT_COLLECTION_WITH_PARTICIPANT, + commandId: ExtensionCommand.selectCollectionWithParticipant, data: { command, chatId: ChatMetadataStore.getChatIdFromHistoryOrNewChatId( @@ -1434,7 +1434,7 @@ export default class ParticipantController { }); stream.button({ - command: EXTENSION_COMMANDS.PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT, + command: ExtensionCommand.participantOpenRawSchemaOutput, title: vscode.l10n.t('Open JSON Output'), arguments: [ { @@ -1779,7 +1779,7 @@ export default class ParticipantController { this._telemetryService.track( new ParticipantResponseFailedTelemetryEvent( 'docs', - ParticipantErrorTypes.DOCS_CHATBOT_API, + ParticipantErrorType.docsChatbotApi, ), ); @@ -1814,7 +1814,7 @@ export default class ParticipantController { return false; } await vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_EXPORT_TO_LANGUAGE, + ExtensionCommand.mdbExportToLanguage, language.id, ); return true; @@ -1893,7 +1893,7 @@ export default class ParticipantController { const content = contentOrError.value; await vscode.commands.executeCommand( - EXTENSION_COMMANDS.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, + ExtensionCommand.openParticipantCodeInPlayground, { runnableContent: content, }, @@ -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, + StorageVariable.copilotHasBeenShownWelcomeMessage, ); 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, + StorageVariable.copilotHasBeenShownWelcomeMessage, true, ); } @@ -2158,7 +2158,7 @@ Please see our [FAQ](https://www.mongodb.com/docs/generative-ai-faq/) for more i ); await vscode.commands.executeCommand( - EXTENSION_COMMANDS.SHOW_EXPORT_TO_LANGUAGE_RESULT, + ExtensionCommand.showExportToLanguageResult, { prompt, content: transpiledContent, diff --git a/src/participant/participantErrorTypes.ts b/src/participant/participantErrorTypes.ts index d83ce8598..bea4e426b 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 ParticipantErrorType = { + chatModelOffTopic: 'Chat Model Off Topic', + invalidPrompt: 'Invalid Prompt', + filtered: 'Filtered by Responsible AI Service', + other: 'Other', + docsChatbotApi: 'Docs Chatbot API Issue', +} as const; + +export type ParticipantErrorType = + (typeof ParticipantErrorType)[keyof typeof ParticipantErrorType]; export type ExportToPlaygroundError = | 'cancelled' diff --git a/src/participant/prompts/promptHistory.ts b/src/participant/prompts/promptHistory.ts index 86226d71d..7dbcc2cd9 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 { ParticipantErrorType } from '../participantErrorTypes'; import type { ChatResult } from '../constants'; import type { ParticipantResponseType } from '../participantTypes'; @@ -12,8 +12,7 @@ export class PromptHistory { namespaceIsKnown: boolean; }): vscode.LanguageModelChatMessage | undefined { if ( - currentTurn.result.errorDetails?.message === - ParticipantErrorTypes.FILTERED + currentTurn.result.errorDetails?.message === ParticipantErrorType.filtered ) { return undefined; } @@ -83,7 +82,7 @@ export class PromptHistory { if ( nextTurn instanceof vscode.ChatResponseTurn && - nextTurn.result.errorDetails?.message === ParticipantErrorTypes.FILTERED + nextTurn.result.errorDetails?.message === ParticipantErrorType.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..a86ea46dd 100644 --- a/src/storage/connectionStorage.ts +++ b/src/storage/connectionStorage.ts @@ -8,12 +8,11 @@ import type { ConnectionOptions } from 'mongodb-data-service'; import { createLogger } from '../logging'; import type StorageController from './storageController'; -import type { SecretStorageLocationType } from './storageController'; +import { StorageLocation } from './storageController'; import { - DefaultSavingLocations, + DefaultSavingLocation, SecretStorageLocation, - StorageLocation, - StorageVariables, + StorageVariable, } from './storageController'; import { v4 as uuidv4 } from 'uuid'; @@ -24,7 +23,7 @@ export interface StoreConnectionInfo { id: string; // Connection model id or a new uuid. name: string; // Possibly user given name, not unique. storageLocation: StorageLocation; - secretStorageLocation?: SecretStorageLocationType; + secretStorageLocation?: SecretStorageLocation; connectionOptions?: ConnectionOptions; source?: ConnectionSource; lastUsed?: Date; // Date and time when the connection was last used, i.e. connected with. @@ -133,9 +132,9 @@ export class ConnectionStorage { async saveConnection(connection: LoadedConnection): Promise { if ( - ![StorageLocation.GLOBAL, StorageLocation.WORKSPACE].includes( - connection.storageLocation, - ) + !( + [StorageLocation.global, StorageLocation.workspace] as StorageLocation[] + ).includes(connection.storageLocation) ) { return; } @@ -157,9 +156,9 @@ export class ConnectionStorage { connectionWithoutSecrets: StoreConnectionInfo, ): Promise { const variableName = - connectionWithoutSecrets.storageLocation === StorageLocation.GLOBAL - ? StorageVariables.GLOBAL_SAVED_CONNECTIONS - : StorageVariables.WORKSPACE_SAVED_CONNECTIONS; + connectionWithoutSecrets.storageLocation === StorageLocation.global + ? StorageVariable.globalSavedConnections + : StorageVariable.workspaceSavedConnections; // Get the current saved connections. let savedConnections = this._storageController.get( @@ -211,7 +210,7 @@ export class ConnectionStorage { connectionString: presetConnection.connectionString, }, source: presetConnection.source, - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }) satisfies LoadedConnection, ); @@ -220,12 +219,12 @@ export class ConnectionStorage { async loadConnections(): Promise { const globalAndWorkspaceConnections = Object.values({ ...this._storageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ), ...this._storageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ), }); @@ -265,21 +264,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, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); if (globalStoredConnections && globalStoredConnections[connectionId]) { delete globalStoredConnections[connectionId]; void this._storageController.update( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, + StorageVariable.globalSavedConnections, globalStoredConnections, - StorageLocation.GLOBAL, + StorageLocation.global, ); } const workspaceStoredConnections = this._storageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); if ( workspaceStoredConnections && @@ -287,21 +286,21 @@ export class ConnectionStorage { ) { delete workspaceStoredConnections[connectionId]; void this._storageController.update( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + StorageVariable.workspaceSavedConnections, workspaceStoredConnections, - StorageLocation.WORKSPACE, + StorageLocation.workspace, ); } } hasSavedConnections(): boolean { const savedWorkspaceConnections = this._storageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); const savedGlobalConnections = this._storageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); return !!( @@ -316,15 +315,15 @@ export class ConnectionStorage { .getConfiguration('mdb.connectionSaving') .get('defaultConnectionSavingLocation'); - if (defaultConnectionSavingLocation === DefaultSavingLocations.Workspace) { - return StorageLocation.WORKSPACE; + if (defaultConnectionSavingLocation === DefaultSavingLocation.workspace) { + return StorageLocation.workspace; } - if (defaultConnectionSavingLocation === DefaultSavingLocations.Global) { - return StorageLocation.GLOBAL; + if (defaultConnectionSavingLocation === DefaultSavingLocation.global) { + return StorageLocation.global; } - return StorageLocation.NONE; + return StorageLocation.none; } getUserAnonymousId(): string { diff --git a/src/storage/index.ts b/src/storage/index.ts index 0c0fcf6ff..0517a7856 100644 --- a/src/storage/index.ts +++ b/src/storage/index.ts @@ -1,3 +1,6 @@ -import StorageController, { StorageVariables } from './storageController'; +import StorageController, { + StorageVariable, + StorageLocation, +} from './storageController'; -export { StorageController, StorageVariables }; +export { StorageController, StorageVariable, StorageLocation }; diff --git a/src/storage/storageController.ts b/src/storage/storageController.ts index 5d0d389fc..21c1528e6 100644 --- a/src/storage/storageController.ts +++ b/src/storage/storageController.ts @@ -3,31 +3,40 @@ import { v4 as uuidv4 } from 'uuid'; import type { StoreConnectionInfo } from './connectionStorage'; -export enum StorageVariables { +export const StorageVariable = { // Only exists on globalState. - GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW = 'GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW', - GLOBAL_SAVED_CONNECTIONS = 'GLOBAL_SAVED_CONNECTIONS', + globalHasBeenShownInitialView: 'GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW', + globalSavedConnections: 'GLOBAL_SAVED_CONNECTIONS', // Analytics user identify. - GLOBAL_USER_ID = 'GLOBAL_USER_ID', - GLOBAL_ANONYMOUS_ID = 'GLOBAL_ANONYMOUS_ID', + globalUserId: 'GLOBAL_USER_ID', + globalAnonymousId: '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', -} + workspaceSavedConnections: 'WORKSPACE_SAVED_CONNECTIONS', + copilotHasBeenShownWelcomeMessage: 'COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE', +} as const; + +export type StorageVariable = + (typeof StorageVariable)[keyof typeof StorageVariable]; // Typically variables default to 'GLOBAL' scope. -export enum StorageLocation { - GLOBAL = 'GLOBAL', - WORKSPACE = 'WORKSPACE', - NONE = 'NONE', -} +export const StorageLocation = { + global: 'GLOBAL', + workspace: 'WORKSPACE', + none: 'NONE', +} as const; + +export type StorageLocation = + (typeof StorageLocation)[keyof typeof StorageLocation]; // Coupled with the `defaultConnectionSavingLocation` configuration in `package.json`. -export enum DefaultSavingLocations { - 'Workspace' = 'Workspace', - 'Global' = 'Global', - 'Session Only' = 'Session Only', -} +export const DefaultSavingLocation = { + workspace: 'Workspace', + global: 'Global', + sessionOnly: 'Session Only', +} as const; + +export type DefaultSavingLocation = + (typeof DefaultSavingLocation)[keyof typeof DefaultSavingLocation]; export type ConnectionsFromStorage = { [connectionId: string]: StoreConnectionInfo; @@ -42,41 +51,39 @@ export const SecretStorageLocation = { SecretStorage: 'vscode.SecretStorage', } as const; -export type SecretStorageLocationType = - | typeof SecretStorageLocation.Keytar - | typeof SecretStorageLocation.KeytarSecondAttempt - | typeof SecretStorageLocation.SecretStorage; +export type SecretStorageLocation = + (typeof SecretStorageLocation)[keyof typeof SecretStorageLocation]; 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; + [StorageVariable.globalUserId]: string; + [StorageVariable.globalAnonymousId]: string; + [StorageVariable.globalHasBeenShownInitialView]: boolean; + [StorageVariable.globalSavedConnections]: ConnectionsFromStorage; + [StorageVariable.workspaceSavedConnections]: ConnectionsFromStorage; + [StorageVariable.copilotHasBeenShownWelcomeMessage]: boolean; } type StoredVariableName = keyof StorageVariableContents; type StoredItem = StorageVariableContents[T]; export default class StorageController { _storage: { - [StorageLocation.GLOBAL]: vscode.Memento; - [StorageLocation.WORKSPACE]: vscode.Memento; + [StorageLocation.global]: vscode.Memento; + [StorageLocation.workspace]: vscode.Memento; }; _secretStorage: vscode.SecretStorage; constructor(context: vscode.ExtensionContext) { this._storage = { - [StorageLocation.GLOBAL]: context.globalState, - [StorageLocation.WORKSPACE]: context.workspaceState, + [StorageLocation.global]: context.globalState, + [StorageLocation.workspace]: context.workspaceState, }; this._secretStorage = context.secrets; } get( variableName: T, - storageLocation: StorageLocation = StorageLocation.GLOBAL, + storageLocation: StorageLocation = StorageLocation.global, ): StoredItem { return this._storage[storageLocation].get(variableName); } @@ -85,19 +92,19 @@ export default class StorageController { update( variableName: T, value: StoredItem, - storageLocation: StorageLocation = StorageLocation.GLOBAL, + storageLocation: StorageLocation = StorageLocation.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(StorageVariable.globalAnonymousId); // The anonymousId becomes required with analytics-node v6. if (!anonymousId) { anonymousId = uuidv4(); - void this.update(StorageVariables.GLOBAL_ANONYMOUS_ID, anonymousId); + void this.update(StorageVariable.globalAnonymousId, anonymousId); } return { anonymousId }; diff --git a/src/telemetry/connectionTelemetry.ts b/src/telemetry/connectionTelemetry.ts index 14ad8681f..9a0cff217 100644 --- a/src/telemetry/connectionTelemetry.ts +++ b/src/telemetry/connectionTelemetry.ts @@ -1,9 +1,9 @@ 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 { ConnectionType, type ConnectionTypes } from '../connectionController'; const log = createLogger('connection telemetry helper'); // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -123,10 +123,9 @@ export async function getConnectionTelemetryProperties( connectionType: ConnectionTypes, ): Promise { let preparedProperties: NewConnectionTelemetryEventProperties = { - is_used_connect_screen: connectionType === ConnectionTypes.CONNECTION_FORM, - is_used_command_palette: - connectionType === ConnectionTypes.CONNECTION_STRING, - is_used_saved_connection: connectionType === ConnectionTypes.CONNECTION_ID, + is_used_connect_screen: connectionType === ConnectionType.connectionForm, + is_used_command_palette: connectionType === ConnectionType.connectionString, + is_used_saved_connection: connectionType === ConnectionType.connectionId, vscode_mdb_extension_version: version, }; diff --git a/src/telemetry/telemetryEvents.ts b/src/telemetry/telemetryEvents.ts index cfe9a23b3..efd0b74d6 100644 --- a/src/telemetry/telemetryEvents.ts +++ b/src/telemetry/telemetryEvents.ts @@ -3,7 +3,7 @@ import type { DocumentSourceDetails } from '../documentSource'; import { DocumentSource } from '../documentSource'; import type { ExportToPlaygroundError, - ParticipantErrorTypes, + ParticipantErrorType, } from '../participant/participantErrorTypes'; import type { ParticipantCommandType, @@ -332,7 +332,7 @@ export class SavedConnectionsLoadedTelemetryEvent connections_with_secrets_in_keytar: number; /** Total number of connections that have secrets stored in secret storage */ - connections_with_secrets_in_secret_storage: number; + connections_with_secrets_in_SecretStorage: number; }; constructor({ @@ -353,7 +353,7 @@ export class SavedConnectionsLoadedTelemetryEvent preset_connections: presetConnections, loaded_connections: loadedConnections, connections_with_secrets_in_keytar: connectionsWithSecretsInKeytar, - connections_with_secrets_in_secret_storage: + connections_with_secrets_in_SecretStorage: connectionsWithSecretsInSecretStorage, }; } @@ -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: DocumentSource.treeview, source_details: sourceDetails, }; } diff --git a/src/telemetry/telemetryService.ts b/src/telemetry/telemetryService.ts index 12ecc5b89..c1bf8a584 100644 --- a/src/telemetry/telemetryService.ts +++ b/src/telemetry/telemetryService.ts @@ -10,7 +10,7 @@ import type { ConnectionTypes } from '../connectionController'; import { createLogger } from '../logging'; import { getConnectionTelemetryProperties } from './connectionTelemetry'; import type { StorageController } from '../storage'; -import { ParticipantErrorTypes } from '../participant/participantErrorTypes'; +import { ParticipantErrorType } from '../participant/participantErrorTypes'; import type { ParticipantResponseType } from '../participant/participantTypes'; import type { TelemetryEvent } from './telemetryEvents'; import { @@ -197,7 +197,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 @@ -214,13 +214,13 @@ export class TelemetryService { const message: string = err.message || err.toString(); if (message.includes('off_topic')) { - errorName = ParticipantErrorTypes.CHAT_MODEL_OFF_TOPIC; + errorName = ParticipantErrorType.chatModelOffTopic; } else if (message.includes('Filtered by Responsible AI Service')) { - errorName = ParticipantErrorTypes.FILTERED; + errorName = ParticipantErrorType.filtered; } else if (message.includes('Prompt failed validation')) { - errorName = ParticipantErrorTypes.INVALID_PROMPT; + errorName = ParticipantErrorType.invalidPrompt; } else { - errorName = ParticipantErrorTypes.OTHER; + errorName = ParticipantErrorType.other; } this.track( diff --git a/src/test/suite/connectionController.test.ts b/src/test/suite/connectionController.test.ts index 0d4f5dc6c..35c927c62 100644 --- a/src/test/suite/connectionController.test.ts +++ b/src/test/suite/connectionController.test.ts @@ -8,14 +8,17 @@ import { expect } from 'chai'; import ConnectionString from 'mongodb-connection-string-url'; import ConnectionController, { - ConnectionTypes, + ConnectionType, getNotifyDeviceFlowForConnectionAttempt, } from '../../connectionController'; import formatError from '../../utils/formatError'; -import { StorageController, StorageVariables } from '../../storage'; import { + StorageController, + StorageVariable, StorageLocation, - DefaultSavingLocations, +} from '../../storage'; +import { + DefaultSavingLocation, SecretStorageLocation, } from '../../storage/storageController'; import { StatusView } from '../../views'; @@ -269,7 +272,7 @@ suite('Connection Controller Test Suite', function () { ): void => { testConnectionController._connections[id] = { connectionOptions: { connectionString }, - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, name, id, @@ -547,7 +550,7 @@ suite('Connection Controller Test Suite', function () { connectionOptions: { connectionString: 'localhost:3000', }, - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }; @@ -565,7 +568,7 @@ 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', DefaultSavingLocation.global); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); @@ -576,7 +579,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -604,14 +607,14 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.loadSavedConnections(); await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update('defaultConnectionSavingLocation', DefaultSavingLocation.global); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); expect(Object.keys(globalStoreConnections)).to.have.lengthOf(1); @@ -623,7 +626,7 @@ suite('Connection Controller Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + StorageVariable.workspaceSavedConnections, ); expect(workspaceStoreConnections).to.be.undefined; @@ -635,15 +638,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -655,8 +658,8 @@ suite('Connection Controller Test Suite', function () { ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); expect(globalStoreConnections).to.be.undefined; @@ -668,7 +671,7 @@ suite('Connection Controller Test Suite', function () { id: '25', name: 'tester', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }, }; @@ -686,15 +689,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -748,7 +751,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations['Session Only'], + DefaultSavingLocation.sessionOnly, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -756,15 +759,15 @@ suite('Connection Controller Test Suite', function () { const objectString = JSON.stringify(undefined); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); expect(JSON.stringify(globalStoreConnections)).to.equal(objectString); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(JSON.stringify(workspaceStoreConnections)).to.equal(objectString); @@ -809,15 +812,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -829,8 +832,8 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.removeSavedConnection(connectionId); const postWorkspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(Object.keys(postWorkspaceStoreConnections)).to.have.lengthOf(0); @@ -840,14 +843,14 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.loadSavedConnections(); await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update('defaultConnectionSavingLocation', DefaultSavingLocation.global); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); expect(Object.keys(globalStoreConnections)).to.have.lengthOf(1); @@ -857,8 +860,8 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.removeSavedConnection(connectionId); const postGlobalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); expect(Object.keys(postGlobalStoreConnections)).to.have.lengthOf(0); @@ -885,15 +888,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -933,15 +936,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -1009,7 +1012,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -1079,7 +1082,7 @@ suite('Connection Controller Test Suite', function () { id, name: `test${i}`, connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }; } @@ -1141,7 +1144,7 @@ suite('Connection Controller Test Suite', function () { id: connectionId, name: 'asdfasdg', connectionOptions: { connectionString: testDatabaseURI2WithTimeout }, - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }; @@ -1165,7 +1168,7 @@ suite('Connection Controller Test Suite', function () { id: connectionId, name: 'asdfasdg', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }; @@ -1196,7 +1199,7 @@ suite('Connection Controller Test Suite', function () { const connectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: StorageLocation.GLOBAL, + storageLocation: StorageLocation.global, secretStorageLocation: SecretStorageLocation.SecretStorage, connectionOptions: { connectionString: @@ -1357,8 +1360,8 @@ suite('Connection Controller Test Suite', function () { }; testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === StorageLocation.WORKSPACE || - key === StorageVariables.WORKSPACE_SAVED_CONNECTIONS + storage === StorageLocation.workspace || + key === StorageVariable.workspaceSavedConnections ) { return {}; } @@ -1412,8 +1415,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 === StorageLocation.workspace || + key === StorageVariable.workspaceSavedConnections ) { return {}; } @@ -1479,7 +1482,7 @@ suite('Connection Controller Test Suite', function () { expect(trackStub.lastCall.args).to.deep.equal([ { connections_with_secrets_in_keytar: 2, - connections_with_secrets_in_secret_storage: 2, + connections_with_secrets_in_SecretStorage: 2, saved_connections: 4, loaded_connections: 4, }, @@ -1557,14 +1560,14 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Global, + DefaultSavingLocation.global, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI_USER, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, + StorageVariable.globalSavedConnections, ); expect(workspaceStoreConnections).to.not.be.empty; @@ -1687,7 +1690,7 @@ suite('Connection Controller Test Suite', function () { }); expect(fakeConnect).to.have.been.calledWith( connections[0].id, - ConnectionTypes.CONNECTION_ID, + ConnectionType.connectionId, ); 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..4425610bd 100644 --- a/src/test/suite/editors/collectionDocumentsProvider.test.ts +++ b/src/test/suite/editors/collectionDocumentsProvider.test.ts @@ -3,7 +3,6 @@ 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 CollectionDocumentsOperationsStore from '../../../editors/collectionDocumentsOperationsStore'; import CollectionDocumentsProvider, { @@ -288,7 +287,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!firstCollectionFirstCommandArguments); assert( firstCollectionFirstCommandArguments[0].source === - DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + DocumentSource.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, + DocumentSource.collectionview, ); assert( secondCollectionFirstCommandArguments[0].namespace === @@ -419,14 +418,14 @@ suite('Collection Documents Provider Test Suite', () => { id: firstConnectionId, name: 'localhost', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }, [secondConnectionId]: { id: secondConnectionId, name: 'compass', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }, }; @@ -477,7 +476,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!firstCollectionFirstCommandArguments); assert( firstCollectionFirstCommandArguments[0].source === - DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + DocumentSource.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, + DocumentSource.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..fd12e2433 100644 --- a/src/test/suite/editors/editDocumentCodeLensProvider.test.ts +++ b/src/test/suite/editors/editDocumentCodeLensProvider.test.ts @@ -56,7 +56,7 @@ suite('Edit Document Code Lens Provider Test Suite', () => { }, ], namespace: 'db.coll', - source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND, + source: DocumentSource.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: DocumentSource.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..924c92708 100644 --- a/src/test/suite/editors/mongoDBDocumentService.test.ts +++ b/src/test/suite/editors/mongoDBDocumentService.test.ts @@ -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 = DocumentSource.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 = DocumentSource.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 = DocumentSource.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 = DocumentSource.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 = DocumentSource.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 = DocumentSource.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 = DocumentSource.playground; const fakeGetActiveConnectionId = sandbox.fake.returns('345'); sandbox.replace( diff --git a/src/test/suite/editors/queryWithCopilotCodeLensProvider.test.ts b/src/test/suite/editors/queryWithCopilotCodeLensProvider.test.ts index 65c7231e6..3c00847b0 100644 --- a/src/test/suite/editors/queryWithCopilotCodeLensProvider.test.ts +++ b/src/test/suite/editors/queryWithCopilotCodeLensProvider.test.ts @@ -4,7 +4,7 @@ import { expect } from 'chai'; import sinon from 'sinon'; import path from 'path'; import { QueryWithCopilotCodeLensProvider } from '../../../editors/queryWithCopilotCodeLensProvider'; -import EXTENSION_COMMANDS from '../../../commands'; +import ExtensionCommand from '../../../commands'; suite('Query with Copilot CodeLens Provider Test Suite', () => { let testCodeLensProvider: QueryWithCopilotCodeLensProvider; @@ -77,7 +77,7 @@ suite('Query with Copilot CodeLens Provider Test Suite', () => { expect(codeLens[0].range.start.line).to.be.equal(0); expect(codeLens[0].range.end.line).to.be.equal(0); expect(codeLens[0].command?.command).to.be.equal( - EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, + ExtensionCommand.sendMessageToParticipantFromInput, ); }); }); diff --git a/src/test/suite/explorer/collectionTreeItem.test.ts b/src/test/suite/explorer/collectionTreeItem.test.ts index b90d5caa8..a550f53c4 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 { CollectionType } 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: CollectionType.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: CollectionType.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: CollectionType.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: CollectionType.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: CollectionType.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..d753ac8c0 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, + CollectionType, 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: CollectionType.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: CollectionType.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: CollectionType.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: CollectionType.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..ea9462e70 100644 --- a/src/test/suite/explorer/explorerController.test.ts +++ b/src/test/suite/explorer/explorerController.test.ts @@ -6,7 +6,7 @@ import { connect, createConnectionAttempt } from 'mongodb-data-service'; import { mongoLogId } from 'mongodb-log-writer'; import { - DefaultSavingLocations, + DefaultSavingLocation, SecretStorageLocation, StorageLocation, } from '../../../storage/storageController'; @@ -31,7 +31,7 @@ suite('Explorer Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations['Session Only'], + DefaultSavingLocation.sessionOnly, ); 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, + DefaultSavingLocation.workspace, ); // Reset our connections. await mdbTestExtension.testExtensionController._connectionController.disconnect(); @@ -68,7 +68,7 @@ suite('Explorer Controller Test Suite', function () { id: 'testConnectionId', connectionOptions: { connectionString: 'mongodb://localhost' }, name: 'testConnectionName', - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }, }; @@ -213,7 +213,7 @@ suite('Explorer Controller Test Suite', function () { testConnectionController._connections[connectionId].connectionOptions, name: 'aaa', id: 'aaa', - storageLocation: StorageLocation.WORKSPACE, + storageLocation: StorageLocation.workspace, secretStorageLocation: SecretStorageLocation.SecretStorage, }; @@ -222,7 +222,7 @@ suite('Explorer Controller Test Suite', function () { testConnectionController._connections[connectionId].connectionOptions, name: 'zzz', id: 'zzz', - storageLocation: StorageLocation.WORKSPACE, + storageLocation: StorageLocation.workspace, secretStorageLocation: SecretStorageLocation.SecretStorage, }; diff --git a/src/test/suite/explorer/indexTreeItem.test.ts b/src/test/suite/explorer/indexTreeItem.test.ts index c440ca33e..13692e462 100644 --- a/src/test/suite/explorer/indexTreeItem.test.ts +++ b/src/test/suite/explorer/indexTreeItem.test.ts @@ -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: IndexKeyType.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/extension.test.ts b/src/test/suite/extension.test.ts index a321d58b9..442193bfc 100644 --- a/src/test/suite/extension.test.ts +++ b/src/test/suite/extension.test.ts @@ -1,6 +1,6 @@ import assert from 'assert'; import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../../commands'; +import ExtensionCommand from '../../commands'; // eslint-disable-next-line @typescript-eslint/no-var-requires const { contributes } = require('../../../package.json'); @@ -63,7 +63,7 @@ suite('Extension Test Suite', () => { // Editor commands. 'mdb.codeLens.showMoreDocumentsClicked', - ...Object.values(EXTENSION_COMMANDS), + ...Object.values(ExtensionCommand), ]; for (const expectedCommand of expectedCommands) { diff --git a/src/test/suite/language/mongoDBService.test.ts b/src/test/suite/language/mongoDBService.test.ts index 95339be6d..129b1290b 100644 --- a/src/test/suite/language/mongoDBService.test.ts +++ b/src/test/suite/language/mongoDBService.test.ts @@ -21,8 +21,8 @@ import MongoDBService, { } from '../../../language/mongoDBService'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { StreamStub } from '../stubs'; -import DIAGNOSTIC_CODES from '../../../language/diagnosticCodes'; -import { ServerCommands } from '../../../language/serverCommands'; +import DiagnosticCode from '../../../language/diagnosticCodes'; +import { ServerCommand } 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(ServerCommand.showConsoleOutput) .callsFake((_, params) => Promise.resolve(void consoleOutputs.push(...params)), ); @@ -3105,7 +3105,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 3 }, @@ -3124,7 +3124,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 8 }, @@ -3143,7 +3143,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 8 }, @@ -3162,7 +3162,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 10 }, @@ -3181,7 +3181,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 10 }, @@ -3200,7 +3200,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 14 }, @@ -3219,7 +3219,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 8 }, @@ -3238,7 +3238,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 16 }, @@ -3257,7 +3257,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 11 }, @@ -3276,7 +3276,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 12 }, @@ -3295,7 +3295,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 10 }, @@ -3314,7 +3314,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 10 }, @@ -3333,7 +3333,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 9 }, @@ -3352,7 +3352,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 8 }, @@ -3371,7 +3371,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 8 }, @@ -3390,7 +3390,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 17 }, @@ -3409,7 +3409,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 26 }, 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 2a94e05f5..bf81d92a4 100644 --- a/src/test/suite/mdbExtensionController.test.ts +++ b/src/test/suite/mdbExtensionController.test.ts @@ -9,27 +9,27 @@ import type { Document, Filter } from 'mongodb'; import { CollectionTreeItem, - CollectionTypes, ConnectionTreeItem, DatabaseTreeItem, DocumentTreeItem, SchemaTreeItem, StreamProcessorTreeItem, } from '../../explorer'; -import EXTENSION_COMMANDS from '../../commands'; +import { ExtensionCommand } from '../../commands'; import FieldTreeItem from '../../explorer/fieldTreeItem'; import IndexListTreeItem from '../../explorer/indexListTreeItem'; import { mdbTestExtension } from './stubbableMdbExtension'; import { mockTextEditor } from './stubs'; import { - SecretStorageLocation, StorageLocation, - StorageVariables, + SecretStorageLocation, + StorageVariable, } 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 { CollectionType } from '../../explorer/documentListTreeItem'; import { DEEP_LINK_ALLOWED_COMMANDS, DEEP_LINK_DISALLOWED_COMMANDS, @@ -59,7 +59,7 @@ function getTestCollectionTreeItem( return new CollectionTreeItem({ collection: { name: 'testColName', - type: CollectionTypes.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, databaseName: 'testDbName', dataService: {} as DataService, @@ -145,10 +145,10 @@ suite('MDBExtensionController Test Suite', function () { suite('Deep link command lists validation', () => { test('allowed and disallowed lists are disjoint', () => { const allowedSet = new Set( - DEEP_LINK_ALLOWED_COMMANDS as readonly EXTENSION_COMMANDS[], + DEEP_LINK_ALLOWED_COMMANDS as readonly ExtensionCommand[], ); const disallowedSet = new Set( - DEEP_LINK_DISALLOWED_COMMANDS as readonly EXTENSION_COMMANDS[], + DEEP_LINK_DISALLOWED_COMMANDS as readonly ExtensionCommand[], ); const overlap = [...allowedSet].filter((cmd) => disallowedSet.has(cmd)); @@ -160,12 +160,12 @@ suite('MDBExtensionController Test Suite', function () { }); test('allowed and disallowed lists are complete', () => { - const allCommands = new Set(Object.values(EXTENSION_COMMANDS)); + const allCommands = new Set(Object.values(ExtensionCommand)); const allowedSet = new Set( - DEEP_LINK_ALLOWED_COMMANDS as readonly EXTENSION_COMMANDS[], + DEEP_LINK_ALLOWED_COMMANDS as readonly ExtensionCommand[], ); const disallowedSet = new Set( - DEEP_LINK_DISALLOWED_COMMANDS as readonly EXTENSION_COMMANDS[], + DEEP_LINK_DISALLOWED_COMMANDS as readonly ExtensionCommand[], ); const combinedSet = new Set([...allowedSet, ...disallowedSet]); @@ -178,7 +178,7 @@ suite('MDBExtensionController Test Suite', function () { ); expect(extra).to.deep.equal( [], - `Commands in allowed/disallowed lists but not in EXTENSION_COMMANDS: ${extra.join(', ')}`, + `Commands in allowed/disallowed lists but not in ExtensionCommand: ${extra.join(', ')}`, ); }); }); @@ -764,7 +764,7 @@ suite('MDBExtensionController Test Suite', function () { const testCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'doesntExistColName', - type: CollectionTypes.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, dataService: testConnectionController.getActiveDataService() ?? undefined, @@ -795,7 +795,7 @@ suite('MDBExtensionController Test Suite', function () { const testCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'orange', - type: CollectionTypes.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, }); const inputBoxResolvesStub = sandbox.stub(); @@ -904,7 +904,7 @@ suite('MDBExtensionController Test Suite', function () { id: 'blueBerryPancakesAndTheSmellOfBacon', connectionOptions: { connectionString: 'mongodb://localhost' }, name: 'NAAAME', - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }; @@ -935,7 +935,7 @@ suite('MDBExtensionController Test Suite', function () { id: 'blueBerryPancakesAndTheSmellOfBacon', name: 'NAAAME', connectionOptions: { connectionString: 'mongodb://localhost' }, - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.SecretStorage, }; @@ -1357,7 +1357,7 @@ suite('MDBExtensionController Test Suite', function () { const collectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'pineapple', - type: CollectionTypes.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, databaseName: 'plants', }); @@ -1682,7 +1682,7 @@ suite('MDBExtensionController Test Suite', function () { ); assert.strictEqual( executeCommandStub.firstCall.args[0], - EXTENSION_COMMANDS.MDB_OPEN_OVERVIEW_PAGE, + ExtensionCommand.mdbOpenOverviewPage, ); }); @@ -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, + StorageVariable.globalHasBeenShownInitialView, ); assert.strictEqual( fakeUpdate.firstCall.args[0], @@ -1735,7 +1735,7 @@ suite('MDBExtensionController Test Suite', function () { assert(fakeUpdate.called); assert.strictEqual( fakeUpdate.firstCall.args[0], - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + StorageVariable.globalHasBeenShownInitialView, ); 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..574fac328 100644 --- a/src/test/suite/participant/participant.test.ts +++ b/src/test/suite/participant/participant.test.ts @@ -32,9 +32,9 @@ import { getFullRange } from '../suggestTestHelpers'; import { isPlayground } from '../../../utils/playground'; import { Prompts } from '../../../participant/prompts'; import { createMarkdownLink } from '../../../participant/markdown'; -import EXTENSION_COMMANDS from '../../../commands'; +import ExtensionCommand from '../../../commands'; import { getContentLength } from '../../../participant/prompts/promptBase'; -import { ParticipantErrorTypes } from '../../../participant/participantErrorTypes'; +import { ParticipantErrorType } 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 { DocumentSource } from '../../../documentSource'; // The Copilot's model in not available in tests, // therefore we need to mock its methods and returning values. @@ -57,7 +57,7 @@ const MAX_TOTAL_PROMPT_LENGTH_MOCK = 16000; const loadedConnection = { id: 'id', name: 'localhost', - storageLocation: StorageLocation.NONE, + storageLocation: StorageLocation.none, secretStorageLocation: SecretStorageLocation.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: DocumentSource.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: DocumentSource.treeview, source_details: 'collection', }, }, @@ -2566,12 +2566,12 @@ Schema: `Looks like you aren't currently connected, first let's get you connected to the cluster we'd like to create this query to run against. ${createMarkdownLink({ - commandId: EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, + commandId: ExtensionCommand.connectWithParticipant, name: 'localhost', data: {}, })} ${createMarkdownLink({ - commandId: EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, + commandId: ExtensionCommand.connectWithParticipant, name: 'atlas', data: {}, })}`, @@ -2638,7 +2638,7 @@ Schema: createChatResponseTurn('/query', undefined, { result: { errorDetails: { - message: ParticipantErrorTypes.FILTERED, + message: ParticipantErrorType.filtered, }, metadata: {}, }, diff --git a/src/test/suite/storage/connectionStorage.test.ts b/src/test/suite/storage/connectionStorage.test.ts index d2338b449..28e866d4e 100644 --- a/src/test/suite/storage/connectionStorage.test.ts +++ b/src/test/suite/storage/connectionStorage.test.ts @@ -3,10 +3,13 @@ import * as vscode from 'vscode'; import { afterEach, beforeEach } from 'mocha'; import { expect } from 'chai'; -import { StorageController, StorageVariables } from '../../../storage'; import { + StorageController, + StorageVariable, StorageLocation, - DefaultSavingLocations, +} from '../../../storage'; +import { + DefaultSavingLocation, SecretStorageLocation, } from '../../../storage/storageController'; import { ExtensionContextStub } from '../stubs'; @@ -66,7 +69,7 @@ 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', DefaultSavingLocation.global); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), @@ -78,7 +81,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); await testConnectionStorage.saveConnection( @@ -104,15 +107,15 @@ 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', DefaultSavingLocation.global); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); expect(Object.keys(globalStoreConnections).length).to.equal(1); @@ -124,7 +127,7 @@ suite('Connection Storage Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + StorageVariable.workspaceSavedConnections, ); expect(workspaceStoreConnections).to.equal(undefined); @@ -135,15 +138,15 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(Object.keys(workspaceStoreConnections).length).to.equal(1); @@ -155,8 +158,8 @@ suite('Connection Storage Test Suite', function () { ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); expect(globalStoreConnections).to.equal(undefined); @@ -168,7 +171,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations['Session Only'], + DefaultSavingLocation.sessionOnly, ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), @@ -176,15 +179,15 @@ suite('Connection Storage Test Suite', function () { const objectString = JSON.stringify(undefined); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); expect(JSON.stringify(globalStoreConnections)).to.equal(objectString); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(JSON.stringify(workspaceStoreConnections)).to.equal(objectString); @@ -195,7 +198,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); const connectionId = 'pie'; await testConnectionStorage.saveConnection( @@ -203,8 +206,8 @@ suite('Connection Storage Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(Object.keys(workspaceStoreConnections).length).to.equal(1); @@ -212,8 +215,8 @@ suite('Connection Storage Test Suite', function () { await testConnectionStorage.removeConnection(connectionId); const postWorkspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.workspace, ); expect(Object.keys(postWorkspaceStoreConnections).length).to.equal(0); }); @@ -221,15 +224,15 @@ 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', DefaultSavingLocation.global); const connectionId = 'pineapple'; await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, connectionId), ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); expect(Object.keys(globalStoreConnections).length).to.equal(1); @@ -237,8 +240,8 @@ suite('Connection Storage Test Suite', function () { await testConnectionStorage.removeConnection(connectionId); const postGlobalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.global, ); expect(Object.keys(postGlobalStoreConnections).length).to.equal(0); @@ -263,7 +266,7 @@ suite('Connection Storage Test Suite', function () { const oldSavedConnectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: StorageLocation.GLOBAL, + storageLocation: StorageLocation.global, connectionModel: { _id: '4', isFavorite: false, @@ -295,7 +298,7 @@ suite('Connection Storage Test Suite', function () { const connectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: StorageLocation.GLOBAL, + storageLocation: StorageLocation.global, secretStorageLocation: SecretStorageLocation.SecretStorage, connectionOptions: { connectionString: @@ -499,8 +502,8 @@ suite('Connection Storage Test Suite', function () { }; testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === StorageLocation.WORKSPACE || - key === StorageVariables.WORKSPACE_SAVED_CONNECTIONS + storage === StorageLocation.workspace || + key === StorageVariable.workspaceSavedConnections ) { return {}; } @@ -552,7 +555,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DefaultSavingLocation.workspace, ); await testConnectionStorage.saveConnection( diff --git a/src/test/suite/storage/storageController.test.ts b/src/test/suite/storage/storageController.test.ts index 6d0c4f20c..7573843e8 100644 --- a/src/test/suite/storage/storageController.test.ts +++ b/src/test/suite/storage/storageController.test.ts @@ -1,7 +1,7 @@ import assert from 'assert'; import StorageController, { - StorageVariables, + StorageVariable, StorageLocation, } 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]: { + [StorageVariable.globalSavedConnections]: { collOne: { name: 'this_gonna_get_saved' }, }, }; const testStorageController = new StorageController(extensionContextStub); const testVal = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + StorageVariable.globalSavedConnections, + StorageLocation.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]: { + [StorageVariable.workspaceSavedConnections]: { collTwo: { name: 'i_cant_believe_its_gonna_save_this' }, }, }; const testStorageController = new StorageController(extensionContextStub); const testVal = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + StorageVariable.workspaceSavedConnections, + StorageLocation.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, + StorageVariable.globalAnonymousId, ); 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..e463571c8 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 { ConnectionType } 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, + ConnectionType.connectionForm, ); 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, + ConnectionType.connectionForm, ); 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, + ConnectionType.connectionForm, ); 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, + ConnectionType.connectionForm, ); 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, + ConnectionType.connectionForm, ); 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, + ConnectionType.connectionForm, ); 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, + ConnectionType.connectionString, ); 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, + ConnectionType.connectionForm, ); 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, + ConnectionType.connectionString, ); 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, + ConnectionType.connectionId, ); 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, + ConnectionType.connectionString, ); 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, + ConnectionType.connectionString, ); 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, + ConnectionType.connectionString, ); 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, + ConnectionType.connectionString, ); 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, + ConnectionType.connectionString, ); 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, + ConnectionType.connectionString, ); 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, + ConnectionType.connectionString, ); 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, + ConnectionType.connectionString, ); 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 07b325dc4..3867fef63 100644 --- a/src/test/suite/telemetry/telemetryService.test.ts +++ b/src/test/suite/telemetry/telemetryService.test.ts @@ -9,7 +9,6 @@ import sinon from 'sinon'; import type { SinonSpy } from 'sinon'; import sinonChai from 'sinon-chai'; -import { ConnectionTypes } from '../../../connectionController'; import { DocumentSource } from '../../../documentSource'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { DatabaseTreeItem, DocumentTreeItem } from '../../../explorer'; @@ -25,6 +24,7 @@ import { SavedConnectionsLoadedTelemetryEvent, } from '../../../telemetry'; import type { SegmentProperties } from '../../../telemetry/telemetryService'; +import { ConnectionType } from '../../../connectionController'; // eslint-disable-next-line @typescript-eslint/no-var-requires const { version } = require('../../../../package.json'); @@ -157,7 +157,7 @@ suite('Telemetry Controller Test Suite', () => { test('track new connection event when connecting via connection string', async () => { await testTelemetryService.trackNewConnection( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + ConnectionType.connectionString, ); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -178,7 +178,7 @@ suite('Telemetry Controller Test Suite', () => { test('track new connection event when connecting via connection form', async () => { await testTelemetryService.trackNewConnection( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + ConnectionType.connectionForm, ); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -199,7 +199,7 @@ suite('Telemetry Controller Test Suite', () => { test('track new connection event when connecting via saved connection', async () => { await testTelemetryService.trackNewConnection( dataServiceStub, - ConnectionTypes.CONNECTION_ID, + ConnectionType.connectionId, ); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -218,7 +218,7 @@ suite('Telemetry Controller Test Suite', () => { }); test('track document saved form a tree-view event', () => { - const source = DocumentSource.DOCUMENT_SOURCE_TREEVIEW; + const source = DocumentSource.treeview; testTelemetryService.track( new DocumentUpdatedTelemetryEvent(source, true), ); @@ -237,7 +237,7 @@ suite('Telemetry Controller Test Suite', () => { }); test('track document opened form playground results', () => { - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DocumentSource.playground; testTelemetryService.track(new DocumentEditedTelemetryEvent(source)); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -556,7 +556,7 @@ suite('Telemetry Controller Test Suite', () => { loaded_connections: 3, preset_connections: 3, connections_with_secrets_in_keytar: 0, - connections_with_secrets_in_secret_storage: 3, + connections_with_secrets_in_SecretStorage: 3, }, }), ); diff --git a/src/test/suite/views/webview-app/atlas-cta.test.tsx b/src/test/suite/views/webview-app/atlas-cta.test.tsx index f6e4cf40b..93ff0cf4c 100644 --- a/src/test/suite/views/webview-app/atlas-cta.test.tsx +++ b/src/test/suite/views/webview-app/atlas-cta.test.tsx @@ -4,7 +4,7 @@ import AtlasCta from '../../../../views/webview-app/atlas-cta'; import { expect } from 'chai'; import Sinon from 'sinon'; import vscode from '../../../../views/webview-app/vscode-api'; -import { MESSAGE_TYPES } from '../../../../views/webview-app/extension-app-message-constants'; +import { MessageType } from '../../../../views/webview-app/extension-app-message-constants'; describe('AtlasCta test suite', function () { afterEach(function () { @@ -23,7 +23,7 @@ describe('AtlasCta test suite', function () { render(); screen.getByTestId('link-atlas').click(); expect(postMessageStub).to.be.calledWithExactly({ - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + command: MessageType.extensionLinkClicked, screen: 'overviewPage', linkId: 'atlasLanding', }); @@ -35,10 +35,10 @@ describe('AtlasCta test suite', function () { screen.getByText('Create free cluster').click(); expect(postMessageStub).calledTwice; expect(postMessageStub.firstCall.args[0].command).to.equal( - MESSAGE_TYPES.OPEN_TRUSTED_LINK, + MessageType.openTrustedLink, ); expect(postMessageStub.secondCall.args[0].command).to.equal( - MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + MessageType.extensionLinkClicked, ); }); }); diff --git a/src/test/suite/views/webview-app/connect-helper.test.tsx b/src/test/suite/views/webview-app/connect-helper.test.tsx index b3318fb20..dfe01f2c9 100644 --- a/src/test/suite/views/webview-app/connect-helper.test.tsx +++ b/src/test/suite/views/webview-app/connect-helper.test.tsx @@ -4,7 +4,7 @@ import { render, screen } from '@testing-library/react'; import ConnectHelper from '../../../../views/webview-app/connect-helper'; import Sinon from 'sinon'; import vscode from '../../../../views/webview-app/vscode-api'; -import { MESSAGE_TYPES } from '../../../../views/webview-app/extension-app-message-constants'; +import { MessageType } from '../../../../views/webview-app/extension-app-message-constants'; describe('ConnectHelper test suite', function () { it('when rendered it should show both connection options', function () { @@ -31,7 +31,7 @@ describe('ConnectHelper test suite', function () { ); screen.getByLabelText('Connect with connection string').click(); expect(postMessageStub).to.have.been.calledWithExactly({ - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT, + command: MessageType.openConnectionStringInput, }); }); }); diff --git a/src/test/suite/views/webview-app/connection-status.test.tsx b/src/test/suite/views/webview-app/connection-status.test.tsx index 85a75bc85..31a8ce0d7 100644 --- a/src/test/suite/views/webview-app/connection-status.test.tsx +++ b/src/test/suite/views/webview-app/connection-status.test.tsx @@ -5,7 +5,7 @@ import { act, cleanup, render, screen } from '@testing-library/react'; import ConnectionStatus from '../../../../views/webview-app/connection-status'; import { CONNECTION_STATUS, - MESSAGE_TYPES, + MessageType, } from '../../../../views/webview-app/extension-app-message-constants'; import vscode from '../../../../views/webview-app/vscode-api'; @@ -24,7 +24,7 @@ describe('ConnectionStatus test suite', function () { const postMessageStub = Sinon.stub(vscode, 'postMessage'); render(); expect(postMessageStub).to.have.been.calledWithExactly({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS, + command: MessageType.getConnectionStatus, }); }); @@ -35,8 +35,8 @@ describe('ConnectionStatus test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, - connectionStatus: CONNECTION_STATUS.DISCONNECTING, + command: MessageType.connectionStatusMessage, + connectionStatus: CONNECTION_STATUS.disconnecting, activeConnectionName: '', }, }), @@ -53,8 +53,8 @@ describe('ConnectionStatus test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, - connectionStatus: CONNECTION_STATUS.DISCONNECTED, + command: MessageType.connectionStatusMessage, + connectionStatus: CONNECTION_STATUS.disconnected, activeConnectionName: '', }, }), @@ -71,8 +71,8 @@ describe('ConnectionStatus test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, - connectionStatus: CONNECTION_STATUS.CONNECTING, + command: MessageType.connectionStatusMessage, + connectionStatus: CONNECTION_STATUS.connecting, activeConnectionName: '', }, }), @@ -89,8 +89,8 @@ describe('ConnectionStatus test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, - connectionStatus: CONNECTION_STATUS.CONNECTED, + command: MessageType.connectionStatusMessage, + connectionStatus: CONNECTION_STATUS.connected, activeConnectionName: 'vscode-connection', }, }), @@ -108,7 +108,7 @@ describe('ConnectionStatus test suite', function () { screen.getByLabelText('Rename connection').click(); expect(postMessageStub).to.be.calledWithExactly({ - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION, + command: MessageType.renameActiveConnection, }); }); @@ -117,7 +117,7 @@ describe('ConnectionStatus test suite', function () { screen.getByLabelText('Create playground').click(); expect(postMessageStub).to.be.calledWithExactly({ - command: MESSAGE_TYPES.CREATE_NEW_PLAYGROUND, + command: MessageType.createNewPlayground, }); }); }); diff --git a/src/test/suite/views/webview-app/overview-page.test.tsx b/src/test/suite/views/webview-app/overview-page.test.tsx index 10901a3a8..11dd512c1 100644 --- a/src/test/suite/views/webview-app/overview-page.test.tsx +++ b/src/test/suite/views/webview-app/overview-page.test.tsx @@ -7,7 +7,7 @@ import userEvent from '@testing-library/user-event'; import OverviewPage from '../../../../views/webview-app/overview-page'; import vscode from '../../../../views/webview-app/vscode-api'; import type { MessageFromWebviewToExtension } from '../../../../views/webview-app/extension-app-message-constants'; -import { MESSAGE_TYPES } from '../../../../views/webview-app/extension-app-message-constants'; +import { MessageType } from '../../../../views/webview-app/extension-app-message-constants'; const connectionFormTestId = 'connection-form-modal'; @@ -55,7 +55,7 @@ describe('OverviewPage test suite', function () { expect(screen.getByTestId(connectionFormTestId)).to.exist; const message = postMessageSpy.firstCall.args[0]; expect(message).to.deep.equal({ - command: MESSAGE_TYPES.CONNECTION_FORM_OPENED, + command: MessageType.connectionFormOpened, }); await userEvent.click(screen.getByLabelText('Close modal')); @@ -72,7 +72,7 @@ describe('OverviewPage test suite', function () { .null; await userEvent.click(screen.getByTestId('connect-button')); const argsWithoutConnectId = postMessageSpy.lastCall.args[0] as any; - expect(argsWithoutConnectId.command).to.equal(MESSAGE_TYPES.CONNECT); + expect(argsWithoutConnectId.command).to.equal(MessageType.connect); expect( argsWithoutConnectId.connectionInfo.connectionOptions.connectionString, ).to.equal('mongodb://localhost:27017'); @@ -90,7 +90,7 @@ describe('OverviewPage test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.connectResult, connectionId, connectionSuccess: false, connectionMessage: 'server not found', @@ -113,7 +113,7 @@ describe('OverviewPage test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.connectResult, connectionId, connectionSuccess: true, connectionMessage: '', @@ -135,7 +135,7 @@ describe('OverviewPage test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.OPEN_EDIT_CONNECTION, + command: MessageType.openEditConnection, connection: { id: 'pear', name: 'pineapple', @@ -160,8 +160,7 @@ describe('OverviewPage test suite', function () { .getCalls() .filter( (call) => - call.args[0].command === - MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT, + call.args[0].command === MessageType.editConnectionAndConnect, ); }; expect(getConnectMessages()).to.have.length(0); @@ -189,7 +188,7 @@ describe('OverviewPage test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.connectResult, connectionId: 1, // different from the attempt id generated by our click connectionSuccess: true, connectionMessage: '', @@ -204,7 +203,7 @@ describe('OverviewPage test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.connectResult, connectionId: 2, // different from the attempt id generated by our click connectionSuccess: false, connectionMessage: 'something bad happened', diff --git a/src/test/suite/views/webview-app/resources-panel.test.tsx b/src/test/suite/views/webview-app/resources-panel.test.tsx index ff8b4e43f..ec0561856 100644 --- a/src/test/suite/views/webview-app/resources-panel.test.tsx +++ b/src/test/suite/views/webview-app/resources-panel.test.tsx @@ -5,7 +5,7 @@ import { cleanup, render, screen } from '@testing-library/react'; import ResourcesPanel, { TELEMETRY_SCREEN_ID, } from '../../../../views/webview-app/resources-panel/panel'; -import { MESSAGE_TYPES } from '../../../../views/webview-app/extension-app-message-constants'; +import { MessageType } from '../../../../views/webview-app/extension-app-message-constants'; import vscode from '../../../../views/webview-app/vscode-api'; describe('Resources panel test suite', function () { @@ -38,7 +38,7 @@ describe('Resources panel test suite', function () { screen.getAllByTestId(/^link-\w+/).forEach((link) => { link.click(); expect(postMessageStub).to.have.been.calledWithExactly({ - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + command: MessageType.extensionLinkClicked, screen: TELEMETRY_SCREEN_ID, linkId: link.getAttribute('data-testid')?.replace('link-', ''), }); @@ -47,7 +47,7 @@ describe('Resources panel test suite', function () { screen.getAllByTestId(/^footer-feature-\w+/).forEach((link) => { link.click(); expect(postMessageStub).to.have.been.calledWithExactly({ - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + command: MessageType.extensionLinkClicked, screen: TELEMETRY_SCREEN_ID, linkId: link .getAttribute('data-testid') @@ -58,7 +58,7 @@ describe('Resources panel test suite', function () { screen.getAllByTestId(/^footer-link-\w+/).forEach((link) => { link.click(); expect(postMessageStub).to.have.been.calledWithExactly({ - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + command: MessageType.extensionLinkClicked, screen: TELEMETRY_SCREEN_ID, linkId: link.getAttribute('data-testid')?.replace('footer-link-', ''), }); diff --git a/src/test/suite/views/webviewController.test.ts b/src/test/suite/views/webviewController.test.ts index a6cdf6ae2..4d108aea0 100644 --- a/src/test/suite/views/webviewController.test.ts +++ b/src/test/suite/views/webviewController.test.ts @@ -7,7 +7,7 @@ import path from 'path'; import ConnectionController from '../../../connectionController'; import { mdbTestExtension } from '../stubbableMdbExtension'; -import { MESSAGE_TYPES } from '../../../views/webview-app/extension-app-message-constants'; +import { MessageType } from '../../../views/webview-app/extension-app-message-constants'; import { StatusView } from '../../../views'; import { StorageController } from '../../../storage'; import { TelemetryService } from '../../../telemetry'; @@ -223,7 +223,7 @@ suite('Webview Test Suite', () => { // Mock a connection call. messageReceived({ - command: MESSAGE_TYPES.CONNECT, + command: MessageType.connect, connectionInfo: { id: 2, connectionOptions: { @@ -264,7 +264,7 @@ suite('Webview Test Suite', () => { // Mock a connection call. messageReceived({ - command: MESSAGE_TYPES.CONNECT, + command: MessageType.connect, connectionInfo: { id: 'pineapple', connectionOptions: { @@ -302,7 +302,7 @@ suite('Webview Test Suite', () => { // Mock a connection call. messageReceived({ - command: MESSAGE_TYPES.CONNECT, + command: MessageType.connect, connectionInfo: { id: 'pineapple', connectionOptions: { @@ -346,7 +346,7 @@ suite('Webview Test Suite', () => { // Mock a connection call. messageReceived({ - command: MESSAGE_TYPES.CONNECT, + command: MessageType.connect, connectionInfo: { id: 'pineapple', connectionOptions: { @@ -384,7 +384,7 @@ suite('Webview Test Suite', () => { ); messageReceived({ - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT, + command: MessageType.openConnectionStringInput, }); await waitFor(() => { @@ -424,7 +424,7 @@ suite('Webview Test Suite', () => { // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS, + command: MessageType.getConnectionStatus, }); }); @@ -459,7 +459,7 @@ suite('Webview Test Suite', () => { .then(() => { // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS, + command: MessageType.getConnectionStatus, }); }); }); @@ -498,7 +498,7 @@ suite('Webview Test Suite', () => { // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION, + command: MessageType.renameActiveConnection, }); expect(mockRenameConnectionOnConnectionController).to.be.calledOnce; @@ -538,7 +538,7 @@ suite('Webview Test Suite', () => { // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT, + command: MessageType.editConnectionAndConnect, connectionInfo: { id: 'pineapple', connectionOptions: { @@ -644,7 +644,7 @@ suite('Webview Test Suite', () => { sandbox.replace(linkHelper, 'openLink', stubOpenLink); messageReceived({ - command: MESSAGE_TYPES.OPEN_TRUSTED_LINK, + command: MessageType.openTrustedLink, linkTo: 'https://mongodb.com/test', }); 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/connection-status.tsx b/src/views/webview-app/connection-status.tsx index 29796bccf..d49f1cec2 100644 --- a/src/views/webview-app/connection-status.tsx +++ b/src/views/webview-app/connection-status.tsx @@ -151,22 +151,22 @@ const ConnectionStatus: React.FC = () => { const { connectionStatus, connectionName } = useConnectionStatus(); return ( <> - {connectionStatus === CONNECTION_STATUS.CONNECTED && ( + {connectionStatus === CONNECTION_STATUS.connected && ( )} - {connectionStatus === CONNECTION_STATUS.DISCONNECTED && ( + {connectionStatus === CONNECTION_STATUS.disconnected && ( Not connected. )} - {connectionStatus === CONNECTION_STATUS.LOADING && ( + {connectionStatus === CONNECTION_STATUS.loading && ( Loading... )} - {connectionStatus === CONNECTION_STATUS.CONNECTING && ( + {connectionStatus === CONNECTION_STATUS.connecting && ( Connecting... )} - {connectionStatus === CONNECTION_STATUS.DISCONNECTING && ( + {connectionStatus === CONNECTION_STATUS.disconnecting && ( Disconnecting... )} diff --git a/src/views/webview-app/extension-app-message-constants.ts b/src/views/webview-app/extension-app-message-constants.ts index 80a197347..110018475 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,47 @@ 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 MessageType = { + connect: 'CONNECT', + cancelConnect: 'CANCEL_CONNECT', + connectResult: 'CONNECT_RESULT', + connectionFormOpened: 'CONNECTION_FORM_OPENED', + openFileChooser: 'OPEN_FILE_CHOOSER', + openFileChooserResult: 'OPEN_FILE_CHOOSER_RESULT', + connectionStatusMessage: 'CONNECTION_STATUS_MESSAGE', + openEditConnection: 'OPEN_EDIT_CONNECTION', + editConnectionAndConnect: 'EDIT_CONNECTION_AND_CONNECT', + extensionLinkClicked: 'EXTENSION_LINK_CLICKED', + createNewPlayground: 'CREATE_NEW_PLAYGROUND', + getConnectionStatus: 'GET_CONNECTION_STATUS', + openConnectionStringInput: 'OPEN_CONNECTION_STRING_INPUT', + openTrustedLink: 'OPEN_TRUSTED_LINK', + renameActiveConnection: 'RENAME_ACTIVE_CONNECTION', + themeChanged: 'THEME_CHANGED', +} as const; + +export type MessageType = (typeof MessageType)[keyof typeof MessageType]; interface BasicWebviewMessage { command: string; } export interface CreateNewPlaygroundMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CREATE_NEW_PLAYGROUND; + command: typeof MessageType.createNewPlayground; } export interface ConnectionFormOpenedMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECTION_FORM_OPENED; + command: typeof MessageType.connectionFormOpened; } export interface ConnectionStatusMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE; - connectionStatus: CONNECTION_STATUS; + command: typeof MessageType.connectionStatusMessage; + connectionStatus: ConnectionStatus; activeConnectionName: string; } export interface OpenEditConnectionMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_EDIT_CONNECTION; + command: typeof MessageType.openEditConnection; connection: { id: string; name: string; @@ -62,7 +67,7 @@ export interface OpenEditConnectionMessage extends BasicWebviewMessage { } export interface EditConnectionAndConnectMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT; + command: typeof MessageType.editConnectionAndConnect; connectionInfo: { id: string; connectionOptions: ConnectionOptions; @@ -70,13 +75,13 @@ export interface EditConnectionAndConnectMessage extends BasicWebviewMessage { } export interface OpenFileChooserMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_FILE_CHOOSER; + command: typeof MessageType.openFileChooser; fileChooserOptions: FileChooserOptions; requestId: string; } export interface ConnectMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECT; + command: typeof MessageType.connect; connectionInfo: { id: string; connectionOptions: ConnectionOptions; @@ -84,11 +89,11 @@ export interface ConnectMessage extends BasicWebviewMessage { } export interface CancelConnectMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CANCEL_CONNECT; + command: typeof MessageType.cancelConnect; } export interface ConnectResultsMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECT_RESULT; + command: typeof MessageType.connectResult; connectionSuccess: boolean; connectionMessage: string; connectionId: string; @@ -99,36 +104,36 @@ export type FileChooserResult = | { canceled: false; filePath?: string }; export interface OpenFileChooserResultMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_FILE_CHOOSER_RESULT; + command: typeof MessageType.openFileChooserResult; fileChooserResult: FileChooserResult; requestId: string; } export interface GetConnectionStatusMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.GET_CONNECTION_STATUS; + command: typeof MessageType.getConnectionStatus; } export interface OpenConnectionStringInputMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT; + command: typeof MessageType.openConnectionStringInput; } export interface LinkClickedMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED; + command: typeof MessageType.extensionLinkClicked; screen: string; linkId: string; } export interface OpenTrustedLinkMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_TRUSTED_LINK; + command: typeof MessageType.openTrustedLink; linkTo: string; } export interface RenameConnectionMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION; + command: typeof MessageType.renameActiveConnection; } export interface ThemeChangedMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.THEME_CHANGED; + command: typeof MessageType.themeChanged; darkMode: boolean; } diff --git a/src/views/webview-app/overview-page.tsx b/src/views/webview-app/overview-page.tsx index 15d1ec47e..88af94921 100644 --- a/src/views/webview-app/overview-page.tsx +++ b/src/views/webview-app/overview-page.tsx @@ -18,11 +18,11 @@ import AtlasCta from './atlas-cta'; import ResourcesPanel from './resources-panel/panel'; import { ConnectionForm } from './connection-form'; import useConnectionForm, { - FILE_CHOOSER_MODE, + FileChooserMode, type FileChooserOptions, } from './use-connection-form'; import type { MessageFromExtensionToWebview } from './extension-app-message-constants'; -import { MESSAGE_TYPES } from './extension-app-message-constants'; +import { MessageType } from './extension-app-message-constants'; const pageStyles = css({ width: '90%', @@ -76,7 +76,7 @@ const OverviewPage: React.FC = () => { ): void => { const message = event.data; if ( - message.command === MESSAGE_TYPES.OPEN_FILE_CHOOSER_RESULT && + message.command === MessageType.openFileChooserResult && message.requestId === requestId ) { window.removeEventListener('message', messageHandler); @@ -102,7 +102,7 @@ const OverviewPage: React.FC = () => { ): Promise<{ canceled: boolean; filePath?: string }> { return handleOpenFileChooserResult({ electronFileDialogOptions, - mode: FILE_CHOOSER_MODE.SAVE, + mode: FileChooserMode.save, }); }, async showOpenDialog( @@ -111,7 +111,7 @@ const OverviewPage: React.FC = () => { ): Promise<{ canceled: boolean; filePaths: string[] }> { return handleOpenFileChooserResult({ electronFileDialogOptions, - mode: FILE_CHOOSER_MODE.OPEN, + mode: FileChooserMode.open, }); }, }, diff --git a/src/views/webview-app/use-connection-form.ts b/src/views/webview-app/use-connection-form.ts index c36c40219..d5204eb9d 100644 --- a/src/views/webview-app/use-connection-form.ts +++ b/src/views/webview-app/use-connection-form.ts @@ -9,18 +9,20 @@ import { sendEditConnectionToExtension, sendOpenFileChooserToExtension, } from './vscode-api'; -import { MESSAGE_TYPES } from './extension-app-message-constants'; +import { MessageType } 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 FileChooserMode = { + open: 'open', + save: 'save', +} as const; + +type FileChooserMode = (typeof FileChooserMode)[keyof typeof FileChooserMode]; export type FileChooserOptions = { electronFileDialogOptions?: Partial; - mode: FILE_CHOOSER_MODE; + mode: FileChooserMode; }; type ConnectionInfo = { @@ -160,7 +162,7 @@ export default function useConnectionForm(): { const handleConnectResultResponse = (event): void => { const message: MessageFromExtensionToWebview = event.data; if ( - message.command === MESSAGE_TYPES.CONNECT_RESULT && + message.command === MessageType.connectResult && message.connectionId === initialConnectionInfo.id ) { dispatch({ @@ -179,7 +181,7 @@ export default function useConnectionForm(): { useEffect(() => { const handleConnectResultResponse = (event): void => { const message: MessageFromExtensionToWebview = event.data; - if (message.command === MESSAGE_TYPES.OPEN_EDIT_CONNECTION) { + if (message.command === MessageType.openEditConnection) { dispatch({ type: 'open-edit-connection', connectionInfo: { diff --git a/src/views/webview-app/use-connection-status.ts b/src/views/webview-app/use-connection-status.ts index e7cfe3b38..21602a168 100644 --- a/src/views/webview-app/use-connection-status.ts +++ b/src/views/webview-app/use-connection-status.ts @@ -2,24 +2,25 @@ import { useState, useEffect } from 'react'; import { CONNECTION_STATUS, type MessageFromExtensionToWebview, - MESSAGE_TYPES, + MessageType, + 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( - CONNECTION_STATUS.LOADING, + const [connectionStatus, setConnectionStatus] = useState( + CONNECTION_STATUS.loading, ); const [connectionName, setConnectionName] = useState(''); useEffect(() => { const handleConnectionStatusResponse = (event): void => { const message: MessageFromExtensionToWebview = event.data; - if (message.command === MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE) { + if (message.command === MessageType.connectionStatusMessage) { setConnectionStatus(message.connectionStatus); setConnectionName(message.activeConnectionName); } @@ -28,7 +29,7 @@ const useConnectionStatus = (): { const requestConnectionStatus = (): void => vscode.postMessage({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS, + command: MessageType.getConnectionStatus, }); requestConnectionStatus(); diff --git a/src/views/webview-app/use-detect-vscode-dark-mode.tsx b/src/views/webview-app/use-detect-vscode-dark-mode.tsx index fa58dec62..dcc49bc8a 100644 --- a/src/views/webview-app/use-detect-vscode-dark-mode.tsx +++ b/src/views/webview-app/use-detect-vscode-dark-mode.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react'; import { type MessageFromExtensionToWebview, - MESSAGE_TYPES, + MessageType, } from './extension-app-message-constants'; export const useDetectVsCodeDarkMode = (): boolean => { @@ -12,7 +12,7 @@ export const useDetectVsCodeDarkMode = (): boolean => { useEffect(() => { const onThemeChanged = (event): void => { const message: MessageFromExtensionToWebview = event.data; - if (message.command === MESSAGE_TYPES.THEME_CHANGED) { + if (message.command === MessageType.themeChanged) { setDarkModeDetected(message.darkMode); } }; diff --git a/src/views/webview-app/vscode-api.ts b/src/views/webview-app/vscode-api.ts index 2073c849b..35e025cc3 100644 --- a/src/views/webview-app/vscode-api.ts +++ b/src/views/webview-app/vscode-api.ts @@ -1,5 +1,5 @@ import { - MESSAGE_TYPES, + MessageType, type MessageFromWebviewToExtension, type ConnectMessage, } from './extension-app-message-constants'; @@ -16,7 +16,7 @@ export const sendEditConnectionToExtension = ( connectionInfo: ConnectMessage['connectionInfo'], ): void => { vscode.postMessage({ - command: MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT, + command: MessageType.editConnectionAndConnect, connectionInfo, }); }; @@ -25,7 +25,7 @@ export const sendConnectToExtension = ( connectionInfo: ConnectMessage['connectionInfo'], ): void => { vscode.postMessage({ - command: MESSAGE_TYPES.CONNECT, + command: MessageType.connect, connectionInfo, }); }; @@ -35,7 +35,7 @@ export const sendOpenFileChooserToExtension = ( requestId: string, ): void => { vscode.postMessage({ - command: MESSAGE_TYPES.OPEN_FILE_CHOOSER, + command: MessageType.openFileChooser, fileChooserOptions, requestId, }); @@ -43,7 +43,7 @@ export const sendOpenFileChooserToExtension = ( export const sendCancelConnectToExtension = (): void => { vscode.postMessage({ - command: MESSAGE_TYPES.CANCEL_CONNECT, + command: MessageType.cancelConnect, }); }; @@ -51,25 +51,25 @@ export const sendCancelConnectToExtension = (): void => { // input if it's open, so we message the extension. export const sendFormOpenedToExtension = (): void => { vscode.postMessage({ - command: MESSAGE_TYPES.CONNECTION_FORM_OPENED, + command: MessageType.connectionFormOpened, }); }; export const renameActiveConnection = (): void => { vscode.postMessage({ - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION, + command: MessageType.renameActiveConnection, }); }; export const createNewPlayground = (): void => { vscode.postMessage({ - command: MESSAGE_TYPES.CREATE_NEW_PLAYGROUND, + command: MessageType.createNewPlayground, }); }; export const connectWithConnectionString = (): void => { vscode.postMessage({ - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT, + command: MessageType.openConnectionStringInput, }); }; @@ -78,7 +78,7 @@ export const trackExtensionLinkClicked = ( linkId: string, ): void => { vscode.postMessage({ - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + command: MessageType.extensionLinkClicked, screen, linkId, }); @@ -86,7 +86,7 @@ export const trackExtensionLinkClicked = ( export const openTrustedLink = (linkTo: string): void => { vscode.postMessage({ - command: MESSAGE_TYPES.OPEN_TRUSTED_LINK, + command: MessageType.openTrustedLink, linkTo, }); }; diff --git a/src/views/webviewController.ts b/src/views/webviewController.ts index 8c4d6f80d..a33acbe5a 100644 --- a/src/views/webviewController.ts +++ b/src/views/webviewController.ts @@ -4,12 +4,12 @@ import crypto from 'crypto'; import type { ConnectionOptions } from 'mongodb-data-service'; import type ConnectionController from '../connectionController'; -import { ConnectionTypes } from '../connectionController'; +import { ConnectionType } from '../connectionController'; import { createLogger } from '../logging'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import type { MessageFromWebviewToExtension } from './webview-app/extension-app-message-constants'; import { - MESSAGE_TYPES, + MessageType, VSCODE_EXTENSION_OIDC_DEVICE_AUTH_ID, VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID, } from './webview-app/extension-app-message-constants'; @@ -164,7 +164,7 @@ export default class WebviewController { } void panel.webview.postMessage({ - command: MESSAGE_TYPES.OPEN_FILE_CHOOSER_RESULT, + command: MessageType.openFileChooserResult, fileChooserResult: { canceled: false, ...(Array.isArray(files) @@ -201,13 +201,13 @@ export default class WebviewController { : await this._connectionController.saveNewConnectionAndConnect({ connectionId: connection.id, connectionOptions: connection.connectionOptions, - connectionType: ConnectionTypes.CONNECTION_FORM, + connectionType: ConnectionType.connectionForm, }); try { // The webview may have been closed in which case this will throw. void panel.webview.postMessage({ - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.connectResult, connectionId: connection.id, connectionSuccess: successfullyConnected, connectionMessage: successfullyConnected @@ -223,7 +223,7 @@ export default class WebviewController { ); void panel.webview.postMessage({ - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.connectResult, connectionId: connection.id, connectionSuccess: false, connectionMessage: `Unable to load connection: ${error}`, @@ -237,16 +237,16 @@ export default class WebviewController { panel: vscode.WebviewPanel, ): Promise => { switch (message.command) { - case MESSAGE_TYPES.CONNECT: + case MessageType.connect: await this.handleWebviewConnectAttempt({ panel, connection: message.connectionInfo, }); return; - case MESSAGE_TYPES.CANCEL_CONNECT: + case MessageType.cancelConnect: this._connectionController.cancelConnectionAttempt(); return; - case MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT: + case MessageType.editConnectionAndConnect: await this.handleWebviewConnectAttempt({ panel, connection: message.connectionInfo, @@ -254,37 +254,35 @@ export default class WebviewController { }); this._telemetryService.track(new ConnectionEditedTelemetryEvent()); return; - case MESSAGE_TYPES.OPEN_FILE_CHOOSER: + case MessageType.openFileChooser: await this.handleWebviewOpenFileChooserAttempt({ panel, fileChooserOptions: message.fileChooserOptions, requestId: message.requestId, }); return; - case MESSAGE_TYPES.CREATE_NEW_PLAYGROUND: + case MessageType.createNewPlayground: void vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE, + ExtensionCommand.mdbCreatePlaygroundFromOverviewPage, ); return; - case MESSAGE_TYPES.CONNECTION_FORM_OPENED: + case MessageType.connectionFormOpened: // If the connection string input is open we want to close it // when the user opens the form. this._connectionController.closeConnectionStringInput(); return; - case MESSAGE_TYPES.GET_CONNECTION_STATUS: + case MessageType.getConnectionStatus: void panel.webview.postMessage({ - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, + command: MessageType.connectionStatusMessage, connectionStatus: this._connectionController.getConnectionStatus(), activeConnectionName: this._connectionController.getActiveConnectionName(), }); return; - case MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT: - void vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_CONNECT_WITH_URI, - ); + case MessageType.openConnectionStringInput: + void vscode.commands.executeCommand(ExtensionCommand.mdbConnectWithUri); return; - case MESSAGE_TYPES.OPEN_TRUSTED_LINK: + case MessageType.openTrustedLink: try { await openLink(message.linkTo); } catch (err) { @@ -295,12 +293,12 @@ export default class WebviewController { ); } return; - case MESSAGE_TYPES.EXTENSION_LINK_CLICKED: + case MessageType.extensionLinkClicked: this._telemetryService.track( new LinkClickedTelemetryEvent(message.screen, message.linkId), ); return; - case MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION: + case MessageType.renameActiveConnection: if (this._connectionController.isCurrentlyConnected()) { void this._connectionController.renameConnection( this._connectionController.getActiveConnectionId() as string, @@ -339,7 +337,7 @@ export default class WebviewController { for (const panel of this._activeWebviewPanels) { void panel.webview .postMessage({ - command: MESSAGE_TYPES.THEME_CHANGED, + command: MessageType.themeChanged, darkMode: darkModeDetected, }) .then(undefined, (error) => { @@ -369,7 +367,7 @@ export default class WebviewController { this._telemetryService.track(new OpenEditConnectionTelemetryEvent()); void webviewPanel.webview.postMessage({ - command: MESSAGE_TYPES.OPEN_EDIT_CONNECTION, + command: MessageType.openEditConnection, connection, }); }; diff --git a/tsconfig.json b/tsconfig.json index 7d774cb4c..f1c6b804f 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. */