|
| 1 | +import * as fs from 'mz/fs'; |
| 2 | +import * as path from 'path'; |
| 3 | +import * as ts from 'typescript'; |
| 4 | +import { Logger, NoopLogger } from './logging'; |
| 5 | +import { combinePaths } from './match-files'; |
| 6 | +import { PluginSettings } from './request-type'; |
| 7 | +import { toUnixPath } from './util'; |
| 8 | + |
| 9 | +// Based on types and logic from TypeScript server/project.ts @ |
| 10 | +// https://github.com/Microsoft/TypeScript/blob/711e890e59e10aa05a43cb938474a3d9c2270429/src/server/project.ts |
| 11 | + |
| 12 | +/** |
| 13 | + * A plugin exports an initialization function, injected with |
| 14 | + * the current typescript instance |
| 15 | + */ |
| 16 | +export type PluginModuleFactory = (mod: { typescript: typeof ts }) => PluginModule; |
| 17 | + |
| 18 | +export type EnableProxyFunc = (pluginModuleFactory: PluginModuleFactory, pluginConfigEntry: ts.PluginImport) => void; |
| 19 | + |
| 20 | +/** |
| 21 | + * A plugin presents this API when initialized |
| 22 | + */ |
| 23 | +export interface PluginModule { |
| 24 | + create(createInfo: PluginCreateInfo): ts.LanguageService; |
| 25 | + getExternalFiles?(proj: Project): string[]; |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * All of tsserver's environment exposed to plugins |
| 30 | + */ |
| 31 | +export interface PluginCreateInfo { |
| 32 | + project: Project; |
| 33 | + languageService: ts.LanguageService; |
| 34 | + languageServiceHost: ts.LanguageServiceHost; |
| 35 | + serverHost: ServerHost; |
| 36 | + config: any; |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * The portion of tsserver's Project API exposed to plugins |
| 41 | + */ |
| 42 | +export interface Project { |
| 43 | + projectService: { |
| 44 | + logger: Logger; |
| 45 | + }; |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * The portion of tsserver's ServerHost API exposed to plugins |
| 50 | + */ |
| 51 | +export type ServerHost = object; |
| 52 | + |
| 53 | +/** |
| 54 | + * The result of a node require: a module or an error. |
| 55 | + */ |
| 56 | +type RequireResult = { module: {}, error: undefined } | { module: undefined, error: {} }; |
| 57 | + |
| 58 | +export class PluginLoader { |
| 59 | + |
| 60 | + private allowLocalPluginLoads: boolean = false; |
| 61 | + private globalPlugins: string[] = []; |
| 62 | + private pluginProbeLocations: string[] = []; |
| 63 | + |
| 64 | + constructor( |
| 65 | + private rootFilePath: string, |
| 66 | + private fs: ts.ModuleResolutionHost, |
| 67 | + pluginSettings?: PluginSettings, |
| 68 | + private logger = new NoopLogger(), |
| 69 | + private resolutionHost = new LocalModuleResolutionHost(), |
| 70 | + private requireModule: (moduleName: string) => any = require) { |
| 71 | + if (pluginSettings) { |
| 72 | + this.allowLocalPluginLoads = pluginSettings.allowLocalPluginLoads || false; |
| 73 | + this.globalPlugins = pluginSettings.globalPlugins || []; |
| 74 | + this.pluginProbeLocations = pluginSettings.pluginProbeLocations || []; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + public loadPlugins(options: ts.CompilerOptions, applyProxy: EnableProxyFunc) { |
| 79 | + // Search our peer node_modules, then any globally-specified probe paths |
| 80 | + // ../../.. to walk from X/node_modules/javascript-typescript-langserver/lib/project-manager.js to X/node_modules/ |
| 81 | + const searchPaths = [combinePaths(__filename, '../../..'), ...this.pluginProbeLocations]; |
| 82 | + |
| 83 | + // Corresponds to --allowLocalPluginLoads, opt-in to avoid remote code execution. |
| 84 | + if (this.allowLocalPluginLoads) { |
| 85 | + const local = this.rootFilePath; |
| 86 | + this.logger.info(`Local plugin loading enabled; adding ${local} to search paths`); |
| 87 | + searchPaths.unshift(local); |
| 88 | + } |
| 89 | + |
| 90 | + let pluginImports: ts.PluginImport[] = []; |
| 91 | + if (options.plugins) { |
| 92 | + pluginImports = options.plugins as ts.PluginImport[]; |
| 93 | + } |
| 94 | + |
| 95 | + // Enable tsconfig-specified plugins |
| 96 | + if (options.plugins) { |
| 97 | + for (const pluginConfigEntry of pluginImports) { |
| 98 | + this.enablePlugin(pluginConfigEntry, searchPaths, applyProxy); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + if (this.globalPlugins) { |
| 103 | + // Enable global plugins with synthetic configuration entries |
| 104 | + for (const globalPluginName of this.globalPlugins) { |
| 105 | + // Skip already-locally-loaded plugins |
| 106 | + if (!pluginImports || pluginImports.some(p => p.name === globalPluginName)) { |
| 107 | + continue; |
| 108 | + } |
| 109 | + |
| 110 | + // Provide global: true so plugins can detect why they can't find their config |
| 111 | + this.enablePlugin({ name: globalPluginName, global: true } as ts.PluginImport, searchPaths, applyProxy); |
| 112 | + } |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Tries to load and enable a single plugin |
| 118 | + * @param pluginConfigEntry |
| 119 | + * @param searchPaths |
| 120 | + */ |
| 121 | + private enablePlugin(pluginConfigEntry: ts.PluginImport, searchPaths: string[], enableProxy: EnableProxyFunc) { |
| 122 | + for (const searchPath of searchPaths) { |
| 123 | + const resolvedModule = this.resolveModule(pluginConfigEntry.name, searchPath) as PluginModuleFactory; |
| 124 | + if (resolvedModule) { |
| 125 | + enableProxy(resolvedModule, pluginConfigEntry); |
| 126 | + return; |
| 127 | + } |
| 128 | + } |
| 129 | + this.logger.error(`Couldn't find ${pluginConfigEntry.name} anywhere in paths: ${searchPaths.join(',')}`); |
| 130 | + } |
| 131 | + |
| 132 | + /** |
| 133 | + * Load a plugin using a node require |
| 134 | + * @param moduleName |
| 135 | + * @param initialDir |
| 136 | + */ |
| 137 | + private resolveModule(moduleName: string, initialDir: string): {} | undefined { |
| 138 | + const resolvedPath = toUnixPath(path.resolve(combinePaths(initialDir, 'node_modules'))); |
| 139 | + this.logger.info(`Loading ${moduleName} from ${initialDir} (resolved to ${resolvedPath})`); |
| 140 | + const result = this.requirePlugin(resolvedPath, moduleName); |
| 141 | + if (result.error) { |
| 142 | + this.logger.error(`Failed to load module: ${JSON.stringify(result.error)}`); |
| 143 | + return undefined; |
| 144 | + } |
| 145 | + return result.module; |
| 146 | + } |
| 147 | + |
| 148 | + /** |
| 149 | + * Resolves a loads a plugin function relative to initialDir |
| 150 | + * @param initialDir |
| 151 | + * @param moduleName |
| 152 | + */ |
| 153 | + private requirePlugin(initialDir: string, moduleName: string): RequireResult { |
| 154 | + try { |
| 155 | + const modulePath = this.resolveJavaScriptModule(moduleName, initialDir, this.fs); |
| 156 | + return { module: this.requireModule(modulePath), error: undefined }; |
| 157 | + } catch (error) { |
| 158 | + return { module: undefined, error }; |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + /** |
| 163 | + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. |
| 164 | + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 |
| 165 | + * Throws an error if the module can't be resolved. |
| 166 | + * stolen from moduleNameResolver.ts because marked as internal |
| 167 | + */ |
| 168 | + private resolveJavaScriptModule(moduleName: string, initialDir: string, host: ts.ModuleResolutionHost): string { |
| 169 | + // TODO: this should set jsOnly=true to the internal resolver, but this parameter is not exposed on a public api. |
| 170 | + const result = |
| 171 | + ts.nodeModuleNameResolver( |
| 172 | + moduleName, |
| 173 | + initialDir.replace('\\', '/') + '/package.json', /* containingFile */ |
| 174 | + { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, |
| 175 | + this.resolutionHost, |
| 176 | + undefined |
| 177 | + ); |
| 178 | + if (!result.resolvedModule) { |
| 179 | + // this.logger.error(result.failedLookupLocations); |
| 180 | + throw new Error(`Could not resolve JS module ${moduleName} starting at ${initialDir}.`); |
| 181 | + } |
| 182 | + return result.resolvedModule.resolvedFileName; |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +/** |
| 187 | + * A local filesystem-based ModuleResolutionHost for plugin loading. |
| 188 | + */ |
| 189 | +export class LocalModuleResolutionHost implements ts.ModuleResolutionHost { |
| 190 | + fileExists(fileName: string): boolean { |
| 191 | + return fs.existsSync(fileName); |
| 192 | + } |
| 193 | + readFile(fileName: string): string { |
| 194 | + return fs.readFileSync(fileName, 'utf8'); |
| 195 | + } |
| 196 | +} |
0 commit comments