|
| 1 | +import tsNextPluginFactory from 'next' |
| 2 | +import ts from 'typescript' |
| 3 | +export { NEXT_TS_ERRORS } from 'next/dist/server/typescript/constant' |
| 4 | + |
| 5 | +export type PluginLanguageService = ts.LanguageService & { |
| 6 | + getCapturedLogs: () => string |
| 7 | +} |
| 8 | + |
| 9 | +export function getPluginLanguageService(dir: string): PluginLanguageService { |
| 10 | + const files = ts.sys.readDirectory(dir) |
| 11 | + |
| 12 | + const compilerOptions = ts.getDefaultCompilerOptions() |
| 13 | + const compilerHost = ts.createCompilerHost(compilerOptions) |
| 14 | + |
| 15 | + let logs = '' |
| 16 | + const logger = { |
| 17 | + info: (...args: any[]) => { |
| 18 | + const message = args |
| 19 | + .map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))) |
| 20 | + .join(' ') |
| 21 | + logs += message + '\n' |
| 22 | + console.log(...args) |
| 23 | + }, |
| 24 | + } |
| 25 | + |
| 26 | + const languageServiceHost: ts.LanguageServiceHost = { |
| 27 | + ...compilerHost, |
| 28 | + getCompilationSettings: () => compilerOptions, |
| 29 | + getScriptFileNames: () => files, |
| 30 | + getScriptSnapshot: (fileName) => { |
| 31 | + const contents = ts.sys.readFile(fileName) |
| 32 | + if (contents && typeof contents === 'string') { |
| 33 | + return ts.ScriptSnapshot.fromString(contents) |
| 34 | + } |
| 35 | + return |
| 36 | + }, |
| 37 | + getScriptVersion: () => '0', |
| 38 | + writeFile: ts.sys.writeFile, |
| 39 | + } |
| 40 | + |
| 41 | + const languageService = ts.createLanguageService(languageServiceHost) |
| 42 | + |
| 43 | + const pluginCreateInfo: ts.server.PluginCreateInfo = { |
| 44 | + project: { |
| 45 | + projectService: { |
| 46 | + logger, |
| 47 | + }, |
| 48 | + getCurrentDirectory: () => dir, |
| 49 | + } as unknown as ts.server.Project, |
| 50 | + languageService, |
| 51 | + languageServiceHost, |
| 52 | + serverHost: null, |
| 53 | + config: {}, |
| 54 | + } |
| 55 | + |
| 56 | + const plugin: ts.server.PluginModule = ( |
| 57 | + tsNextPluginFactory as unknown as ts.server.PluginModuleFactory |
| 58 | + )({ typescript: ts }) |
| 59 | + |
| 60 | + const service = plugin.create(pluginCreateInfo) as PluginLanguageService |
| 61 | + |
| 62 | + // Add a custom method to get captured logs |
| 63 | + service.getCapturedLogs = () => logs |
| 64 | + |
| 65 | + return service |
| 66 | +} |
| 67 | + |
| 68 | +export function getTsFiles(dir: string): string[] { |
| 69 | + return ts.sys.readDirectory(dir) |
| 70 | +} |
0 commit comments