From 1ecb66690c220e76adcd55ef2bd0ba691f15eb50 Mon Sep 17 00:00:00 2001 From: Kai Salmen Date: Tue, 21 Jun 2022 14:22:36 +0200 Subject: [PATCH] Enable eslint for all packages --- .eslintrc.js | 10 ++- packages/examples/browser-lsp/package.json | 2 +- packages/examples/browser-lsp/src/client.ts | 8 +-- .../examples/browser-lsp/src/serverWorker.ts | 28 ++++---- packages/examples/browser-old/package.json | 2 +- packages/examples/browser-old/src/client.ts | 36 +++++----- packages/examples/browser/package.json | 2 +- packages/examples/browser/src/client.ts | 53 +++++++------- packages/examples/client/package.json | 2 +- packages/examples/client/src/client.ts | 14 ++-- packages/examples/node/package.json | 2 +- packages/examples/node/src/ext-json-server.ts | 2 +- .../examples/node/src/json-server-launcher.ts | 10 +-- packages/examples/node/src/json-server.ts | 71 +++++++++---------- packages/examples/node/src/server.ts | 18 ++--- packages/vscode-ws-jsonrpc/src/connection.ts | 26 ++++--- packages/vscode-ws-jsonrpc/src/disposable.ts | 13 ++-- packages/vscode-ws-jsonrpc/src/index.ts | 2 +- packages/vscode-ws-jsonrpc/src/logger.ts | 12 ++-- .../src/server/connection.ts | 29 ++++---- .../vscode-ws-jsonrpc/src/server/index.ts | 2 +- .../vscode-ws-jsonrpc/src/server/launch.ts | 17 +++-- .../src/socket/connection.ts | 10 +-- .../vscode-ws-jsonrpc/src/socket/reader.ts | 22 +++--- .../vscode-ws-jsonrpc/src/socket/socket.ts | 4 +- .../vscode-ws-jsonrpc/src/socket/writer.ts | 14 ++-- 26 files changed, 206 insertions(+), 205 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 6237f470b..b007e16e3 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -5,7 +5,6 @@ module.exports = { }, extends: 'standard', globals: { - Thenable: 'readonly' }, parser: '@typescript-eslint/parser', parserOptions: { @@ -29,6 +28,13 @@ module.exports = { 'no-redeclare': 'off', '@typescript-eslint/no-redeclare': ['error'], 'no-useless-constructor': 'warn', - 'no-void': 'warn' + 'no-void': 'warn', + // Following recommendation: + // https://typescript-eslint.io/docs/linting/troubleshooting/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors + 'no-undef': 'off', + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': ['warn', { + argsIgnorePattern: '^_' + }] } }; diff --git a/packages/examples/browser-lsp/package.json b/packages/examples/browser-lsp/package.json index 18f2946dc..636d3c703 100644 --- a/packages/examples/browser-lsp/package.json +++ b/packages/examples/browser-lsp/package.json @@ -10,7 +10,7 @@ }, "scripts": { "clean": "npx shx rm -fr dist tsconfig.tsbuildinfo", - "lint": "echo 'No linting yet'", + "lint": "eslint src --ext .ts", "compile": "tsc", "watch": "tsc -w", "copy:monacoworkers": "shx mkdir -p dist && shx cp -r ../../../node_modules/monaco-editor-workers/dist/workers/editorWorker* ./dist", diff --git a/packages/examples/browser-lsp/src/client.ts b/packages/examples/browser-lsp/src/client.ts index fdc359170..2618cc01b 100644 --- a/packages/examples/browser-lsp/src/client.ts +++ b/packages/examples/browser-lsp/src/client.ts @@ -19,10 +19,10 @@ import 'monaco-editor/esm/vs/editor/standalone/browser/toggleHighContrast/toggle import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'; import { buildWorkerDefinition } from 'monaco-editor-workers'; -buildWorkerDefinition('dist', new URL('', window.location.href).href, false); import { MonacoLanguageClient, CloseAction, ErrorAction, MonacoServices, MessageTransports } from 'monaco-languageclient'; import { BrowserMessageReader, BrowserMessageWriter } from 'vscode-languageserver-protocol/browser'; +buildWorkerDefinition('dist', new URL('', window.location.href).href, false); // register Monaco languages monaco.languages.register({ @@ -38,7 +38,7 @@ const editorText = ` #00ff00 (green) #0000ff (blue) `; -monaco.editor.create(document.getElementById("container")!, { +monaco.editor.create(document.getElementById('container')!, { model: monaco.editor.createModel(editorText, 'plaintext', monaco.Uri.parse('inmemory://model.txt')), glyphMargin: true, lightbulb: { @@ -46,9 +46,9 @@ monaco.editor.create(document.getElementById("container")!, { } }); -function createLanguageClient(transports: MessageTransports): MonacoLanguageClient { +function createLanguageClient (transports: MessageTransports): MonacoLanguageClient { return new MonacoLanguageClient({ - name: "Sample Language Client", + name: 'Sample Language Client', clientOptions: { // use a language id as a document selector documentSelector: [{ language: 'plaintext' }], diff --git a/packages/examples/browser-lsp/src/serverWorker.ts b/packages/examples/browser-lsp/src/serverWorker.ts index 0d13a47ac..b5e1e9ee0 100644 --- a/packages/examples/browser-lsp/src/serverWorker.ts +++ b/packages/examples/browser-lsp/src/serverWorker.ts @@ -1,17 +1,17 @@ +/* --------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *-------------------------------------------------------------------------------------------- */ + // This is an example copied as is from here: // https://github.com/microsoft/vscode-extension-samples/blob/main/lsp-web-extension-sample/server/src/browserServerMain.ts // the only addition is the following line: -declare const self: DedicatedWorkerGlobalScope; - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ import { createConnection, BrowserMessageReader, BrowserMessageWriter } from 'vscode-languageserver/browser'; import { Color, ColorInformation, Range, InitializeParams, InitializeResult, ServerCapabilities, TextDocuments, ColorPresentation, TextEdit, TextDocumentIdentifier } from 'vscode-languageserver'; import { TextDocument } from 'vscode-languageserver-textdocument'; +declare const self: DedicatedWorkerGlobalScope; console.log('running server lsp-web-extension-sample'); @@ -42,10 +42,9 @@ connection.onColorPresentation(params => getColorPresentation(params.color, para // Listen on the connection connection.listen(); - const colorRegExp = /#([0-9A-Fa-f]{6})/g; -function getColorInformation(textDocument: TextDocumentIdentifier) { +function getColorInformation (textDocument: TextDocumentIdentifier) { const colorInfos: ColorInformation[] = []; const document = documents.get(textDocument.uri); @@ -67,22 +66,21 @@ function getColorInformation(textDocument: TextDocumentIdentifier) { return colorInfos; } -function getColorPresentation(color: Color, range: Range) { +function getColorPresentation (color: Color, range: Range) { const result: ColorPresentation[] = []; - const red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255); + const red256 = Math.round(color.red * 255); const green256 = Math.round(color.green * 255); const blue256 = Math.round(color.blue * 255); - function toTwoDigitHex(n: number): string { + function toTwoDigitHex (n: number): string { const r = n.toString(16); return r.length !== 2 ? '0' + r : r; } const label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}`; - result.push({ label: label, textEdit: TextEdit.replace(range, label) }); + result.push({ label, textEdit: TextEdit.replace(range, label) }); return result; } - const enum CharCode { Digit0 = 48, Digit9 = 57, @@ -94,7 +92,7 @@ const enum CharCode { f = 102, } -function parseHexDigit(charCode: CharCode): number { +function parseHexDigit (charCode: CharCode): number { if (charCode >= CharCode.Digit0 && charCode <= CharCode.Digit9) { return charCode - CharCode.Digit0; } @@ -107,7 +105,7 @@ function parseHexDigit(charCode: CharCode): number { return 0; } -function parseColor(content: string, offset: number): Color { +function parseColor (content: string, offset: number): Color { const r = (16 * parseHexDigit(content.charCodeAt(offset + 1)) + parseHexDigit(content.charCodeAt(offset + 2))) / 255; const g = (16 * parseHexDigit(content.charCodeAt(offset + 3)) + parseHexDigit(content.charCodeAt(offset + 4))) / 255; const b = (16 * parseHexDigit(content.charCodeAt(offset + 5)) + parseHexDigit(content.charCodeAt(offset + 6))) / 255; diff --git a/packages/examples/browser-old/package.json b/packages/examples/browser-old/package.json index 782010cd6..43101ba16 100644 --- a/packages/examples/browser-old/package.json +++ b/packages/examples/browser-old/package.json @@ -9,7 +9,7 @@ }, "scripts": { "clean": "npx shx rm -fr dist tsconfig.tsbuildinfo", - "lint": "echo 'No linting yet'", + "lint": "eslint src --ext .ts", "compile": "tsc", "watch": "tsc -w", "copy:monacoworkers": "shx mkdir -p dist && shx cp -r ../../../node_modules/monaco-editor-workers/dist/workers/editorWorker* ./dist", diff --git a/packages/examples/browser-old/src/client.ts b/packages/examples/browser-old/src/client.ts index 828382a77..f66341a3c 100644 --- a/packages/examples/browser-old/src/client.ts +++ b/packages/examples/browser-old/src/client.ts @@ -20,13 +20,13 @@ import 'monaco-editor/esm/vs/editor/standalone/browser/toggleHighContrast/toggle import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'; import { buildWorkerDefinition } from 'monaco-editor-workers'; -buildWorkerDefinition('dist', new URL('', window.location.href).href, false); -import { getLanguageService, TextDocument } from "vscode-json-languageservice"; +import { getLanguageService, TextDocument } from 'vscode-json-languageservice'; import { MonacoToProtocolConverter, ProtocolToMonacoConverter } from 'monaco-languageclient'; +buildWorkerDefinition('dist', new URL('', window.location.href).href, false); const LANGUAGE_ID = 'json'; -const MODEL_URI = 'inmemory://model.json' +const MODEL_URI = 'inmemory://model.json'; const MONACO_URI = monaco.Uri.parse(MODEL_URI); // register the JSON language with Monaco @@ -34,7 +34,7 @@ monaco.languages.register({ id: LANGUAGE_ID, extensions: ['.json', '.bowerrc', '.jshintrc', '.jscsrc', '.eslintrc', '.babelrc'], aliases: ['JSON', 'json'], - mimetypes: ['application/json'], + mimetypes: ['application/json'] }); // create the Monaco editor @@ -42,7 +42,7 @@ const value = `{ "$schema": "http://json.schemastore.org/coffeelint", "line_endings": "unix" }`; -monaco.editor.create(document.getElementById("container")!, { +monaco.editor.create(document.getElementById('container')!, { model: monaco.editor.createModel(value, LANGUAGE_ID, MONACO_URI), glyphMargin: true, lightbulb: { @@ -50,20 +50,20 @@ monaco.editor.create(document.getElementById("container")!, { } }); -function getModel(): monaco.editor.IModel { +function getModel (): monaco.editor.IModel { return monaco.editor.getModel(MONACO_URI) as monaco.editor.IModel; } -function createDocument(model: monaco.editor.IReadOnlyModel) { +function createDocument (model: monaco.editor.IReadOnlyModel) { return TextDocument.create(MODEL_URI, model.getLanguageId(), model.getVersionId(), model.getValue()); } -function resolveSchema(url: string): Promise { +function resolveSchema (url: string): Promise { const promise = new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onload = () => resolve(xhr.responseText); xhr.onerror = () => reject(xhr.statusText); - xhr.open("GET", url, true); + xhr.open('GET', url, true); xhr.send(); }); return promise; @@ -77,7 +77,7 @@ const jsonService = getLanguageService({ const pendingValidationRequests = new Map(); monaco.languages.registerCompletionItemProvider(LANGUAGE_ID, { - provideCompletionItems(model, position, _context, _token): monaco.Thenable { + provideCompletionItems (model, position, _context, _token): monaco.Thenable { const document = createDocument(model); const wordUntil = model.getWordUntilPosition(position); const defaultRange = new monaco.Range(position.lineNumber, wordUntil.startColumn, position.lineNumber, wordUntil.endColumn); @@ -87,13 +87,13 @@ monaco.languages.registerCompletionItemProvider(LANGUAGE_ID, { }); }, - resolveCompletionItem(item, _token): monaco.languages.CompletionItem | monaco.Thenable { + resolveCompletionItem (item, _token): monaco.languages.CompletionItem | monaco.Thenable { return jsonService.doResolve(m2p.asCompletionItem(item)).then(result => p2m.asCompletionItem(result, item.range)); } }); monaco.languages.registerDocumentRangeFormattingEditProvider(LANGUAGE_ID, { - provideDocumentRangeFormattingEdits(model, range, options, _token): monaco.languages.TextEdit[] | monaco.Thenable { + provideDocumentRangeFormattingEdits (model, range, options, _token): monaco.languages.TextEdit[] | monaco.Thenable { const document = createDocument(model); const edits = jsonService.format(document, m2p.asRange(range), m2p.asFormattingOptions(options)); return p2m.asTextEdits(edits); @@ -101,7 +101,7 @@ monaco.languages.registerDocumentRangeFormattingEditProvider(LANGUAGE_ID, { }); monaco.languages.registerDocumentSymbolProvider(LANGUAGE_ID, { - provideDocumentSymbols(model, _token): monaco.languages.DocumentSymbol[] | monaco.Thenable { + provideDocumentSymbols (model, _token): monaco.languages.DocumentSymbol[] | monaco.Thenable { const document = createDocument(model); const jsonDocument = jsonService.parseJSONDocument(document); return p2m.asSymbolInformations(jsonService.findDocumentSymbols(document, jsonDocument)); @@ -109,7 +109,7 @@ monaco.languages.registerDocumentSymbolProvider(LANGUAGE_ID, { }); monaco.languages.registerHoverProvider(LANGUAGE_ID, { - provideHover(model, position, _token): monaco.languages.Hover | monaco.Thenable { + provideHover (model, position, _token): monaco.languages.Hover | monaco.Thenable { const document = createDocument(model); const jsonDocument = jsonService.parseJSONDocument(document); return jsonService.doHover(document, m2p.asPosition(position.lineNumber, position.column), jsonDocument).then((hover) => { @@ -123,7 +123,7 @@ getModel().onDidChangeContent((_event) => { }); validate(); -function validate(): void { +function validate (): void { const document = createDocument(getModel()); cleanPendingValidation(document); pendingValidationRequests.set(document.uri, setTimeout(() => { @@ -132,7 +132,7 @@ function validate(): void { })); } -function cleanPendingValidation(document: TextDocument): void { +function cleanPendingValidation (document: TextDocument): void { const request = pendingValidationRequests.get(document.uri); if (request !== undefined) { clearTimeout(request); @@ -140,7 +140,7 @@ function cleanPendingValidation(document: TextDocument): void { } } -function doValidate(document: TextDocument): void { +function doValidate (document: TextDocument): void { if (document.getText().length === 0) { cleanDiagnostics(); return; @@ -152,6 +152,6 @@ function doValidate(document: TextDocument): void { }); } -function cleanDiagnostics(): void { +function cleanDiagnostics (): void { monaco.editor.setModelMarkers(getModel(), 'default', []); } diff --git a/packages/examples/browser/package.json b/packages/examples/browser/package.json index eb15d5003..2ebe0c313 100644 --- a/packages/examples/browser/package.json +++ b/packages/examples/browser/package.json @@ -9,7 +9,7 @@ }, "scripts": { "clean": "npx shx rm -fr dist tsconfig.tsbuildinfo", - "lint": "echo 'No linting yet'", + "lint": "eslint src --ext .ts", "compile": "tsc", "watch": "tsc -w", "copy:monacoworkers": "shx mkdir -p dist && shx cp -r ../../../node_modules/monaco-editor-workers/dist/workers/editorWorker* ./dist", diff --git a/packages/examples/browser/src/client.ts b/packages/examples/browser/src/client.ts index 555863e85..3e847beee 100644 --- a/packages/examples/browser/src/client.ts +++ b/packages/examples/browser/src/client.ts @@ -18,19 +18,19 @@ import 'monaco-editor/esm/vs/editor/standalone/browser/referenceSearch/standalon import 'monaco-editor/esm/vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast.js'; import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'; -import * as vscode from 'vscode' +import * as vscode from 'vscode'; import { buildWorkerDefinition } from 'monaco-editor-workers'; -buildWorkerDefinition('dist', new URL('', window.location.href).href, false); -import { getLanguageService, TextDocument } from "vscode-json-languageservice"; -import { createConverter as createCodeConverter } from "vscode-languageclient/lib/common/codeConverter" -import { createConverter as createProtocolConverter } from "vscode-languageclient/lib/common/protocolConverter" -const codeConverter = createCodeConverter() -const protocolConverter = createProtocolConverter(undefined, true, true) +import { getLanguageService, TextDocument } from 'vscode-json-languageservice'; +import { createConverter as createCodeConverter } from 'vscode-languageclient/lib/common/codeConverter'; +import { createConverter as createProtocolConverter } from 'vscode-languageclient/lib/common/protocolConverter'; +buildWorkerDefinition('dist', new URL('', window.location.href).href, false); +const codeConverter = createCodeConverter(); +const protocolConverter = createProtocolConverter(undefined, true, true); const LANGUAGE_ID = 'json'; -const MODEL_URI = 'inmemory://model.json' +const MODEL_URI = 'inmemory://model.json'; const MONACO_URI = monaco.Uri.parse(MODEL_URI); // register the JSON language with Monaco @@ -38,7 +38,7 @@ monaco.languages.register({ id: LANGUAGE_ID, extensions: ['.json', '.bowerrc', '.jshintrc', '.jscsrc', '.eslintrc', '.babelrc'], aliases: ['JSON', 'json'], - mimetypes: ['application/json'], + mimetypes: ['application/json'] }); // create the Monaco editor @@ -46,8 +46,8 @@ const value = `{ "$schema": "http://json.schemastore.org/coffeelint", "line_endings": "unix" }`; -const model = monaco.editor.createModel(value, LANGUAGE_ID, MONACO_URI) -monaco.editor.create(document.getElementById("container")!, { +const model = monaco.editor.createModel(value, LANGUAGE_ID, MONACO_URI); +monaco.editor.create(document.getElementById('container')!, { model, glyphMargin: true, lightbulb: { @@ -55,18 +55,18 @@ monaco.editor.create(document.getElementById("container")!, { } }); -const vscodeDocument = vscode.workspace.textDocuments[0] +const vscodeDocument = vscode.workspace.textDocuments[0]; -function createDocument(vscodeDocument: vscode.TextDocument) { +function createDocument (vscodeDocument: vscode.TextDocument) { return TextDocument.create(MODEL_URI, vscodeDocument.languageId, vscodeDocument.version, vscodeDocument.getText()); } -function resolveSchema(url: string): Promise { +function resolveSchema (url: string): Promise { const promise = new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onload = () => resolve(xhr.responseText); xhr.onerror = () => reject(xhr.statusText); - xhr.open("GET", url, true); + xhr.open('GET', url, true); xhr.send(); }); return promise; @@ -78,20 +78,20 @@ const jsonService = getLanguageService({ const pendingValidationRequests = new Map(); vscode.languages.registerCompletionItemProvider(LANGUAGE_ID, { - async provideCompletionItems(vscodeDocument, position, _token, _context) { - const document = createDocument(vscodeDocument) + async provideCompletionItems (vscodeDocument, position, _token, _context) { + const document = createDocument(vscodeDocument); const jsonDocument = jsonService.parseJSONDocument(document); const completionList = await jsonService.doComplete(document, codeConverter.asPosition(position), jsonDocument); return protocolConverter.asCompletionResult(completionList); }, - resolveCompletionItem(item, _token) { + resolveCompletionItem (item, _token) { return jsonService.doResolve(codeConverter.asCompletionItem(item)).then(result => protocolConverter.asCompletionItem(result)); } }); vscode.languages.registerDocumentRangeFormattingEditProvider(LANGUAGE_ID, { - provideDocumentRangeFormattingEdits(vscodeDocument, range, options, _token) { + provideDocumentRangeFormattingEdits (vscodeDocument, range, options, _token) { const document = createDocument(vscodeDocument); const edits = jsonService.format(document, codeConverter.asRange(range), codeConverter.asFormattingOptions(options, {})); return protocolConverter.asTextEdits(edits); @@ -99,7 +99,7 @@ vscode.languages.registerDocumentRangeFormattingEditProvider(LANGUAGE_ID, { }); vscode.languages.registerDocumentSymbolProvider(LANGUAGE_ID, { - provideDocumentSymbols(vscodeDocument, _token) { + provideDocumentSymbols (vscodeDocument, _token) { const document = createDocument(vscodeDocument); const jsonDocument = jsonService.parseJSONDocument(document); return protocolConverter.asSymbolInformations(jsonService.findDocumentSymbols(document, jsonDocument)); @@ -107,7 +107,7 @@ vscode.languages.registerDocumentSymbolProvider(LANGUAGE_ID, { }); vscode.languages.registerHoverProvider(LANGUAGE_ID, { - provideHover(vscodeDocument, position, _token) { + provideHover (vscodeDocument, position, _token) { const document = createDocument(vscodeDocument); const jsonDocument = jsonService.parseJSONDocument(document); return jsonService.doHover(document, codeConverter.asPosition(position), jsonDocument).then((hover) => { @@ -121,7 +121,7 @@ model.onDidChangeContent((_event) => { }); validate(); -function validate(): void { +function validate (): void { const document = createDocument(vscodeDocument); cleanPendingValidation(document); pendingValidationRequests.set(document.uri, setTimeout(() => { @@ -130,7 +130,7 @@ function validate(): void { })); } -function cleanPendingValidation(document: TextDocument): void { +function cleanPendingValidation (document: TextDocument): void { const request = pendingValidationRequests.get(document.uri); if (request !== undefined) { clearTimeout(request); @@ -139,20 +139,19 @@ function cleanPendingValidation(document: TextDocument): void { } const diagnosticCollection = vscode.languages.createDiagnosticCollection('json'); -function doValidate(document: TextDocument): void { +function doValidate (document: TextDocument): void { if (document.getText().length === 0) { cleanDiagnostics(); return; } const jsonDocument = jsonService.parseJSONDocument(document); - jsonService.doValidation(document, jsonDocument).then(async (pDiagnostics) => { const diagnostics = await protocolConverter.asDiagnostics(pDiagnostics); diagnosticCollection.set(MONACO_URI, diagnostics); }); } -function cleanDiagnostics(): void { - diagnosticCollection.clear() +function cleanDiagnostics (): void { + diagnosticCollection.clear(); } diff --git a/packages/examples/client/package.json b/packages/examples/client/package.json index ec4e239e9..e19381259 100644 --- a/packages/examples/client/package.json +++ b/packages/examples/client/package.json @@ -20,7 +20,7 @@ }, "scripts": { "clean": "npx shx rm -fr dist tsconfig.tsbuildinfo", - "lint": "echo 'No linting yet'", + "lint": "eslint src --ext .ts", "compile": "tsc", "watch": "tsc -w", "copy:monacoworkers": "shx mkdir -p dist && shx cp -r ../../../node_modules/monaco-editor-workers/dist/workers/editorWorker* ./dist", diff --git a/packages/examples/client/src/client.ts b/packages/examples/client/src/client.ts index 397bbc2ac..ea673398e 100644 --- a/packages/examples/client/src/client.ts +++ b/packages/examples/client/src/client.ts @@ -19,11 +19,11 @@ import 'monaco-editor/esm/vs/editor/standalone/browser/toggleHighContrast/toggle import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'; import { buildWorkerDefinition } from 'monaco-editor-workers'; -buildWorkerDefinition('dist', new URL('', window.location.href).href, false); import { MonacoLanguageClient, CloseAction, ErrorAction, MonacoServices, MessageTransports } from 'monaco-languageclient'; import { toSocket, WebSocketMessageReader, WebSocketMessageWriter } from 'vscode-ws-jsonrpc'; import normalizeUrl from 'normalize-url'; +buildWorkerDefinition('dist', new URL('', window.location.href).href, false); // register Monaco languages monaco.languages.register({ @@ -38,7 +38,7 @@ const value = `{ "$schema": "http://json.schemastore.org/coffeelint", "line_endings": "unix" }`; -monaco.editor.create(document.getElementById("container")!, { +monaco.editor.create(document.getElementById('container')!, { model: monaco.editor.createModel(value, 'json', monaco.Uri.parse('inmemory://model.json')), glyphMargin: true, lightbulb: { @@ -50,7 +50,7 @@ monaco.editor.create(document.getElementById("container")!, { MonacoServices.install(); // create the web socket -const url = createUrl('localhost', 3000, '/sampleServer') +const url = createUrl('localhost', 3000, '/sampleServer'); const webSocket = new WebSocket(url); webSocket.onopen = () => { @@ -65,9 +65,9 @@ webSocket.onopen = () => { reader.onClose(() => languageClient.stop()); }; -function createLanguageClient(transports: MessageTransports): MonacoLanguageClient { +function createLanguageClient (transports: MessageTransports): MonacoLanguageClient { return new MonacoLanguageClient({ - name: "Sample Language Client", + name: 'Sample Language Client', clientOptions: { // use a language id as a document selector documentSelector: ['json'], @@ -80,13 +80,13 @@ function createLanguageClient(transports: MessageTransports): MonacoLanguageClie // create a language client connection from the JSON RPC connection on demand connectionProvider: { get: () => { - return Promise.resolve(transports) + return Promise.resolve(transports); } } }); } -function createUrl(hostname: string, port: number, path: string): string { +function createUrl (hostname: string, port: number, path: string): string { const protocol = location.protocol === 'https:' ? 'wss' : 'ws'; return normalizeUrl(`${protocol}://${hostname}:${port}${path}`); } diff --git a/packages/examples/node/package.json b/packages/examples/node/package.json index 491d06c1a..492d9dc84 100644 --- a/packages/examples/node/package.json +++ b/packages/examples/node/package.json @@ -19,7 +19,7 @@ }, "scripts": { "clean": "npx shx rm -fr lib tsconfig.tsbuildinfo", - "lint": "echo 'No linting yet'", + "lint": "eslint src --ext .ts", "compile": "tsc -b .", "build": "npm run clean && npm run compile", "watch": "tsc -w", diff --git a/packages/examples/node/src/ext-json-server.ts b/packages/examples/node/src/ext-json-server.ts index 3fa5af414..de4c0814f 100644 --- a/packages/examples/node/src/ext-json-server.ts +++ b/packages/examples/node/src/ext-json-server.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ import { StreamMessageReader, StreamMessageWriter } from 'vscode-jsonrpc/node'; -import { start } from "./json-server"; +import { start } from './json-server'; const reader = new StreamMessageReader(process.stdin); const writer = new StreamMessageWriter(process.stdout); diff --git a/packages/examples/node/src/json-server-launcher.ts b/packages/examples/node/src/json-server-launcher.ts index 7e2942324..354aa0dd6 100644 --- a/packages/examples/node/src/json-server-launcher.ts +++ b/packages/examples/node/src/json-server-launcher.ts @@ -3,13 +3,13 @@ * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ import * as path from 'path'; -import * as rpc from "vscode-ws-jsonrpc"; -import * as server from "vscode-ws-jsonrpc/lib/server"; -import * as lsp from "vscode-languageserver"; -import { start } from "./json-server"; +import * as rpc from 'vscode-ws-jsonrpc'; +import * as server from 'vscode-ws-jsonrpc/lib/server'; +import * as lsp from 'vscode-languageserver'; +import { start } from './json-server'; import { Message } from 'vscode-languageserver'; -export function launch(socket: rpc.IWebSocket) { +export function launch (socket: rpc.IWebSocket) { const reader = new rpc.WebSocketMessageReader(socket); const writer = new rpc.WebSocketMessageWriter(socket); const asExternalProccess = process.argv.findIndex(value => value === '--external') !== -1; diff --git a/packages/examples/node/src/json-server.ts b/packages/examples/node/src/json-server.ts index 80f1820e7..ea354dd66 100644 --- a/packages/examples/node/src/json-server.ts +++ b/packages/examples/node/src/json-server.ts @@ -2,20 +2,20 @@ * Copyright (c) 2018-2022 TypeFox GmbH (http://www.typefox.io). All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ -import * as fs from "fs"; +import * as fs from 'fs'; import { xhr, getErrorStatusDescription } from 'request-light'; import { URI } from 'vscode-uri'; -import { MessageReader, MessageWriter } from "vscode-jsonrpc"; +import { MessageReader, MessageWriter } from 'vscode-jsonrpc'; import { _Connection, TextDocuments, DocumentSymbolParams, createConnection } from 'vscode-languageserver/lib/node/main'; import { Diagnostic, Command, CompletionList, CompletionItem, Hover, SymbolInformation, TextEdit, FoldingRange, ColorInformation, ColorPresentation -} from "vscode-languageserver-types"; +} from 'vscode-languageserver-types'; import { TextDocumentPositionParams, DocumentRangeFormattingParams, ExecuteCommandParams, CodeActionParams, FoldingRangeParams, DocumentColorParams, ColorPresentationParams, TextDocumentSyncKind } from 'vscode-languageserver-protocol'; -import { getLanguageService, LanguageService, JSONDocument } from "vscode-json-languageservice"; -import * as TextDocumentImpl from "vscode-languageserver-textdocument"; +import { getLanguageService, LanguageService, JSONDocument } from 'vscode-json-languageservice'; +import * as TextDocumentImpl from 'vscode-languageserver-textdocument'; -export function start(reader: MessageReader, writer: MessageWriter): JsonServer { +export function start (reader: MessageReader, writer: MessageWriter): JsonServer { const connection = createConnection(reader, writer); const server = new JsonServer(connection); server.start(); @@ -23,7 +23,6 @@ export function start(reader: MessageReader, writer: MessageWriter): JsonServer } export class JsonServer { - protected workspaceRoot: URI | undefined; protected readonly documents = new TextDocuments(TextDocumentImpl.TextDocument); @@ -32,9 +31,9 @@ export class JsonServer { schemaRequestService: this.resolveSchema.bind(this) }); - protected readonly pendingValidationRequests = new Map(); + protected readonly pendingValidationRequests = new Map(); - constructor( + constructor ( protected readonly connection: _Connection ) { this.documents.listen(this.connection); @@ -52,7 +51,7 @@ export class JsonServer { } else if (params.rootUri) { this.workspaceRoot = URI.parse(params.rootUri); } - this.connection.console.log("The server is initialized."); + this.connection.console.log('The server is initialized.'); return { capabilities: { textDocumentSync: TextDocumentSyncKind.Incremental, @@ -70,7 +69,7 @@ export class JsonServer { colorProvider: true, foldingRangeProvider: true } - } + }; }); this.connection.onCodeAction(params => this.codeAction(params) @@ -86,7 +85,7 @@ export class JsonServer { ); this.connection.onHover(params => this.hover(params) - ) + ); this.connection.onDocumentSymbol(params => this.findDocumentSymbols(params) ); @@ -104,11 +103,11 @@ export class JsonServer { ); } - start() { + start () { this.connection.listen(); } - protected getFoldingRanges(params: FoldingRangeParams): FoldingRange[] { + protected getFoldingRanges (params: FoldingRangeParams): FoldingRange[] { const document = this.documents.get(params.textDocument.uri); if (!document) { return []; @@ -116,7 +115,7 @@ export class JsonServer { return this.jsonService.getFoldingRanges(document); } - protected findDocumentColors(params: DocumentColorParams): Thenable { + protected findDocumentColors (params: DocumentColorParams): Thenable { const document = this.documents.get(params.textDocument.uri); if (!document) { return Promise.resolve([]); @@ -125,7 +124,7 @@ export class JsonServer { return this.jsonService.findDocumentColors(document, jsonDocument); } - protected getColorPresentations(params: ColorPresentationParams): ColorPresentation[] { + protected getColorPresentations (params: ColorPresentationParams): ColorPresentation[] { const document = this.documents.get(params.textDocument.uri); if (!document) { return []; @@ -134,14 +133,14 @@ export class JsonServer { return this.jsonService.getColorPresentations(document, jsonDocument, params.color, params.range); } - protected codeAction(params: CodeActionParams): Command[] { + protected codeAction (params: CodeActionParams): Command[] { const document = this.documents.get(params.textDocument.uri); if (!document) { return []; } return [{ - title: "Upper Case Document", - command: "json.documentUpper", + title: 'Upper Case Document', + command: 'json.documentUpper', // Send a VersionedTextDocumentIdentifier arguments: [{ ...params.textDocument, @@ -150,12 +149,12 @@ export class JsonServer { }]; } - protected format(params: DocumentRangeFormattingParams): TextEdit[] { + protected format (params: DocumentRangeFormattingParams): TextEdit[] { const document = this.documents.get(params.textDocument.uri); return document ? this.jsonService.format(document, params.range, params.options) : []; } - protected findDocumentSymbols(params: DocumentSymbolParams): SymbolInformation[] { + protected findDocumentSymbols (params: DocumentSymbolParams): SymbolInformation[] { const document = this.documents.get(params.textDocument.uri); if (!document) { return []; @@ -164,8 +163,8 @@ export class JsonServer { return this.jsonService.findDocumentSymbols(document, jsonDocument); } - protected executeCommand(params: ExecuteCommandParams): any { - if (params.command === "json.documentUpper" && params.arguments) { + protected executeCommand (params: ExecuteCommandParams): any { + if (params.command === 'json.documentUpper' && params.arguments) { const versionedTextDocumentIdentifier = params.arguments[0]; const document = this.documents.get(versionedTextDocumentIdentifier.uri); if (document) { @@ -185,7 +184,7 @@ export class JsonServer { } } - protected hover(params: TextDocumentPositionParams): Thenable { + protected hover (params: TextDocumentPositionParams): Thenable { const document = this.documents.get(params.textDocument.uri); if (!document) { return Promise.resolve(null); @@ -194,30 +193,29 @@ export class JsonServer { return this.jsonService.doHover(document, params.position, jsonDocument); } - protected async resolveSchema(url: string): Promise { + protected async resolveSchema (url: string): Promise { const uri = URI.parse(url); if (uri.scheme === 'file') { return new Promise((resolve, reject) => { fs.readFile(uri.fsPath, { encoding: 'utf8' }, (err, result) => { - err ? reject('') : resolve(result.toString()); + err ? reject(err) : resolve(result.toString()); }); }); } try { const response = await xhr({ url, followRedirects: 5 }); return response.responseText; - } - catch (error: unknown) { + } catch (error: unknown) { const err = error as Record; return Promise.reject(err.responseText || getErrorStatusDescription(err.status as number) || err.toString()); } } - protected resolveCompletion(item: CompletionItem): Thenable { + protected resolveCompletion (item: CompletionItem): Thenable { return this.jsonService.doResolve(item); } - protected completion(params: TextDocumentPositionParams): Thenable { + protected completion (params: TextDocumentPositionParams): Thenable { const document = this.documents.get(params.textDocument.uri); if (!document) { return Promise.resolve(null); @@ -226,7 +224,7 @@ export class JsonServer { return this.jsonService.doComplete(document, params.position, jsonDocument); } - protected validate(document: TextDocumentImpl.TextDocument): void { + protected validate (document: TextDocumentImpl.TextDocument): void { this.cleanPendingValidation(document); this.pendingValidationRequests.set(document.uri, setTimeout(() => { this.pendingValidationRequests.delete(document.uri); @@ -234,7 +232,7 @@ export class JsonServer { })); } - protected cleanPendingValidation(document: TextDocumentImpl.TextDocument): void { + protected cleanPendingValidation (document: TextDocumentImpl.TextDocument): void { const request = this.pendingValidationRequests.get(document.uri); if (request !== undefined) { clearTimeout(request); @@ -242,7 +240,7 @@ export class JsonServer { } } - protected doValidate(document: TextDocumentImpl.TextDocument): void { + protected doValidate (document: TextDocumentImpl.TextDocument): void { if (document.getText().length === 0) { this.cleanDiagnostics(document); return; @@ -253,18 +251,17 @@ export class JsonServer { ); } - protected cleanDiagnostics(document: TextDocumentImpl.TextDocument): void { + protected cleanDiagnostics (document: TextDocumentImpl.TextDocument): void { this.sendDiagnostics(document, []); } - protected sendDiagnostics(document: TextDocumentImpl.TextDocument, diagnostics: Diagnostic[]): void { + protected sendDiagnostics (document: TextDocumentImpl.TextDocument, diagnostics: Diagnostic[]): void { this.connection.sendDiagnostics({ uri: document.uri, diagnostics }); } - protected getJSONDocument(document: TextDocumentImpl.TextDocument): JSONDocument { + protected getJSONDocument (document: TextDocumentImpl.TextDocument): JSONDocument { return this.jsonService.parseJSONDocument(document); } - } diff --git a/packages/examples/node/src/server.ts b/packages/examples/node/src/server.ts index 0451191c8..2efc39e31 100644 --- a/packages/examples/node/src/server.ts +++ b/packages/examples/node/src/server.ts @@ -2,13 +2,13 @@ * Copyright (c) 2018-2022 TypeFox GmbH (http://www.typefox.io). All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ -import * as ws from "ws"; -import * as http from "http"; -import * as url from "url"; -import * as net from "net"; -import express from "express"; -import * as rpc from "vscode-ws-jsonrpc"; -import { launch } from "./json-server-launcher"; +import * as ws from 'ws'; +import * as http from 'http'; +import * as url from 'url'; +import * as net from 'net'; +import express from 'express'; +import * as rpc from 'vscode-ws-jsonrpc'; +import { launch } from './json-server-launcher'; process.on('uncaughtException', function (err: any) { console.error('Uncaught Exception: ', err.toString()); @@ -29,7 +29,7 @@ const wss = new ws.Server({ perMessageDeflate: false }); server.on('upgrade', (request: http.IncomingMessage, socket: net.Socket, head: Buffer) => { - const pathname = request.url ? url.parse(request.url).pathname : undefined; + const pathname = request.url ? new url.URL(request.url).pathname : undefined; if (pathname === '/sampleServer') { wss.handleUpgrade(request, socket, head, webSocket => { const socket: rpc.IWebSocket = { @@ -51,4 +51,4 @@ server.on('upgrade', (request: http.IncomingMessage, socket: net.Socket, head: B } }); } -}) +}); diff --git a/packages/vscode-ws-jsonrpc/src/connection.ts b/packages/vscode-ws-jsonrpc/src/connection.ts index 69389a49e..6a4b7d0a4 100644 --- a/packages/vscode-ws-jsonrpc/src/connection.ts +++ b/packages/vscode-ws-jsonrpc/src/connection.ts @@ -6,7 +6,7 @@ import { MessageConnection, Logger } from 'vscode-jsonrpc'; import { createWebSocketConnection, IWebSocket } from './socket'; import { ConsoleLogger } from './logger'; -export function listen(options: { +export function listen (options: { webSocket: WebSocket; logger?: Logger; onConnection: (connection: MessageConnection) => void; @@ -20,16 +20,22 @@ export function listen(options: { }; } -export function toSocket(webSocket: WebSocket): IWebSocket { +export function toSocket (webSocket: WebSocket): IWebSocket { return { send: content => webSocket.send(content), - onMessage: cb => webSocket.onmessage = event => cb(event.data), - onError: cb => webSocket.onerror = event => { - if ('message' in event) { - cb((event as any).message) - } + onMessage: cb => { + webSocket.onmessage = event => cb(event.data); + }, + onError: cb => { + webSocket.onerror = event => { + if ('message' in event) { + cb((event as any).message); + } + }; + }, + onClose: cb => { + webSocket.onclose = event => cb(event.code, event.reason); }, - onClose: cb => webSocket.onclose = event => cb(event.code, event.reason), dispose: () => webSocket.close() - } -} \ No newline at end of file + }; +} diff --git a/packages/vscode-ws-jsonrpc/src/disposable.ts b/packages/vscode-ws-jsonrpc/src/disposable.ts index 084cd8173..be45dde0b 100644 --- a/packages/vscode-ws-jsonrpc/src/disposable.ts +++ b/packages/vscode-ws-jsonrpc/src/disposable.ts @@ -6,28 +6,27 @@ import { Disposable } from 'vscode-jsonrpc/lib/common/disposable'; export { Disposable -} +}; export class DisposableCollection implements Disposable { protected readonly disposables: Disposable[] = []; - dispose(): void { + dispose (): void { while (this.disposables.length !== 0) { this.disposables.pop()!.dispose(); } } - push(disposable: Disposable): Disposable { + push (disposable: Disposable): Disposable { const disposables = this.disposables; disposables.push(disposable); return { - dispose(): void { + dispose (): void { const index = disposables.indexOf(disposable); if (index !== -1) { disposables.splice(index, 1); } } - } + }; } - -} \ No newline at end of file +} diff --git a/packages/vscode-ws-jsonrpc/src/index.ts b/packages/vscode-ws-jsonrpc/src/index.ts index 6ead0b180..e5daef8f7 100644 --- a/packages/vscode-ws-jsonrpc/src/index.ts +++ b/packages/vscode-ws-jsonrpc/src/index.ts @@ -7,4 +7,4 @@ export * from 'vscode-jsonrpc/lib/common/messages'; export * from './disposable'; export * from './socket'; export * from './logger'; -export * from './connection'; \ No newline at end of file +export * from './connection'; diff --git a/packages/vscode-ws-jsonrpc/src/logger.ts b/packages/vscode-ws-jsonrpc/src/logger.ts index c1d292236..afbc4a6a8 100644 --- a/packages/vscode-ws-jsonrpc/src/logger.ts +++ b/packages/vscode-ws-jsonrpc/src/logger.ts @@ -2,26 +2,26 @@ * Copyright (c) 2018 TypeFox GmbH (http://www.typefox.io). All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ -import { Logger } from "vscode-jsonrpc"; +import { Logger } from 'vscode-jsonrpc'; export class ConsoleLogger implements Logger { - public error(message: string): void { + public error (message: string): void { console.error(message); } - public warn(message: string): void { + public warn (message: string): void { console.warn(message); } - public info(message: string): void { + public info (message: string): void { console.info(message); } - public log(message: string): void { + public log (message: string): void { console.log(message); } - public debug(message: string): void { + public debug (message: string): void { console.debug(message); } } diff --git a/packages/vscode-ws-jsonrpc/src/server/connection.ts b/packages/vscode-ws-jsonrpc/src/server/connection.ts index 88d570e9e..6c6a9f726 100644 --- a/packages/vscode-ws-jsonrpc/src/server/connection.ts +++ b/packages/vscode-ws-jsonrpc/src/server/connection.ts @@ -3,14 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ import { MessageReader, MessageWriter, Disposable, Message } from 'vscode-jsonrpc'; -import { DisposableCollection } from "../disposable"; - -export function forward(clientConnection: IConnection, serverConnection: IConnection, map?: (message: Message) => Message): void { - clientConnection.forward(serverConnection, map); - serverConnection.forward(clientConnection, map); - clientConnection.onClose(() => serverConnection.dispose()); - serverConnection.onClose(() => clientConnection.dispose()); -} +import { DisposableCollection } from '../disposable'; export interface IConnection extends Disposable { readonly reader: MessageReader; @@ -19,20 +12,28 @@ export interface IConnection extends Disposable { onClose(callback: () => void): Disposable; } -export function createConnection(reader: MessageReader, writer: MessageWriter, onDispose: () => void, - extensions: T = {} as T): IConnection & T { +export function forward (clientConnection: IConnection, serverConnection: IConnection, map?: (message: Message) => Message): void { + clientConnection.forward(serverConnection, map); + serverConnection.forward(clientConnection, map); + clientConnection.onClose(() => serverConnection.dispose()); + serverConnection.onClose(() => clientConnection.dispose()); +} + +export function createConnection (reader: MessageReader, writer: MessageWriter, onDispose: () => void, + extensions: T = {} as T): IConnection & T { const disposeOnClose = new DisposableCollection(); reader.onClose(() => disposeOnClose.dispose()); writer.onClose(() => disposeOnClose.dispose()); return { - reader, writer, - forward(to: IConnection, map: (message: Message) => Message = (message) => message): void { + reader, + writer, + forward (to: IConnection, map: (message: Message) => Message = (message) => message): void { reader.listen(input => { const output = map(input); - to.writer.write(output) + to.writer.write(output); }); }, - onClose(callback: () => void): Disposable { + onClose (callback: () => void): Disposable { return disposeOnClose.push(Disposable.create(callback)); }, dispose: () => onDispose(), diff --git a/packages/vscode-ws-jsonrpc/src/server/index.ts b/packages/vscode-ws-jsonrpc/src/server/index.ts index c10b4c95b..da5faafcd 100644 --- a/packages/vscode-ws-jsonrpc/src/server/index.ts +++ b/packages/vscode-ws-jsonrpc/src/server/index.ts @@ -3,4 +3,4 @@ * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ export * from './connection'; -export * from './launch'; \ No newline at end of file +export * from './launch'; diff --git a/packages/vscode-ws-jsonrpc/src/server/launch.ts b/packages/vscode-ws-jsonrpc/src/server/launch.ts index 838da62a4..a3205181b 100644 --- a/packages/vscode-ws-jsonrpc/src/server/launch.ts +++ b/packages/vscode-ws-jsonrpc/src/server/launch.ts @@ -6,11 +6,11 @@ import * as net from 'net'; import * as stream from 'stream'; import * as cp from 'child_process'; -import { StreamMessageReader, StreamMessageWriter, SocketMessageReader, SocketMessageWriter } from "vscode-jsonrpc/node"; -import { IConnection, createConnection } from "./connection"; +import { StreamMessageReader, StreamMessageWriter, SocketMessageReader, SocketMessageWriter } from 'vscode-jsonrpc/node'; +import { IConnection, createConnection } from './connection'; import { IWebSocket, WebSocketMessageReader, WebSocketMessageWriter, IWebSocketConnection } from '../socket'; -export function createServerProcess(serverName: string, command: string, args?: string[], options?: cp.SpawnOptions): IConnection | undefined { +export function createServerProcess (serverName: string, command: string, args?: string[], options?: cp.SpawnOptions): IConnection | undefined { const serverProcess = cp.spawn(command, args || [], options || {}); serverProcess.on('error', error => console.error(`Launching ${serverName} Server failed: ${error}`) @@ -23,23 +23,23 @@ export function createServerProcess(serverName: string, command: string, args?: return createProcessStreamConnection(serverProcess); } -export function createWebSocketConnection(socket: IWebSocket): IWebSocketConnection { +export function createWebSocketConnection (socket: IWebSocket): IWebSocketConnection { const reader = new WebSocketMessageReader(socket); const writer = new WebSocketMessageWriter(socket); return createConnection(reader, writer, () => socket.dispose(), { socket }); } -export function createProcessSocketConnection(process: cp.ChildProcess, outSocket: net.Socket, inSocket: net.Socket = outSocket): IConnection { +export function createProcessSocketConnection (process: cp.ChildProcess, outSocket: net.Socket, inSocket: net.Socket = outSocket): IConnection { return createSocketConnection(outSocket, inSocket, () => process.kill()); } -export function createSocketConnection(outSocket: net.Socket, inSocket: net.Socket, onDispose: () => void): IConnection { +export function createSocketConnection (outSocket: net.Socket, inSocket: net.Socket, onDispose: () => void): IConnection { const reader = new SocketMessageReader(outSocket); const writer = new SocketMessageWriter(inSocket); return createConnection(reader, writer, onDispose); } -export function createProcessStreamConnection(process: cp.ChildProcess): IConnection | undefined { +export function createProcessStreamConnection (process: cp.ChildProcess): IConnection | undefined { if (process.stdout !== null && process.stdin !== null) { return createStreamConnection(process.stdout, process.stdin, () => process.kill()); } else { @@ -47,9 +47,8 @@ export function createProcessStreamConnection(process: cp.ChildProcess): IConnec } } -export function createStreamConnection(outStream: stream.Readable, inStream: stream.Writable, onDispose: () => void): IConnection { +export function createStreamConnection (outStream: stream.Readable, inStream: stream.Writable, onDispose: () => void): IConnection { const reader = new StreamMessageReader(outStream); const writer = new StreamMessageWriter(inStream); return createConnection(reader, writer, onDispose); } - diff --git a/packages/vscode-ws-jsonrpc/src/socket/connection.ts b/packages/vscode-ws-jsonrpc/src/socket/connection.ts index 7eceea581..506688359 100644 --- a/packages/vscode-ws-jsonrpc/src/socket/connection.ts +++ b/packages/vscode-ws-jsonrpc/src/socket/connection.ts @@ -2,12 +2,12 @@ * Copyright (c) 2018 TypeFox GmbH (http://www.typefox.io). All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ -import { MessageConnection, createMessageConnection, Logger } from "vscode-jsonrpc"; -import { IWebSocket } from "./socket"; -import { WebSocketMessageReader } from "./reader"; -import { WebSocketMessageWriter } from "./writer"; +import { MessageConnection, createMessageConnection, Logger } from 'vscode-jsonrpc'; +import { IWebSocket } from './socket'; +import { WebSocketMessageReader } from './reader'; +import { WebSocketMessageWriter } from './writer'; -export function createWebSocketConnection(socket: IWebSocket, logger: Logger): MessageConnection { +export function createWebSocketConnection (socket: IWebSocket, logger: Logger): MessageConnection { const messageReader = new WebSocketMessageReader(socket); const messageWriter = new WebSocketMessageWriter(socket); const connection = createMessageConnection(messageReader, messageWriter, logger); diff --git a/packages/vscode-ws-jsonrpc/src/socket/reader.ts b/packages/vscode-ws-jsonrpc/src/socket/reader.ts index 04ed0981e..a68c2ca01 100644 --- a/packages/vscode-ws-jsonrpc/src/socket/reader.ts +++ b/packages/vscode-ws-jsonrpc/src/socket/reader.ts @@ -3,17 +3,16 @@ * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ -import { Disposable } from "vscode-jsonrpc"; -import { DataCallback, AbstractMessageReader, MessageReader } from "vscode-jsonrpc/lib/common/messageReader"; -import { IWebSocket } from "./socket"; +import { Disposable } from 'vscode-jsonrpc'; +import { DataCallback, AbstractMessageReader, MessageReader } from 'vscode-jsonrpc/lib/common/messageReader'; +import { IWebSocket } from './socket'; export class WebSocketMessageReader extends AbstractMessageReader implements MessageReader { - protected state: 'initial' | 'listening' | 'closed' = 'initial'; protected callback: DataCallback | undefined; protected readonly events: { message?: any, error?: any }[] = []; - constructor(protected readonly socket: IWebSocket) { + constructor (protected readonly socket: IWebSocket) { super(); this.socket.onMessage(message => this.readMessage(message) @@ -33,7 +32,7 @@ export class WebSocketMessageReader extends AbstractMessageReader implements Mes }); } - listen(callback: DataCallback): Disposable { + listen (callback: DataCallback): Disposable { if (this.state === 'initial') { this.state = 'listening'; this.callback = callback; @@ -51,13 +50,13 @@ export class WebSocketMessageReader extends AbstractMessageReader implements Mes return { dispose: () => { if (this.callback === callback) { - this.callback = undefined + this.callback = undefined; } } - } + }; } - protected readMessage(message: any): void { + protected readMessage (message: any): void { if (this.state === 'initial') { this.events.splice(0, 0, { message }); } else if (this.state === 'listening') { @@ -66,7 +65,7 @@ export class WebSocketMessageReader extends AbstractMessageReader implements Mes } } - protected fireError(error: any): void { + protected fireError (error: any): void { if (this.state === 'initial') { this.events.splice(0, 0, { error }); } else if (this.state === 'listening') { @@ -74,7 +73,7 @@ export class WebSocketMessageReader extends AbstractMessageReader implements Mes } } - protected fireClose(): void { + protected fireClose (): void { if (this.state === 'initial') { this.events.splice(0, 0, {}); } else if (this.state === 'listening') { @@ -82,5 +81,4 @@ export class WebSocketMessageReader extends AbstractMessageReader implements Mes } this.state = 'closed'; } - } diff --git a/packages/vscode-ws-jsonrpc/src/socket/socket.ts b/packages/vscode-ws-jsonrpc/src/socket/socket.ts index 87727566f..b301d86c5 100644 --- a/packages/vscode-ws-jsonrpc/src/socket/socket.ts +++ b/packages/vscode-ws-jsonrpc/src/socket/socket.ts @@ -2,8 +2,8 @@ * Copyright (c) 2018 TypeFox GmbH (http://www.typefox.io). All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ -import { Disposable } from "../disposable"; -import { IConnection } from "../server/connection"; +import { Disposable } from '../disposable'; +import { IConnection } from '../server/connection'; export interface IWebSocket extends Disposable { send(content: string): void; diff --git a/packages/vscode-ws-jsonrpc/src/socket/writer.ts b/packages/vscode-ws-jsonrpc/src/socket/writer.ts index eaef57556..2ffe7a006 100644 --- a/packages/vscode-ws-jsonrpc/src/socket/writer.ts +++ b/packages/vscode-ws-jsonrpc/src/socket/writer.ts @@ -3,22 +3,21 @@ * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ -import { Message } from "vscode-jsonrpc/lib/common/messages"; -import { AbstractMessageWriter, MessageWriter } from "vscode-jsonrpc/lib/common/messageWriter"; -import { IWebSocket } from "./socket"; +import { Message } from 'vscode-jsonrpc/lib/common/messages'; +import { AbstractMessageWriter, MessageWriter } from 'vscode-jsonrpc/lib/common/messageWriter'; +import { IWebSocket } from './socket'; export class WebSocketMessageWriter extends AbstractMessageWriter implements MessageWriter { - protected errorCount = 0; - constructor(protected readonly socket: IWebSocket) { + constructor (protected readonly socket: IWebSocket) { super(); } - end(): void { + end (): void { } - async write(msg: Message): Promise { + async write (msg: Message): Promise { try { const content = JSON.stringify(msg); this.socket.send(content); @@ -27,5 +26,4 @@ export class WebSocketMessageWriter extends AbstractMessageWriter implements Mes this.fireError(e, msg, this.errorCount); } } - }