-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathrun-prettier.js
More file actions
51 lines (43 loc) · 1.28 KB
/
run-prettier.js
File metadata and controls
51 lines (43 loc) · 1.28 KB
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
import getPrettier from "./get-prettier.js";
import getPlugins from "./get-plugins.js";
import { CURSOR_PLACEHOLDER } from "./constants.js";
import visualizeEndOfLine from "./visualize-end-of-line.js";
async function parse(input, options) {
const prettier = await getPrettier();
const { ast } = await prettier.__debug.parse(
input,
await loadPlugins(options),
{ massage: true },
);
return ast;
}
async function format(input, options) {
const inputWithCursor = insertCursor(input, options.cursorOffset);
const prettier = await getPrettier();
const { formatted: output, cursorOffset } = await prettier.formatWithCursor(
input,
await loadPlugins(options),
);
const outputWithCursor = insertCursor(output, cursorOffset);
const eolVisualizedOutput = visualizeEndOfLine(outputWithCursor);
const changed = outputWithCursor !== inputWithCursor;
return {
changed,
options,
input,
inputWithCursor,
output,
outputWithCursor,
eolVisualizedOutput,
};
}
const insertCursor = (text, cursorOffset) =>
cursorOffset >= 0
? text.slice(0, cursorOffset) +
CURSOR_PLACEHOLDER +
text.slice(cursorOffset)
: text;
async function loadPlugins(options) {
return { ...options, plugins: await getPlugins() };
}
export { format, parse };