Skip to content

Commit

Permalink
refactor: clean code with @tsconfig/node16-strictest-esm
Browse files Browse the repository at this point in the history
  • Loading branch information
fi3ework committed Aug 26, 2022
1 parent b43977f commit f0d9ce6
Show file tree
Hide file tree
Showing 18 changed files with 98 additions and 108 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
]
},
"devDependencies": {
"@tsconfig/node16-strictest-esm": "^1.0.3",
"@types/babel__code-frame": "^7.0.2",
"@types/debug": "^4.1.5",
"@types/fs-extra": "^9.0.11",
Expand Down
2 changes: 1 addition & 1 deletion packages/vite-plugin-checker/__tests__/codeFrame.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'

import { SourceLocation } from '@babel/code-frame'
import type { SourceLocation } from '@babel/code-frame'

import { tsLocationToBabelLocation } from '../src/codeFrame'

Expand Down
6 changes: 1 addition & 5 deletions packages/vite-plugin-checker/__tests__/logger.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { describe, expect, it } from 'vitest'
import strip from 'strip-ansi'

import {
diagnosticToTerminalLog,
NormalizedDiagnostic,
normalizeEslintDiagnostic,
} from '../src/logger'
import { diagnosticToTerminalLog, normalizeEslintDiagnostic } from '../src/logger'
import {
error1 as eslintError1,
warning1 as eslintWarning1,
Expand Down
9 changes: 6 additions & 3 deletions packages/vite-plugin-checker/__tests__/vlsConfig.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ import { prepareClientConnection, logLevel2Severity } from '../src/checkers/vls/

async function testVslConfig(overrideConfig?: any) {
const workspaceUri = URI.file(path.join(__dirname, 'fixtures'))
const { clientConnection, serverConnection, vls, up, down, logger } =
await prepareClientConnection(workspaceUri, logLevel2Severity['WARN'], {
const { clientConnection, serverConnection, vls, up, down } = await prepareClientConnection(
workspaceUri,
logLevel2Severity['WARN'],
{
watch: false,
verbose: false,
config: overrideConfig || null,
})
}
)

// @ts-expect-error
expect(vls.workspaceConfig).toMatchSnapshot()
Expand Down
12 changes: 7 additions & 5 deletions packages/vite-plugin-checker/src/Checker.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import invariant from 'tiny-invariant'
import { isMainThread, threadId } from 'worker_threads'
import { isInVitestEntryThread, isMainThread } from './utils.js'

import { ServeAndBuildChecker, BuildInCheckerNames } from './types.js'
import type { ServeAndBuildChecker, BuildInCheckerNames } from './types.js'
import { createScript, Script } from './worker.js'

// still an only issue https://github.com/microsoft/TypeScript/issues/29808#issuecomment-829750974
import type {} from 'vite'
import type { CreateDiagnostic, BuildInCheckers } from './types.js'

if (!(isMainThread || (threadId === 1 && process.env.VITEST))) {
if (!(isMainThread || isInVitestEntryThread)) {
process.stdout.isTTY = true
}

Expand Down Expand Up @@ -59,16 +59,18 @@ export abstract class Checker<T extends BuildInCheckerNames> implements CheckerM
public initMainThread() {
invariant(this.script, `script should be created in 'prepare', but got ${this.script}`)

if (isMainThread || (threadId === 1 && process.env.VITEST)) {
if (isMainThread || isInVitestEntryThread) {
const createServeAndBuild = this.script.mainScript()
return createServeAndBuild
}

return
}

public initWorkerThread() {
invariant(this.script, `script should be created in 'prepare', but got ${this.script}`)

if (!(isMainThread || (threadId === 1 && process.env.VITEST))) {
if (!(isMainThread || isInVitestEntryThread)) {
this.script.workerScript()
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vite-plugin-checker/src/FileDiagnosticManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class FileDiagnosticManager {

public updateByFileId(fileId: string, next: NormalizedDiagnostic[] | null) {
for (let i = 0; i < this.diagnostics.length; i++) {
if (this.diagnostics[i].id === fileId) {
if (this.diagnostics[i]?.id === fileId) {
this.diagnostics.splice(i, 1)
i--
}
Expand Down
9 changes: 2 additions & 7 deletions packages/vite-plugin-checker/src/checkers/typescript/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import os from 'os'
import path from 'path'
import invariant from 'tiny-invariant'
import ts from 'typescript'
import { parentPort } from 'worker_threads'
import { fileURLToPath } from 'url'
import { parentPort } from 'worker_threads'

import { Checker } from '../../Checker.js'
import {
Expand All @@ -15,12 +15,7 @@ import {
toViteCustomPayload,
wrapCheckerSummary,
} from '../../logger.js'
import {
ACTION_TYPES,
CreateDiagnostic,
DiagnosticLevel,
DiagnosticToRuntime,
} from '../../types.js'
import { ACTION_TYPES, CreateDiagnostic, DiagnosticToRuntime } from '../../types.js'

const __filename = fileURLToPath(import.meta.url)
let createServeAndBuild
Expand Down
85 changes: 42 additions & 43 deletions packages/vite-plugin-checker/src/checkers/vls/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import os from 'os'
import path from 'path'
import { Duplex } from 'stream'
import { VLS } from 'vls'
import { TextDocument } from 'vscode-languageserver-textdocument'
import type { TextDocument } from 'vscode-languageserver-textdocument'
import {
createConnection,
createProtocolConnection,
Expand All @@ -33,7 +33,7 @@ import {
normalizePublishDiagnosticParams,
NormalizedDiagnostic,
} from '../../logger.js'
import { DeepPartial } from '../../types.js'
import type { DeepPartial } from '../../types.js'
import { getInitParams, VlsOptions } from './initParams.js'

import { FileDiagnosticManager } from '../../FileDiagnosticManager.js'
Expand Down Expand Up @@ -107,11 +107,11 @@ class NullLogger implements Logger {
}

export class TestStream extends Duplex {
public _write(chunk: string, _encoding: string, done: () => void) {
public override _write(chunk: string, _encoding: string, done: () => void) {
this.emit('data', chunk)
done()
}
public _read(_size: number) {}
public override _read(_size: number) {}
}

function suppressConsole() {
Expand Down Expand Up @@ -266,47 +266,46 @@ async function getDiagnostics(

// build mode - step 2
// use $/getDiagnostics to get diagnostics from server side directly
if (!options.watch) {
try {
let diagnostics = (await clientConnection.sendRequest('$/getDiagnostics', {
uri: URI.file(absFilePath).toString(),
version: DOC_VERSION.init,
})) as Diagnostic[]

diagnostics = filterDiagnostics(diagnostics, severity)
let logChunk = ''
if (diagnostics.length > 0) {
logChunk +=
os.EOL +
diagnostics
.map((d) =>
diagnosticToTerminalLog(
normalizeLspDiagnostic({
diagnostic: d,
absFilePath,
fileText,
}),
'VLS'
)
if (options.watch) return
try {
let diagnostics = (await clientConnection.sendRequest('$/getDiagnostics', {
uri: URI.file(absFilePath).toString(),
version: DOC_VERSION.init,
})) as Diagnostic[]

diagnostics = filterDiagnostics(diagnostics, severity)
let logChunk = ''
if (diagnostics.length > 0) {
logChunk +=
os.EOL +
diagnostics
.map((d) =>
diagnosticToTerminalLog(
normalizeLspDiagnostic({
diagnostic: d,
absFilePath,
fileText,
}),
'VLS'
)
.join(os.EOL)

diagnostics.forEach((d) => {
if (d.severity === DiagnosticSeverity.Error) {
initialErrorCount++
}
if (d.severity === DiagnosticSeverity.Warning) {
initialWarningCount++
}
})
}

console.log(logChunk)
return { initialErrorCount, initialWarningCount }
} catch (err: any) {
console.error(err.stack)
return { initialErrorCount, initialWarningCount }
)
.join(os.EOL)

diagnostics.forEach((d) => {
if (d.severity === DiagnosticSeverity.Error) {
initialErrorCount++
}
if (d.severity === DiagnosticSeverity.Warning) {
initialWarningCount++
}
})
}

console.log(logChunk)
return { initialErrorCount, initialWarningCount }
} catch (err: any) {
console.error(err.stack)
return { initialErrorCount, initialWarningCount }
}
})
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { URI } from 'vscode-uri'
import type { URI } from 'vscode-uri'

import type { InitializeParams } from 'vscode-languageserver/node'

Expand Down
2 changes: 1 addition & 1 deletion packages/vite-plugin-checker/src/checkers/vueTsc/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createRequire } from 'module'
import os from 'os'
import path from 'path'
import invariant from 'tiny-invariant'
import ts from 'typescript'
import type ts from 'typescript'
import { fileURLToPath } from 'url'
import { parentPort } from 'worker_threads'

Expand Down
2 changes: 1 addition & 1 deletion packages/vite-plugin-checker/src/codeFrame.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os from 'os'
import ts from 'typescript'
import type ts from 'typescript'

import { codeFrameColumns, SourceLocation } from '@babel/code-frame'

Expand Down
21 changes: 11 additions & 10 deletions packages/vite-plugin-checker/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import chalk from 'chalk'
import fs from 'fs'
import { createRequire } from 'module'
import os from 'os'
import strip from 'strip-ansi'
import { CustomPayload } from 'vite'
// import { URI } from 'vscode-uri'
import vscodeUri from 'vscode-uri'
const { URI } = vscodeUri
import { isMainThread, parentPort, threadId } from 'worker_threads'
import { createRequire } from 'module'
const _require = createRequire(import.meta.url)
import { parentPort } from 'worker_threads'

import { codeFrameColumns, SourceLocation } from '@babel/code-frame'

import { WS_CHECKER_ERROR_EVENT } from './client/index.js'
import { ACTION_TYPES, DiagnosticToRuntime, DiagnosticLevel } from './types.js'
import { ACTION_TYPES, DiagnosticLevel, DiagnosticToRuntime } from './types.js'
import { isMainThread } from './utils.js'

import type { CustomPayload } from 'vite'
const _require = createRequire(import.meta.url)
import type { Range } from 'vscode-languageclient'
import type { ESLint } from 'eslint'
import type {
Expand All @@ -27,6 +27,7 @@ import type {
LineAndCharacter,
} from 'typescript'

const { URI } = vscodeUri
export interface NormalizedDiagnostic {
/** error message */
message?: string
Expand Down Expand Up @@ -119,7 +120,7 @@ export function diagnosticToRuntimeError(
let loc: DiagnosticToRuntime['loc']
if (d.loc) {
loc = {
file: d.id,
file: d.id ?? '',
line: d.loc.start.line,
column: typeof d.loc.start.column === 'number' ? d.loc.start.column : 0,
}
Expand All @@ -137,7 +138,7 @@ export function diagnosticToRuntimeError(
}
})

return Array.isArray(diagnostics) ? results : results[0]
return Array.isArray(diagnostics) ? results : results[0]!
}

export function toViteCustomPayload(id: string, diagnostics: DiagnosticToRuntime[]): CustomPayload {
Expand Down Expand Up @@ -387,7 +388,7 @@ export function ensureCall(callback: CallableFunction) {
}

export function consoleLog(value: string) {
if (isMainThread || (threadId === 1 && process.env.VITEST)) {
if (isMainThread) {
console.log(value)
} else {
parentPort?.postMessage({
Expand Down
10 changes: 7 additions & 3 deletions packages/vite-plugin-checker/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import { spawn } from 'child_process'
import pick from 'lodash.pick'
import npmRunPath from 'npm-run-path'
import path from 'path'
import { ConfigEnv, Plugin, ResolvedConfig } from 'vite'
import { createRequire } from 'module'
// const _require = createRequire(import.meta.url)
import type { ConfigEnv, Plugin, ResolvedConfig } from 'vite'
import { Checker } from './Checker.js'
import { RUNTIME_PUBLIC_PATH, runtimeCode, WS_CHECKER_RECONNECT_EVENT } from './client/index.js'
import {
Expand Down Expand Up @@ -91,13 +89,17 @@ export function checker(userConfig: UserPluginConfig): Plugin {
return id
}
}

return
},
load(id) {
if (viteMode === 'serve') {
if (id === RUNTIME_PUBLIC_PATH) {
return runtimeCode
}
}

return
},
transform(code, id) {
if (id === RUNTIME_PUBLIC_PATH) {
Expand Down Expand Up @@ -150,6 +152,8 @@ inject({
},
]
}

return
},
buildStart: () => {
// only run in build mode
Expand Down
5 changes: 5 additions & 0 deletions packages/vite-plugin-checker/src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { isMainThread as _isMainThread, threadId } from 'worker_threads'

// since vitest run all cases in worker thread, we should compatible with it to pass E2E tests
export const isInVitestEntryThread = threadId === 1 && process.env['VITEST']
export const isMainThread = _isMainThread || isInVitestEntryThread
2 changes: 1 addition & 1 deletion packages/vite-plugin-checker/src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ConfigEnv } from 'vite'
import type { ConfigEnv } from 'vite'
import { parentPort, Worker, workerData } from 'worker_threads'

import { ACTION_TYPES } from './types.js'
Expand Down
17 changes: 3 additions & 14 deletions packages/vite-plugin-checker/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,9 @@
{
"extends": "@tsconfig/node16-strictest-esm/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"target": "ES2015",
"lib": ["ESNext"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true,
"forceConsistentCasingInFileNames": true,
//
"rootDir": "./",
"moduleResolution": "node",
"module": "ESNext"
"noUnusedParameters": false,
"exactOptionalPropertyTypes": false
},

"include": ["src", "__tests__"],
"exclude": ["src/@runtime"]
}
Loading

0 comments on commit f0d9ce6

Please sign in to comment.