/
SvelteDocument.ts
310 lines (272 loc) · 9.93 KB
/
SvelteDocument.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
import { SourceMapConsumer } from 'source-map';
import { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
import type { compile } from 'svelte/compiler';
import { CompileOptions } from 'svelte/types/compiler/interfaces';
import { Processed } from 'svelte/types/compiler/preprocess';
import { Position } from 'vscode-languageserver';
import {
Document,
DocumentMapper,
extractScriptTags,
extractStyleTag,
FragmentMapper,
IdentityMapper,
offsetAt,
SourceMapDocumentMapper,
TagInformation,
} from '../../lib/documents';
import { importSvelte } from '../../importPackage';
export type SvelteCompileResult = ReturnType<typeof compile>;
export enum TranspileErrorSource {
Script = 'Script',
Style = 'Style',
}
/**
* Represents a text document that contains a svelte component.
*/
export class SvelteDocument {
private transpiledDoc: TranspiledSvelteDocument | undefined;
private compileResult: SvelteCompileResult | undefined;
public script: TagInformation | null;
public moduleScript: TagInformation | null;
public style: TagInformation | null;
public languageId = 'svelte';
public version = 0;
public uri = this.parent.uri;
public config = this.parent.config;
constructor(private parent: Document) {
this.script = this.parent.scriptInfo;
this.moduleScript = this.parent.moduleScriptInfo;
this.style = this.parent.styleInfo;
this.version = this.parent.version;
}
getText() {
return this.parent.getText();
}
getFilePath(): string {
return this.parent.getFilePath() || '';
}
offsetAt(position: Position): number {
return this.parent.offsetAt(position);
}
async getTranspiled(): Promise<TranspiledSvelteDocument> {
if (!this.transpiledDoc) {
this.transpiledDoc = await TranspiledSvelteDocument.create(
this.parent,
this.parent.config.preprocess,
);
}
return this.transpiledDoc;
}
async getCompiled(): Promise<SvelteCompileResult> {
if (!this.compileResult) {
this.compileResult = await this.getCompiledWith(this.parent.config.compilerOptions);
}
return this.compileResult;
}
async getCompiledWith(options: CompileOptions = {}): Promise<SvelteCompileResult> {
const svelte = importSvelte(this.getFilePath());
return svelte.compile((await this.getTranspiled()).getText(), options);
}
/**
* Needs to be called before cleanup to prevent source map memory leaks.
*/
destroyTranspiled() {
if (this.transpiledDoc) {
this.transpiledDoc.destroy();
this.transpiledDoc = undefined;
}
}
}
export class TranspiledSvelteDocument implements Pick<DocumentMapper, 'getOriginalPosition'> {
static async create(document: Document, preprocessors: PreprocessorGroup = {}) {
const { transpiled, processedScript, processedStyle } = await transpile(
document,
preprocessors,
);
const scriptMapper = await SvelteFragmentMapper.createScript(
document,
transpiled,
processedScript,
);
const styleMapper = await SvelteFragmentMapper.createStyle(
document,
transpiled,
processedStyle,
);
return new TranspiledSvelteDocument(document, transpiled, scriptMapper, styleMapper);
}
private fragmentInfos = [this.scriptMapper.fragmentInfo, this.styleMapper.fragmentInfo].sort(
(i1, i2) => i1.end - i2.end,
);
private constructor(
private parent: Document,
private transpiled: string,
public scriptMapper: SvelteFragmentMapper,
public styleMapper: SvelteFragmentMapper,
) {}
getOriginalPosition(generatedPosition: Position): Position {
if (this.scriptMapper.isInTranspiledFragment(generatedPosition)) {
return this.scriptMapper.getOriginalPosition(generatedPosition);
}
if (this.styleMapper.isInTranspiledFragment(generatedPosition)) {
return this.styleMapper.getOriginalPosition(generatedPosition);
}
// Position is not in fragments, but we still need to account for
// the length differences of the fragments before the position.
let offset = offsetAt(generatedPosition, this.transpiled);
for (const fragmentInfo of this.fragmentInfos) {
if (offset > fragmentInfo.end) {
offset += fragmentInfo.diff;
}
}
return this.parent.positionAt(offset);
}
getURL(): string {
return this.parent.getURL();
}
getText() {
return this.transpiled;
}
/**
* Needs to be called before cleanup to prevent source map memory leaks.
*/
destroy() {
this.scriptMapper.destroy();
this.styleMapper.destroy();
}
}
export class SvelteFragmentMapper {
static async createStyle(originalDoc: Document, transpiled: string, processed?: Processed) {
return SvelteFragmentMapper.create(
originalDoc,
transpiled,
originalDoc.styleInfo,
extractStyleTag(transpiled),
processed,
);
}
static async createScript(originalDoc: Document, transpiled: string, processed?: Processed) {
return SvelteFragmentMapper.create(
originalDoc,
transpiled,
originalDoc.scriptInfo,
extractScriptTags(transpiled)?.script || null,
processed,
);
}
private static async create(
originalDoc: Document,
transpiled: string,
originalTagInfo: TagInformation | null,
transpiledTagInfo: TagInformation | null,
processed?: Processed,
) {
const sourceMapper = processed?.map
? new SourceMapDocumentMapper(
await new SourceMapConsumer(processed.map.toString()),
originalDoc.uri,
)
: new IdentityMapper(originalDoc.uri);
if (originalTagInfo && transpiledTagInfo) {
const sourceLength = originalTagInfo.container.end - originalTagInfo.container.start;
const transpiledLength =
transpiledTagInfo.container.end - transpiledTagInfo.container.start;
const diff = sourceLength - transpiledLength;
return new SvelteFragmentMapper(
{ end: transpiledTagInfo.container.end, diff },
new FragmentMapper(originalDoc.getText(), originalTagInfo, originalDoc.uri),
new FragmentMapper(transpiled, transpiledTagInfo, originalDoc.uri),
sourceMapper,
);
}
return new SvelteFragmentMapper(
{ end: -1, diff: 0 },
new IdentityMapper(originalDoc.uri),
new IdentityMapper(originalDoc.uri),
sourceMapper,
);
}
private constructor(
/**
* End offset + length difference to original
*/
public fragmentInfo: { end: number; diff: number },
/**
* Maps between full original source and fragment within that original.
*/
private originalFragmentMapper: DocumentMapper,
/**
* Maps between full transpiled source and fragment within that transpiled.
*/
private transpiledFragmentMapper: DocumentMapper,
/**
* Maps between original and transpiled, within fragment.
*/
private sourceMapper: DocumentMapper,
) {}
isInTranspiledFragment(generatedPosition: Position): boolean {
return this.transpiledFragmentMapper.isInGenerated(generatedPosition);
}
getOriginalPosition(generatedPosition: Position): Position {
// Map the position to be relative to the transpiled fragment
const positionInTranspiledFragment = this.transpiledFragmentMapper.getGeneratedPosition(
generatedPosition,
);
// Map the position, using the sourcemap, to the original position in the source fragment
const positionInOriginalFragment = this.sourceMapper.getOriginalPosition(
positionInTranspiledFragment,
);
// Map the position to be in the original fragment's parent
return this.originalFragmentMapper.getOriginalPosition(positionInOriginalFragment);
}
/**
* Needs to be called before cleanup to prevent source map memory leaks.
*/
destroy() {
if (this.sourceMapper.destroy) {
this.sourceMapper.destroy();
}
}
}
async function transpile(document: Document, preprocessors: PreprocessorGroup = {}) {
const preprocessor: PreprocessorGroup = {};
let processedScript: Processed | undefined;
let processedStyle: Processed | undefined;
preprocessor.markup = preprocessors.markup;
if (preprocessors.script) {
preprocessor.script = async (args: any) => {
try {
const res = await preprocessors.script!(args);
if (res && res.map) {
processedScript = res;
}
return res;
} catch (e) {
e.__source = TranspileErrorSource.Script;
throw e;
}
};
}
if (preprocessors.style) {
preprocessor.style = async (args: any) => {
try {
const res = await preprocessors.style!(args);
if (res && res.map) {
processedStyle = res;
}
return res;
} catch (e) {
e.__source = TranspileErrorSource.Style;
throw e;
}
};
}
const svelte = importSvelte(document.getFilePath() || '');
const transpiled = (
await svelte.preprocess(document.getText(), preprocessor, {
filename: document.getFilePath() || '',
})
).toString();
return { transpiled, processedScript, processedStyle };
}