-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathindex.ts
102 lines (90 loc) · 3.22 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
import { SupportLanguage, Parser, Printer } from 'prettier';
import * as prettierPluginBabel from 'prettier/plugins/babel';
import { hasPragma, print } from './print';
import { ASTNode } from './print/nodes';
import { embed, getVisitorKeys } from './embed';
import { snipScriptAndStyleTagContent } from './lib/snipTagContent';
import { parse, VERSION } from 'svelte/compiler';
import { ParserOptions } from './options';
const babelParser = prettierPluginBabel.parsers.babel;
const typescriptParser = prettierPluginBabel.parsers['babel-ts']; // TODO use TypeScript parser in next major?
function locStart(node: any) {
return node.start;
}
function locEnd(node: any) {
return node.end;
}
export const languages: Partial<SupportLanguage>[] = [
{
name: 'svelte',
parsers: ['svelte'],
extensions: ['.svelte'],
vscodeLanguageIds: ['svelte'],
},
];
export const parsers: Record<string, Parser> = {
svelte: {
hasPragma,
parse: (text) => {
try {
return <ASTNode>{ ...parse(text), __isRoot: true };
} catch (err: any) {
if (err.start != null && err.end != null) {
// Prettier expects error objects to have loc.start and loc.end fields.
// Svelte uses start and end directly on the error.
err.loc = {
start: err.start,
end: err.end,
};
}
throw err;
}
},
preprocess: (text, options: ParserOptions) => {
const result = snipScriptAndStyleTagContent(text);
text = result.text.trim();
// Prettier sets the preprocessed text as the originalText in case
// the Svelte formatter is called directly. In case it's called
// as an embedded parser (for example when there's a Svelte code block
// inside markdown), the originalText is not updated after preprocessing.
// Therefore we do it ourselves here.
options.originalText = text;
options._svelte_ts = result.isTypescript;
return text;
},
locStart,
locEnd,
astFormat: 'svelte-ast',
},
svelteExpressionParser: {
...babelParser,
parse: (text: string, options: any) => {
const ast = babelParser.parse(text, options);
let program = ast.program.body[0];
if (!options._svelte_asFunction) {
program = program.expression;
}
return { ...ast, program };
},
},
svelteTSExpressionParser: {
...typescriptParser,
parse: (text: string, options: any) => {
const ast = typescriptParser.parse(text, options);
let program = ast.program.body[0];
if (!options._svelte_asFunction) {
program = program.expression;
}
return { ...ast, program };
},
},
};
export const printers: Record<string, Printer> = {
'svelte-ast': {
print,
embed,
// @ts-expect-error Prettier's type definitions are wrong
getVisitorKeys,
},
};
export { options } from './options';