1const { Buffer } = require("buffer");
2const fs = require("fs");
3const path = require("path");
4const { once } = require("events");
5
6const prettierContainerPath = process.argv[2];
7if (prettierContainerPath == null || prettierContainerPath.length == 0) {
8 process.stderr.write(
9 `Prettier path argument was not specified or empty.\nUsage: ${process.argv[0]} ${process.argv[1]} prettier/path\n`,
10 );
11 process.exit(1);
12}
13fs.stat(prettierContainerPath, (err, stats) => {
14 if (err) {
15 process.stderr.write(`Path '${prettierContainerPath}' does not exist\n`);
16 process.exit(1);
17 }
18
19 if (!stats.isDirectory()) {
20 process.stderr.write(`Path '${prettierContainerPath}' exists but is not a directory\n`);
21 process.exit(1);
22 }
23});
24const prettierPath = path.join(prettierContainerPath, "node_modules/prettier");
25
26class Prettier {
27 constructor(path, prettier, config) {
28 this.path = path;
29 this.prettier = prettier;
30 this.config = config;
31 }
32}
33
34(async () => {
35 let prettier;
36 let config;
37 try {
38 prettier = await loadPrettier(prettierPath);
39 config = (await prettier.resolveConfig(prettierPath)) || {};
40 } catch (e) {
41 process.stderr.write(`Failed to load prettier: ${e}\n`);
42 process.exit(1);
43 }
44 process.stderr.write(`Prettier at path '${prettierPath}' loaded successfully, config: ${JSON.stringify(config)}\n`);
45 process.stdin.resume();
46 handleBuffer(new Prettier(prettierPath, prettier, config));
47})();
48
49async function handleBuffer(prettier) {
50 for await (const messageText of readStdin()) {
51 let message;
52 try {
53 message = JSON.parse(messageText);
54 } catch (e) {
55 sendResponse(makeError(`Failed to parse message '${messageText}': ${e}`));
56 continue;
57 }
58 // allow concurrent request handling by not `await`ing the message handling promise (async function)
59 handleMessage(message, prettier).catch((e) => {
60 const errorMessage = message;
61 if ((errorMessage.params || {}).text !== undefined) {
62 errorMessage.params.text = "..snip..";
63 }
64 sendResponse({
65 id: message.id,
66 ...makeError(`error during message '${JSON.stringify(errorMessage)}' handling: ${e}`),
67 });
68 });
69 }
70}
71
72const headerSeparator = "\r\n";
73const contentLengthHeaderName = "Content-Length";
74
75async function* readStdin() {
76 let buffer = Buffer.alloc(0);
77 let streamEnded = false;
78 process.stdin.on("end", () => {
79 streamEnded = true;
80 });
81 process.stdin.on("data", (data) => {
82 buffer = Buffer.concat([buffer, data]);
83 });
84
85 async function handleStreamEnded(errorMessage) {
86 sendResponse(makeError(errorMessage));
87 buffer = Buffer.alloc(0);
88 messageLength = null;
89 await once(process.stdin, "readable");
90 streamEnded = false;
91 }
92
93 try {
94 let headersLength = null;
95 let messageLength = null;
96 main_loop: while (true) {
97 if (messageLength === null) {
98 while (buffer.indexOf(`${headerSeparator}${headerSeparator}`) === -1) {
99 if (streamEnded) {
100 await handleStreamEnded("Unexpected end of stream: headers not found");
101 continue main_loop;
102 } else if (buffer.length > contentLengthHeaderName.length * 10) {
103 await handleStreamEnded(
104 `Unexpected stream of bytes: no headers end found after ${buffer.length} bytes of input`,
105 );
106 continue main_loop;
107 }
108 await once(process.stdin, "readable");
109 }
110 const headers = buffer.subarray(0, buffer.indexOf(`${headerSeparator}${headerSeparator}`)).toString("ascii");
111 const contentLengthHeader = headers
112 .split(headerSeparator)
113 .map((header) => header.split(":"))
114 .filter((header) => header[2] === undefined)
115 .filter((header) => (header[1] || "").length > 0)
116 .find((header) => (header[0] || "").trim() === contentLengthHeaderName);
117 const contentLength = (contentLengthHeader || [])[1];
118 if (contentLength === undefined) {
119 await handleStreamEnded(`Missing or incorrect ${contentLengthHeaderName} header: ${headers}`);
120 continue main_loop;
121 }
122 headersLength = headers.length + headerSeparator.length * 2;
123 messageLength = parseInt(contentLength, 10);
124 }
125
126 while (buffer.length < headersLength + messageLength) {
127 if (streamEnded) {
128 await handleStreamEnded(
129 `Unexpected end of stream: buffer length ${buffer.length} does not match expected header length ${headersLength} + body length ${messageLength}`,
130 );
131 continue main_loop;
132 }
133 await once(process.stdin, "readable");
134 }
135
136 const messageEnd = headersLength + messageLength;
137 const message = buffer.subarray(headersLength, messageEnd);
138 buffer = buffer.subarray(messageEnd);
139 headersLength = null;
140 messageLength = null;
141 yield message.toString("utf8");
142 }
143 } catch (e) {
144 sendResponse(makeError(`Error reading stdin: ${e}`));
145 } finally {
146 process.stdin.off("data", () => {});
147 }
148}
149
150async function handleMessage(message, prettier) {
151 const { method, id, params } = message;
152 if (method === undefined) {
153 throw new Error(`Message method is undefined: ${JSON.stringify(message)}`);
154 } else if (method == "initialized") {
155 return;
156 }
157
158 if (id === undefined) {
159 throw new Error(`Message id is undefined: ${JSON.stringify(message)}`);
160 }
161
162 if (method === "prettier/format") {
163 if (params === undefined || params.text === undefined) {
164 throw new Error(`Message params.text is undefined: ${JSON.stringify(message)}`);
165 }
166 if (params.options === undefined) {
167 throw new Error(`Message params.options is undefined: ${JSON.stringify(message)}`);
168 }
169
170 let resolvedConfig = {};
171 if (params.options.filepath) {
172 resolvedConfig = (await prettier.prettier.resolveConfig(params.options.filepath)) || {};
173
174 if (params.options.ignorePath) {
175 const fileInfo = await prettier.prettier.getFileInfo(params.options.filepath, {
176 ignorePath: params.options.ignorePath,
177 });
178 if (fileInfo.ignored) {
179 process.stderr.write(
180 `Ignoring file '${params.options.filepath}' based on rules in '${params.options.ignorePath}'\n`,
181 );
182 sendResponse({ id, result: { text: params.text } });
183 return;
184 }
185 }
186 }
187
188 // Marking the params.options.filepath as undefined makes
189 // prettier.format() work even if no filepath is set.
190 if (params.options.filepath === null) {
191 params.options.filepath = undefined;
192 }
193
194 const plugins =
195 Array.isArray(resolvedConfig?.plugins) && resolvedConfig.plugins.length > 0
196 ? resolvedConfig.plugins
197 : params.options.plugins;
198
199 const options = {
200 ...(params.options.prettierOptions || prettier.config),
201 ...resolvedConfig,
202 plugins,
203 parser: params.options.parser,
204 filepath: params.options.filepath,
205 };
206 process.stderr.write(
207 `Resolved config: ${JSON.stringify(resolvedConfig)}, will format file '${
208 params.options.filepath || ""
209 }' with options: ${JSON.stringify(options)}\n`,
210 );
211 const formattedText = await prettier.prettier.format(params.text, options);
212 sendResponse({ id, result: { text: formattedText } });
213 } else if (method === "prettier/clear_cache") {
214 prettier.prettier.clearConfigCache();
215 prettier.config = (await prettier.prettier.resolveConfig(prettier.path)) || {};
216 sendResponse({ id, result: null });
217 } else if (method === "initialize") {
218 sendResponse({
219 id,
220 result: {
221 capabilities: {},
222 },
223 });
224 } else {
225 throw new Error(`Unknown method: ${method}`);
226 }
227}
228
229function makeError(message) {
230 return {
231 error: {
232 code: -32600, // invalid request code
233 message,
234 },
235 };
236}
237
238function sendResponse(response) {
239 const responsePayloadString = JSON.stringify({
240 jsonrpc: "2.0",
241 ...response,
242 });
243 const headers = `${contentLengthHeaderName}: ${Buffer.byteLength(
244 responsePayloadString,
245 )}${headerSeparator}${headerSeparator}`;
246 process.stdout.write(headers + responsePayloadString);
247}
248
249function loadPrettier(prettierPath) {
250 return new Promise((resolve, reject) => {
251 fs.access(prettierPath, fs.constants.F_OK, (err) => {
252 if (err) {
253 reject(`Path '${prettierPath}' does not exist.Error: ${err}`);
254 } else {
255 try {
256 resolve(require(prettierPath));
257 } catch (err) {
258 reject(`Error requiring prettier module from path '${prettierPath}'.Error: ${err}`);
259 }
260 }
261 });
262 });
263}