forked from vuejs/language-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathts.ts
324 lines (299 loc) · 9.1 KB
/
ts.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import { camelize } from '@vue/shared';
import { posix as path } from 'path-browserify';
import type * as ts from 'typescript';
import { generateGlobalTypes, resolveGlobalTypesName } from '../codegen/globalTypes';
import { getAllExtensions } from '../languagePlugin';
import type { RawVueCompilerOptions, VueCompilerOptions, VueLanguagePlugin } from '../types';
export type ParsedCommandLine = ts.ParsedCommandLine & {
vueOptions: VueCompilerOptions;
};
export function createParsedCommandLineByJson(
ts: typeof import('typescript'),
parseConfigHost: ts.ParseConfigHost & {
writeFile?(path: string, data: string): void;
},
rootDir: string,
json: any,
configFileName = rootDir + '/jsconfig.json',
skipGlobalTypesSetup = false
): ParsedCommandLine {
const proxyHost = proxyParseConfigHostForExtendConfigPaths(parseConfigHost);
ts.parseJsonConfigFileContent(json, proxyHost.host, rootDir, {}, configFileName);
let vueOptions: Partial<VueCompilerOptions> = {};
for (const extendPath of proxyHost.extendConfigPaths.reverse()) {
try {
vueOptions = {
...vueOptions,
...getPartialVueCompilerOptions(ts, ts.readJsonConfigFile(extendPath, proxyHost.host.readFile)),
};
} catch (err) { }
}
const resolvedVueOptions = resolveVueCompilerOptions(vueOptions);
if (skipGlobalTypesSetup) {
resolvedVueOptions.__setupedGlobalTypes = true;
}
else {
resolvedVueOptions.__setupedGlobalTypes = setupGlobalTypes(rootDir, resolvedVueOptions, parseConfigHost);
}
const parsed = ts.parseJsonConfigFileContent(
json,
proxyHost.host,
rootDir,
{},
configFileName,
undefined,
getAllExtensions(resolvedVueOptions)
.map(extension => ({
extension: extension.slice(1),
isMixedContent: true,
scriptKind: ts.ScriptKind.Deferred,
}))
);
// fix https://github.com/vuejs/language-tools/issues/1786
// https://github.com/microsoft/TypeScript/issues/30457
// patching ts server broke with outDir + rootDir + composite/incremental
parsed.options.outDir = undefined;
return {
...parsed,
vueOptions: resolvedVueOptions,
};
}
export function createParsedCommandLine(
ts: typeof import('typescript'),
parseConfigHost: ts.ParseConfigHost,
tsConfigPath: string,
skipGlobalTypesSetup = false
): ParsedCommandLine {
try {
const proxyHost = proxyParseConfigHostForExtendConfigPaths(parseConfigHost);
const config = ts.readJsonConfigFile(tsConfigPath, proxyHost.host.readFile);
ts.parseJsonSourceFileConfigFileContent(config, proxyHost.host, path.dirname(tsConfigPath), {}, tsConfigPath);
let vueOptions: Partial<VueCompilerOptions> = {};
for (const extendPath of proxyHost.extendConfigPaths.reverse()) {
try {
vueOptions = {
...vueOptions,
...getPartialVueCompilerOptions(ts, ts.readJsonConfigFile(extendPath, proxyHost.host.readFile)),
};
} catch (err) { }
}
const resolvedVueOptions = resolveVueCompilerOptions(vueOptions);
if (skipGlobalTypesSetup) {
resolvedVueOptions.__setupedGlobalTypes = true;
}
else {
resolvedVueOptions.__setupedGlobalTypes = setupGlobalTypes(path.dirname(tsConfigPath), resolvedVueOptions, parseConfigHost);
}
const parsed = ts.parseJsonSourceFileConfigFileContent(
config,
proxyHost.host,
path.dirname(tsConfigPath),
{},
tsConfigPath,
undefined,
getAllExtensions(resolvedVueOptions)
.map(extension => ({
extension: extension.slice(1),
isMixedContent: true,
scriptKind: ts.ScriptKind.Deferred,
}))
);
// fix https://github.com/vuejs/language-tools/issues/1786
// https://github.com/microsoft/TypeScript/issues/30457
// patching ts server broke with outDir + rootDir + composite/incremental
parsed.options.outDir = undefined;
return {
...parsed,
vueOptions: resolvedVueOptions,
};
}
catch (err) {
// console.warn('Failed to resolve tsconfig path:', tsConfigPath, err);
return {
fileNames: [],
options: {},
vueOptions: resolveVueCompilerOptions({}),
errors: [],
};
}
}
function proxyParseConfigHostForExtendConfigPaths(parseConfigHost: ts.ParseConfigHost) {
const extendConfigPaths: string[] = [];
const host = new Proxy(parseConfigHost, {
get(target, key) {
if (key === 'readFile') {
return (fileName: string) => {
if (!fileName.endsWith('/package.json') && !extendConfigPaths.includes(fileName)) {
extendConfigPaths.push(fileName);
}
return target.readFile(fileName);
};
}
return target[key as keyof typeof target];
}
});
return {
host,
extendConfigPaths,
};
}
function getPartialVueCompilerOptions(
ts: typeof import('typescript'),
tsConfigSourceFile: ts.TsConfigSourceFile
) {
const folder = path.dirname(tsConfigSourceFile.fileName);
const obj = ts.convertToObject(tsConfigSourceFile, []);
const rawOptions: RawVueCompilerOptions = obj?.vueCompilerOptions ?? {};
const result: Partial<VueCompilerOptions> = {
...rawOptions as any,
};
const target = rawOptions.target ?? 'auto';
if (target === 'auto') {
const resolvedPath = resolvePath('vue/package.json');
if (resolvedPath) {
const vuePackageJson = require(resolvedPath);
const versionNumbers = vuePackageJson.version.split('.');
result.target = Number(versionNumbers[0] + '.' + versionNumbers[1]);
}
else {
// console.warn('Load vue/package.json failed from', folder);
}
}
else {
result.target = target;
}
if (rawOptions.plugins) {
const plugins = rawOptions.plugins
.map<VueLanguagePlugin>((pluginPath: string) => {
try {
const resolvedPath = resolvePath(pluginPath);
if (resolvedPath) {
const plugin = require(resolvedPath);
plugin.__moduleName = pluginPath;
return plugin;
}
else {
console.warn('[Vue] Load plugin failed:', pluginPath);
}
}
catch (error) {
console.warn('[Vue] Resolve plugin path failed:', pluginPath, error);
}
return [];
});
result.plugins = plugins;
}
return result;
function resolvePath(scriptPath: string) {
try {
if (require?.resolve) {
return require.resolve(scriptPath, { paths: [folder] });
}
else {
// console.warn('failed to resolve path:', scriptPath, 'require.resolve is not supported in web');
}
}
catch (error) {
// console.warn(error);
}
}
}
export function getDefaultOptions(vueOptions: Partial<VueCompilerOptions>): VueCompilerOptions {
const target = vueOptions.target ?? 3.3;
const lib = vueOptions.lib ?? 'vue';
const strictTemplates = typeof vueOptions.strictTemplates === 'boolean' ? {
attributes: vueOptions.strictTemplates,
components: vueOptions.strictTemplates
} : vueOptions.strictTemplates ?? {
attributes: false,
components: false
};
return {
target,
lib,
extensions: ['.vue'],
vitePressExtensions: [],
petiteVueExtensions: [],
jsxSlots: false,
strictTemplates,
skipTemplateCodegen: false,
fallthroughAttributes: false,
dataAttributes: [],
htmlAttributes: ['aria-*'],
optionsWrapper: target >= 2.7
? [`(await import('${lib}')).defineComponent(`, `)`]
: [`(await import('${lib}')).default.extend(`, `)`],
macros: {
defineProps: ['defineProps'],
defineSlots: ['defineSlots'],
defineEmits: ['defineEmits'],
defineExpose: ['defineExpose'],
defineModel: ['defineModel'],
defineOptions: ['defineOptions'],
withDefaults: ['withDefaults'],
},
composables: {
useAttrs: ['useAttrs'],
useCssModule: ['useCssModule'],
useSlots: ['useSlots'],
useTemplateRef: ['useTemplateRef', 'templateRef'],
},
plugins: [],
experimentalDefinePropProposal: false,
experimentalResolveStyleCssClasses: 'scoped',
experimentalModelPropName: null!
};
};
export function resolveVueCompilerOptions(
options: Partial<VueCompilerOptions>,
defaults: VueCompilerOptions = getDefaultOptions(options)
): VueCompilerOptions {
return {
...defaults,
...options,
macros: {
...defaults.macros,
...options.macros,
},
composables: {
...defaults.composables,
...options.composables,
},
// https://github.com/vuejs/vue-next/blob/master/packages/compiler-dom/src/transforms/vModel.ts#L49-L51
// https://vuejs.org/guide/essentials/forms.html#form-input-bindings
experimentalModelPropName: Object.fromEntries(Object.entries(
options.experimentalModelPropName ?? defaults.experimentalModelPropName ?? {
'': {
input: true
},
value: {
input: { type: 'text' },
textarea: true,
select: true
}
}
).map(([k, v]) => [camelize(k), v])),
};
}
export function setupGlobalTypes(rootDir: string, vueOptions: VueCompilerOptions, host: {
fileExists(path: string): boolean;
writeFile?(path: string, data: string): void;
}): VueCompilerOptions['__setupedGlobalTypes'] {
if (!host.writeFile) {
return;
}
try {
let dir = rootDir;
while (!host.fileExists(path.join(dir, 'node_modules', vueOptions.lib, 'package.json'))) {
const parentDir = path.dirname(dir);
if (dir === parentDir) {
throw 0;
}
dir = parentDir;
}
const globalTypesPath = path.join(dir, 'node_modules', '.vue-global-types', resolveGlobalTypesName(vueOptions));
const globalTypesContents = `// @ts-nocheck\nexport {};\n` + generateGlobalTypes(vueOptions);
host.writeFile(globalTypesPath, globalTypesContents);
return { absolutePath: globalTypesPath };
} catch { }
}