-
Notifications
You must be signed in to change notification settings - Fork 71
/
index.ts
241 lines (215 loc) · 7.69 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import fs from 'fs';
import path from 'path';
import dotenv from 'dotenv';
import postcss, { AcceptedPlugin } from 'postcss';
import postcssIcssSelectors from 'postcss-icss-selectors';
import postcssrc from 'postcss-load-config';
import filter from 'postcss-filter-plugins';
import tsModule from 'typescript/lib/tsserverlibrary';
import { Options } from './options';
import { createMatchers } from './helpers/createMatchers';
import { isCSSFn } from './helpers/cssExtensions';
import { getDtsSnapshot } from './helpers/getDtsSnapshot';
import { createLogger } from './helpers/logger';
const getPostCssConfigPlugins = (directory: string) => {
try {
return postcssrc.sync({}, directory).plugins;
} catch (error) {
return [];
}
};
function init({ typescript: ts }: { typescript: typeof tsModule }) {
let _isCSS: isCSSFn;
function create(info: ts.server.PluginCreateInfo) {
const logger = createLogger(info);
const directory = info.project.getCurrentDirectory();
// TypeScript plugins have a `cwd` of `/`, which causes issues with import resolution.
process.chdir(directory);
// User options for plugin.
const options: Options = info.config.options || {};
logger.log(`options: ${JSON.stringify(options)}`);
// Load environment variables like SASS_PATH.
// TODO: Add tests for this option.
const dotenvOptions = options.dotenvOptions || {};
if (dotenvOptions) {
dotenvOptions.path = path.resolve(
directory,
dotenvOptions.path || '.env',
);
}
dotenv.config(dotenvOptions);
// Normalise SASS_PATH array to absolute paths.
if (process.env.SASS_PATH) {
process.env.SASS_PATH = process.env.SASS_PATH.split(path.delimiter)
.map((sassPath) =>
path.isAbsolute(sassPath)
? sassPath
: path.resolve(directory, sassPath),
)
.join(path.delimiter);
}
// Add postCSS config if enabled.
const postCssOptions = options.postCssOptions || {};
let userPlugins: AcceptedPlugin[] = [];
if (postCssOptions.useConfig) {
const postcssConfig = getPostCssConfigPlugins(directory);
userPlugins = [
filter({
exclude: postCssOptions.excludePlugins,
silent: true,
}),
...postcssConfig,
];
}
// If a custom renderer is provided, resolve the path.
if (options.customRenderer) {
options.customRenderer = path.resolve(directory, options.customRenderer);
}
// If a custom template is provided, resolve the path.
if (options.customTemplate) {
options.customTemplate = path.resolve(directory, options.customTemplate);
}
// Create PostCSS processor.
const processor = postcss([
...userPlugins,
postcssIcssSelectors({ mode: 'local' }),
]);
// Create matchers using options object.
const { isCSS, isRelativeCSS } = createMatchers(logger, options);
_isCSS = isCSS;
// Creates new virtual source files for the CSS modules.
const _createLanguageServiceSourceFile = ts.createLanguageServiceSourceFile;
ts.createLanguageServiceSourceFile = (
fileName,
scriptSnapshot,
...rest
): ts.SourceFile => {
if (isCSS(fileName)) {
scriptSnapshot = getDtsSnapshot(
ts,
processor,
fileName,
scriptSnapshot,
options,
logger,
);
}
const sourceFile = _createLanguageServiceSourceFile(
fileName,
scriptSnapshot,
...rest,
);
if (isCSS(fileName)) {
sourceFile.isDeclarationFile = true;
}
return sourceFile;
};
// Updates virtual source files as files update.
const _updateLanguageServiceSourceFile = ts.updateLanguageServiceSourceFile;
ts.updateLanguageServiceSourceFile = (
sourceFile,
scriptSnapshot,
...rest
): ts.SourceFile => {
if (isCSS(sourceFile.fileName)) {
scriptSnapshot = getDtsSnapshot(
ts,
processor,
sourceFile.fileName,
scriptSnapshot,
options,
logger,
);
}
sourceFile = _updateLanguageServiceSourceFile(
sourceFile,
scriptSnapshot,
...rest,
);
if (isCSS(sourceFile.fileName)) {
sourceFile.isDeclarationFile = true;
}
return sourceFile;
};
if (info.languageServiceHost.resolveModuleNames) {
const _resolveModuleNames = info.languageServiceHost.resolveModuleNames.bind(
info.languageServiceHost,
);
info.languageServiceHost.resolveModuleNames = (
moduleNames,
containingFile,
...rest
) => {
const resolvedModules = _resolveModuleNames(
moduleNames,
containingFile,
...rest,
);
return moduleNames.map((moduleName, index) => {
try {
if (isRelativeCSS(moduleName)) {
return {
extension: tsModule.Extension.Dts,
isExternalLibraryImport: false,
resolvedFileName: path.resolve(
path.dirname(containingFile),
moduleName,
),
};
} else if (isCSS(moduleName)) {
// TODO: Move this section to a separate file and add basic tests.
// Attempts to locate the module using TypeScript's previous search paths. These include "baseUrl" and "paths".
const failedModule = info.project.getResolvedModuleWithFailedLookupLocationsFromCache(
moduleName,
containingFile,
);
const baseUrl = info.project.getCompilerOptions().baseUrl;
const match = '/index.ts';
// An array of paths TypeScript searched for the module. All include .ts, .tsx, .d.ts, or .json extensions.
// NOTE: TypeScript doesn't expose this in their interfaces, which is why the type is unkown.
// https://github.com/microsoft/TypeScript/issues/28770
const failedLocations: readonly string[] = ((failedModule as unknown) as {
failedLookupLocations: readonly string[];
}).failedLookupLocations;
// Filter to only one extension type, and remove that extension. This leaves us with the actual filename.
// Example: "usr/person/project/src/dir/File.module.css/index.d.ts" > "usr/person/project/src/dir/File.module.css"
const normalizedLocations = failedLocations.reduce(
(locations, location) => {
if (
(baseUrl ? location.includes(baseUrl) : true) &&
location.endsWith(match)
) {
return [...locations, location.replace(match, '')];
}
return locations;
},
[] as string[],
);
// Find the imported CSS module, if it exists.
const cssModulePath = normalizedLocations.find((location) =>
fs.existsSync(location),
);
if (cssModulePath) {
return {
extension: tsModule.Extension.Dts,
isExternalLibraryImport: false,
resolvedFileName: path.resolve(cssModulePath),
};
}
}
} catch (e) {
logger.error(e);
return resolvedModules[index];
}
return resolvedModules[index];
});
};
}
return info.languageService;
}
function getExternalFiles(project: tsModule.server.ConfiguredProject) {
return project.getFileNames().filter(_isCSS);
}
return { create, getExternalFiles };
}
export = init;