Skip to content

Commit bd7ebb2

Browse files
authored
fix: quote flow scalars where a colon precedes a flow indicator (#773)
1 parent ac16b42 commit bd7ebb2

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

src/ast/presenter.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,14 @@ function isPlainSafe (c: number, prev: number, inblock: boolean) {
257257
!(prev === CHAR_COLON && !cIsNsChar)
258258
) || // false on ': '
259259
(isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) || // change to true on '[^ ]#'
260-
(prev === CHAR_COLON && cIsNsChar) // change to true on ':[^ ]'
260+
(prev === CHAR_COLON && cIsNsChar &&
261+
// outside block context a following c-flow-indicator is not ns-plain-safe
262+
(inblock ||
263+
(c !== CHAR_COMMA &&
264+
c !== CHAR_LEFT_SQUARE_BRACKET &&
265+
c !== CHAR_RIGHT_SQUARE_BRACKET &&
266+
c !== CHAR_LEFT_CURLY_BRACKET &&
267+
c !== CHAR_RIGHT_CURLY_BRACKET))) // change to true on ':[^ ]'
261268
}
262269

263270
// Simplified test for values allowed as the first character in plain style.

test/core/units/dump-options.test.mjs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, it } from 'node:test'
22
import assert from 'node:assert/strict'
3-
import { dump, JSON_SCHEMA, CORE_SCHEMA, defineMappingTag, realMapTag, YAMLException } from 'js-yaml'
3+
import { dump, load, JSON_SCHEMA, CORE_SCHEMA, defineMappingTag, realMapTag, YAMLException } from 'js-yaml'
44

55
describe('dump options', () => {
66
it('schema — decides which plain scalars need quoting', () => {
@@ -96,6 +96,16 @@ describe('dump options', () => {
9696
assert.equal(dump({ a: [1, 2] }, { flowLevel: 1 }), 'a: [1, 2]\n')
9797
})
9898

99+
it('flowLevel — quotes a colon followed by a flow indicator', () => {
100+
// In flow context a `:` followed by a flow indicator ({ } [ ] ,) is not
101+
// plain-safe (ns-plain-safe-in excludes c-flow-indicator), so the value
102+
// must be quoted for the output to re-parse.
103+
for (const value of [':{', ':[', ':,', ':}', ':]', 'x:{']) {
104+
assert.deepStrictEqual(load(dump([value], { flowLevel: 0 })), [value])
105+
assert.deepStrictEqual(load(dump({ k: value }, { flowLevel: 0 })), { k: value })
106+
}
107+
})
108+
99109
it('transform — mutates the generated documents before presentation', () => {
100110
const output = dump({ values: [1, 2] }, {
101111
flowLevel: 1,

0 commit comments

Comments
 (0)