Skip to content

Commit 0f6cf86

Browse files
authored
fix: handle CR in JSONSourceCode (#170)
1 parent 95c6238 commit 0f6cf86

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

src/languages/json-source-code.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ export class JSONSourceCode extends TextSourceCodeBase {
148148
* @param {DocumentNode} options.ast The root AST node.
149149
*/
150150
constructor({ text, ast }) {
151-
super({ text, ast });
151+
super({ text, ast, lineEndingPattern: /\r\n|[\r\n]/u });
152152
this.ast = ast;
153153

154154
const { comments, starts, ends } = processTokens(this.ast.tokens ?? []);

tests/languages/json-source-code.test.js

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ describe("JSONSourceCode", () => {
346346
});
347347

348348
describe("lines", () => {
349-
it("should return an array of lines", () => {
349+
it("should split lines on LF line endings", () => {
350350
const file = { body: "{\n//test\n}", path: "test.jsonc" };
351351
const language = new JSONLanguage({ mode: "jsonc" });
352352
const parseResult = language.parse(file);
@@ -357,6 +357,50 @@ describe("JSONSourceCode", () => {
357357

358358
assert.deepStrictEqual(sourceCode.lines, ["{", "//test", "}"]);
359359
});
360+
361+
it("should split lines on CR line endings", () => {
362+
const file = { body: "{\r//test\r}", path: "test.jsonc" };
363+
const language = new JSONLanguage({ mode: "jsonc" });
364+
const parseResult = language.parse(file);
365+
const sourceCode = new JSONSourceCode({
366+
text: file.body,
367+
ast: parseResult.ast,
368+
});
369+
370+
assert.deepStrictEqual(sourceCode.lines, ["{", "//test", "}"]);
371+
});
372+
373+
it("should split lines on CRLF line endings", () => {
374+
const file = { body: "{\r\n//test\r\n}", path: "test.jsonc" };
375+
const language = new JSONLanguage({ mode: "jsonc" });
376+
const parseResult = language.parse(file);
377+
const sourceCode = new JSONSourceCode({
378+
text: file.body,
379+
ast: parseResult.ast,
380+
});
381+
382+
assert.deepStrictEqual(sourceCode.lines, ["{", "//test", "}"]);
383+
});
384+
385+
it("should split lines with mixed line endings (LF, CRLF, CR)", () => {
386+
const file = {
387+
body: "{\n//one\r\n//two\r}",
388+
path: "test.jsonc",
389+
};
390+
const language = new JSONLanguage({ mode: "jsonc" });
391+
const parseResult = language.parse(file);
392+
const sourceCode = new JSONSourceCode({
393+
text: file.body,
394+
ast: parseResult.ast,
395+
});
396+
397+
assert.deepStrictEqual(sourceCode.lines, [
398+
"{",
399+
"//one",
400+
"//two",
401+
"}",
402+
]);
403+
});
360404
});
361405

362406
describe("getParent()", () => {

0 commit comments

Comments
 (0)