Skip to content

Commit

Permalink
Fix nested json parsing errors (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
dengelke authored Oct 4, 2024
1 parent 9201ba4 commit 721c42d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/safe-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class SafeParser extends Parser {
for (nextStart = colon - 1; nextStart >= 0; nextStart--) {
if (tokens[nextStart][0] === 'word') break
}
if (nextStart === 0) return
if (nextStart === 0 || nextStart < 0) return

for (prevEnd = nextStart - 1; prevEnd >= 0; prevEnd--) {
if (tokens[prevEnd][0] !== 'space') {
Expand Down
33 changes: 33 additions & 0 deletions test/parse.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,38 @@ test('fixes colon instead of semicolon', () => {
equal(root.toString(), 'a { one: 1: } b { one: 1 : }')
})

test('fixes {} error', () => {
let root = parse(`:root { --example-var: { "Version": { "Build": "10.30.7.350828.20230224122352", "Source": "10.30.7.350828.1", "Required": "10.30.7.307232"; }}}; @font-face { font-family: 'Calibri'; }`)
equal(root.toString(), `:root { --example-var: { "Version": { "Build": "10.30.7.350828.20230224122352", "Source": "10.30.7.350828.1", "Required": "10.30.7.307232"; }}}; @font-face { font-family: 'Calibri'; }`)
})

test('Rule at the start of tokens', () => {
let root = parse(`.start { font-size: 16px; }`);
equal(root.toString(), `.start { font-size: 16px; }`);
});

test('Complex nested structures with JSON-like properties', () => {
let root = parse(`:root { --complex: {"nested": {"key": "value"}, "array": [1, {"sub": "value"}]}; } @font-face { font-family: 'Calibri'; }`);
equal(root.toString(), `:root { --complex: {"nested": {"key": "value"}, "array": [1, {"sub": "value"}]}; } @font-face { font-family: 'Calibri'; }`);
});

test('Multiple rules with one JSON-like custom property', () => {
let root = parse(`
.class1 { margin: 10px; }
:root { --jsonProp: {"a": 1, "b": {"c": 3}}; }
.class2 { padding: 20px; }
`);
equal(root.toString(), `
.class1 { margin: 10px; }
:root { --jsonProp: {"a": 1, "b": {"c": 3}}; }
.class2 { padding: 20px; }
`);
});

test('Custom property at start without modifications', () => {
let root = parse(`--example: {"key": "value"}; .class { color: black; }`);
equal(root.toString(), `--example: {"key": "value"}; .class { color: black; }`);
});

test.run()

0 comments on commit 721c42d

Please sign in to comment.