Path: blob/main/build/lib/typeScriptLanguageServiceHost.ts
4770 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import ts from 'typescript';6import fs from 'node:fs';7import { normalize } from 'node:path';89export type IFileMap = Map</*fileName*/ string, string>;1011function normalizePath(filePath: string): string {12return normalize(filePath);13}1415/**16* A TypeScript language service host17*/18export class TypeScriptLanguageServiceHost implements ts.LanguageServiceHost {1920private readonly ts: typeof import('typescript');21private readonly topLevelFiles: IFileMap;22private readonly compilerOptions: ts.CompilerOptions;2324constructor(25ts: typeof import('typescript'),26topLevelFiles: IFileMap,27compilerOptions: ts.CompilerOptions,28) {29this.ts = ts;30this.topLevelFiles = topLevelFiles;31this.compilerOptions = compilerOptions;32}3334// --- language service host ---------------35getCompilationSettings(): ts.CompilerOptions {36return this.compilerOptions;37}38getScriptFileNames(): string[] {39return [40...this.topLevelFiles.keys(),41this.ts.getDefaultLibFilePath(this.compilerOptions)42];43}44getScriptVersion(_fileName: string): string {45return '1';46}47getProjectVersion(): string {48return '1';49}50getScriptSnapshot(fileName: string): ts.IScriptSnapshot {51fileName = normalizePath(fileName);5253if (this.topLevelFiles.has(fileName)) {54return this.ts.ScriptSnapshot.fromString(this.topLevelFiles.get(fileName)!);55} else {56return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString());57}58}59getScriptKind(_fileName: string): ts.ScriptKind {60return this.ts.ScriptKind.TS;61}62getCurrentDirectory(): string {63return '';64}65getDefaultLibFileName(options: ts.CompilerOptions): string {66return this.ts.getDefaultLibFilePath(options);67}68readFile(path: string, encoding?: string): string | undefined {69path = normalizePath(path);7071if (this.topLevelFiles.get(path)) {72return this.topLevelFiles.get(path);73}74return ts.sys.readFile(path, encoding);75}76fileExists(path: string): boolean {77path = normalizePath(path);7879if (this.topLevelFiles.has(path)) {80return true;81}82return ts.sys.fileExists(path);83}84}858687