-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathtypescript.ts
259 lines (218 loc) · 6.58 KB
/
typescript.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import { dirname, isAbsolute, join, resolve } from 'path';
import ts from 'typescript';
import { throwTypescriptError } from '../modules/errors';
import type { Transformer, Options } from '../types';
type CompilerOptions = ts.CompilerOptions;
/**
* Map of valid tsconfigs (no errors). Key is the path.
*/
const tsconfigMap = new Map<string, any>();
function createFormatDiagnosticsHost(cwd: string): ts.FormatDiagnosticsHost {
return {
getCanonicalFileName: (fileName: string) =>
fileName.replace('.injected.ts', ''),
getCurrentDirectory: () => cwd,
getNewLine: () => ts.sys.newLine,
};
}
function formatDiagnostics(
diagnostics: ts.Diagnostic | ts.Diagnostic[],
basePath: string,
) {
if (Array.isArray(diagnostics)) {
return ts.formatDiagnosticsWithColorAndContext(
diagnostics,
createFormatDiagnosticsHost(basePath),
);
}
return ts.formatDiagnostic(
diagnostics,
createFormatDiagnosticsHost(basePath),
);
}
let warned_verbatim = false;
function getCompilerOptions({
filename,
options,
basePath,
}: {
filename: string;
options: Options.Typescript;
basePath: string;
}): CompilerOptions {
const inputOptions = ts.convertCompilerOptionsFromJson(
options.compilerOptions ?? {},
basePath,
);
const { errors, options: convertedCompilerOptions } =
options.tsconfigFile !== false || options.tsconfigDirectory
? loadTsconfig(inputOptions, filename, options)
: inputOptions;
if (errors.length) {
throw new Error(formatDiagnostics(errors, basePath));
}
const compilerOptions: CompilerOptions = {
target: ts.ScriptTarget.ES2015,
...convertedCompilerOptions,
// force module(resolution) to esnext and a compatible moduleResolution. Reason:
// transpileModule treats NodeNext as CommonJS because it doesn't read the package.json.
// Also see https://github.com/microsoft/TypeScript/issues/53022 (the filename workaround doesn't work).
module: ts.ModuleKind.ESNext,
moduleResolution:
convertedCompilerOptions.moduleResolution ===
ts.ModuleResolutionKind.Bundler
? ts.ModuleResolutionKind.Bundler
: ts.ModuleResolutionKind.Node10,
customConditions: undefined, // fails when using an invalid moduleResolution combination which could happen when we force moduleResolution to Node10
allowNonTsExtensions: true,
// Clear outDir since it causes source map issues when the files aren't actually written to disk.
outDir: undefined,
};
if (!warned_verbatim && !compilerOptions.verbatimModuleSyntax) {
warned_verbatim = true;
console.warn(
'\x1b[1m%s\x1b[0m',
'The TypeScript option verbatimModuleSyntax is now required when using Svelte files with lang="ts". Please add it to your tsconfig.json.',
);
// best effort to still add it, if possible, in case no config was found whatsoever
if (
Object.keys(inputOptions.options).length === 0 &&
convertedCompilerOptions === inputOptions.options
) {
compilerOptions.verbatimModuleSyntax = true;
}
}
if (
compilerOptions.target === ts.ScriptTarget.ES3 ||
compilerOptions.target === ts.ScriptTarget.ES5
) {
throw new Error(
`Svelte only supports es6+ syntax. Set your 'compilerOptions.target' to 'es6' or higher.`,
);
}
return compilerOptions;
}
function transpileTs({
code,
fileName,
basePath,
options,
compilerOptions,
transformers,
}: {
code: string;
fileName: string;
basePath: string;
options: Options.Typescript;
compilerOptions: CompilerOptions;
transformers?: ts.CustomTransformers;
}): {
transpiledCode: string;
diagnostics: ts.Diagnostic[] | undefined;
sourceMapText: string | undefined;
} {
const {
outputText: transpiledCode,
sourceMapText,
diagnostics,
} = ts.transpileModule(code, {
fileName,
compilerOptions,
reportDiagnostics: options.reportDiagnostics !== false,
transformers,
});
if (diagnostics && diagnostics.length > 0) {
// could this be handled elsewhere?
const hasError = diagnostics.some(
(d) => d.category === ts.DiagnosticCategory.Error,
);
if (hasError) {
const formattedDiagnostics = formatDiagnostics(diagnostics, basePath);
console.log(formattedDiagnostics);
throwTypescriptError();
}
}
return { transpiledCode, sourceMapText, diagnostics };
}
export function loadTsconfig(
fallback: {
options: ts.CompilerOptions;
errors: ts.Diagnostic[];
},
filename: string,
tsOptions: Options.Typescript,
): {
options: ts.CompilerOptions;
errors: ts.Diagnostic[];
} {
if (typeof tsOptions.tsconfigFile === 'boolean') {
return fallback;
}
let basePath = process.cwd();
const fileDirectory = (tsOptions.tsconfigDirectory ||
dirname(filename)) as string;
let tsconfigFile =
tsOptions.tsconfigFile ||
ts.findConfigFile(fileDirectory, ts.sys.fileExists);
if (!tsconfigFile) {
return fallback;
}
tsconfigFile = isAbsolute(tsconfigFile)
? tsconfigFile
: join(basePath, tsconfigFile);
basePath = dirname(tsconfigFile);
if (tsconfigMap.has(tsconfigFile)) {
return {
errors: [],
options: tsconfigMap.get(tsconfigFile),
};
}
const { error, config } = ts.readConfigFile(tsconfigFile, ts.sys.readFile);
if (error) {
throw new Error(formatDiagnostics(error, basePath));
}
// Do this so TS will not search for initial files which might take a while
config.include = [];
let { errors, options } = ts.parseJsonConfigFileContent(
config,
ts.sys,
basePath,
fallback.options,
tsconfigFile,
);
// Filter out "no files found error"
errors = errors.filter((d) => d.code !== 18003);
if (errors.length === 0) {
tsconfigMap.set(tsconfigFile, options);
}
return { errors, options };
}
let warned_mixed = false;
const transformer: Transformer<Options.Typescript> = async ({
content,
filename = 'input.svelte',
options = {},
}) => {
const basePath = process.cwd();
filename = isAbsolute(filename) ? filename : resolve(basePath, filename);
const compilerOptions = getCompilerOptions({ filename, options, basePath });
if ('handleMixedImports' in options && !warned_mixed) {
warned_mixed = true;
console.warn(
'The svelte-preprocess TypeScript option handleMixedImports was removed. Use the verbatimModuleSyntax TypeScript option instead.',
);
}
const { transpiledCode, sourceMapText, diagnostics } = transpileTs({
code: content,
fileName: filename,
basePath,
options,
compilerOptions,
});
return {
code: transpiledCode,
map: sourceMapText,
diagnostics,
};
};
export { transformer };