3 /*eslint-disable no-use-before-define*/
5 var common = require('./common');
6 var YAMLException = require('./exception');
7 var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
8 var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
10 var _toString = Object.prototype.toString;
11 var _hasOwnProperty = Object.prototype.hasOwnProperty;
13 var CHAR_TAB = 0x09; /* Tab */
14 var CHAR_LINE_FEED = 0x0A; /* LF */
15 var CHAR_SPACE = 0x20; /* Space */
16 var CHAR_EXCLAMATION = 0x21; /* ! */
17 var CHAR_DOUBLE_QUOTE = 0x22; /* " */
18 var CHAR_SHARP = 0x23; /* # */
19 var CHAR_PERCENT = 0x25; /* % */
20 var CHAR_AMPERSAND = 0x26; /* & */
21 var CHAR_SINGLE_QUOTE = 0x27; /* ' */
22 var CHAR_ASTERISK = 0x2A; /* * */
23 var CHAR_COMMA = 0x2C; /* , */
24 var CHAR_MINUS = 0x2D; /* - */
25 var CHAR_COLON = 0x3A; /* : */
26 var CHAR_GREATER_THAN = 0x3E; /* > */
27 var CHAR_QUESTION = 0x3F; /* ? */
28 var CHAR_COMMERCIAL_AT = 0x40; /* @ */
29 var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
30 var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
31 var CHAR_GRAVE_ACCENT = 0x60; /* ` */
32 var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
33 var CHAR_VERTICAL_LINE = 0x7C; /* | */
34 var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
36 var ESCAPE_SEQUENCES = {};
38 ESCAPE_SEQUENCES[0x00] = '\\0';
39 ESCAPE_SEQUENCES[0x07] = '\\a';
40 ESCAPE_SEQUENCES[0x08] = '\\b';
41 ESCAPE_SEQUENCES[0x09] = '\\t';
42 ESCAPE_SEQUENCES[0x0A] = '\\n';
43 ESCAPE_SEQUENCES[0x0B] = '\\v';
44 ESCAPE_SEQUENCES[0x0C] = '\\f';
45 ESCAPE_SEQUENCES[0x0D] = '\\r';
46 ESCAPE_SEQUENCES[0x1B] = '\\e';
47 ESCAPE_SEQUENCES[0x22] = '\\"';
48 ESCAPE_SEQUENCES[0x5C] = '\\\\';
49 ESCAPE_SEQUENCES[0x85] = '\\N';
50 ESCAPE_SEQUENCES[0xA0] = '\\_';
51 ESCAPE_SEQUENCES[0x2028] = '\\L';
52 ESCAPE_SEQUENCES[0x2029] = '\\P';
54 var DEPRECATED_BOOLEANS_SYNTAX = [
55 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
56 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
59 function compileStyleMap(schema, map) {
60 var result, keys, index, length, tag, style, type;
62 if (map === null) return {};
65 keys = Object.keys(map);
67 for (index = 0, length = keys.length; index < length; index += 1) {
69 style = String(map[tag]);
71 if (tag.slice(0, 2) === '!!') {
72 tag = 'tag:yaml.org,2002:' + tag.slice(2);
74 type = schema.compiledTypeMap['fallback'][tag];
76 if (type && _hasOwnProperty.call(type.styleAliases, style)) {
77 style = type.styleAliases[style];
86 function encodeHex(character) {
87 var string, handle, length;
89 string = character.toString(16).toUpperCase();
91 if (character <= 0xFF) {
94 } else if (character <= 0xFFFF) {
97 } else if (character <= 0xFFFFFFFF) {
101 throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
104 return '\\' + handle + common.repeat('0', length - string.length) + string;
107 function State(options) {
108 this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
109 this.indent = Math.max(1, (options['indent'] || 2));
110 this.skipInvalid = options['skipInvalid'] || false;
111 this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
112 this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
113 this.sortKeys = options['sortKeys'] || false;
114 this.lineWidth = options['lineWidth'] || 80;
115 this.noRefs = options['noRefs'] || false;
116 this.noCompatMode = options['noCompatMode'] || false;
118 this.implicitTypes = this.schema.compiledImplicit;
119 this.explicitTypes = this.schema.compiledExplicit;
124 this.duplicates = [];
125 this.usedDuplicates = null;
128 // Indents every line in a string. Empty lines (\n only) are not indented.
129 function indentString(string, spaces) {
130 var ind = common.repeat(' ', spaces),
135 length = string.length;
137 while (position < length) {
138 next = string.indexOf('\n', position);
140 line = string.slice(position);
143 line = string.slice(position, next + 1);
147 if (line.length && line !== '\n') result += ind;
155 function generateNextLine(state, level) {
156 return '\n' + common.repeat(' ', state.indent * level);
159 function testImplicitResolving(state, str) {
160 var index, length, type;
162 for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
163 type = state.implicitTypes[index];
165 if (type.resolve(str)) {
173 // [33] s-white ::= s-space | s-tab
174 function isWhitespace(c) {
175 return c === CHAR_SPACE || c === CHAR_TAB;
178 // Returns true if the character can be printed without escaping.
179 // From YAML 1.2: "any allowed characters known to be non-printable
180 // should also be escaped. [However,] This isn’t mandatory"
181 // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
182 function isPrintable(c) {
183 return (0x00020 <= c && c <= 0x00007E)
184 || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
185 || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
186 || (0x10000 <= c && c <= 0x10FFFF);
189 // Simplified test for values allowed after the first character in plain style.
190 function isPlainSafe(c) {
191 // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
192 // where nb-char ::= c-printable - b-char - c-byte-order-mark.
193 return isPrintable(c) && c !== 0xFEFF
194 // - c-flow-indicator
196 && c !== CHAR_LEFT_SQUARE_BRACKET
197 && c !== CHAR_RIGHT_SQUARE_BRACKET
198 && c !== CHAR_LEFT_CURLY_BRACKET
199 && c !== CHAR_RIGHT_CURLY_BRACKET
205 // Simplified test for values allowed as the first character in plain style.
206 function isPlainSafeFirst(c) {
207 // Uses a subset of ns-char - c-indicator
208 // where ns-char = nb-char - s-white.
209 return isPrintable(c) && c !== 0xFEFF
210 && !isWhitespace(c) // - s-white
211 // - (c-indicator ::=
212 // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
214 && c !== CHAR_QUESTION
217 && c !== CHAR_LEFT_SQUARE_BRACKET
218 && c !== CHAR_RIGHT_SQUARE_BRACKET
219 && c !== CHAR_LEFT_CURLY_BRACKET
220 && c !== CHAR_RIGHT_CURLY_BRACKET
221 // | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"”
223 && c !== CHAR_AMPERSAND
224 && c !== CHAR_ASTERISK
225 && c !== CHAR_EXCLAMATION
226 && c !== CHAR_VERTICAL_LINE
227 && c !== CHAR_GREATER_THAN
228 && c !== CHAR_SINGLE_QUOTE
229 && c !== CHAR_DOUBLE_QUOTE
230 // | “%” | “@” | “`”)
231 && c !== CHAR_PERCENT
232 && c !== CHAR_COMMERCIAL_AT
233 && c !== CHAR_GRAVE_ACCENT;
242 // Determines which scalar styles are possible and returns the preferred style.
243 // lineWidth = -1 => no limit.
244 // Pre-conditions: str.length > 0.
246 // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
247 // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
248 // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
249 function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
252 var hasLineBreak = false;
253 var hasFoldableLine = false; // only checked if shouldTrackWidth
254 var shouldTrackWidth = lineWidth !== -1;
255 var previousLineBreak = -1; // count the first line correctly
256 var plain = isPlainSafeFirst(string.charCodeAt(0))
257 && !isWhitespace(string.charCodeAt(string.length - 1));
259 if (singleLineOnly) {
260 // Case: no block styles.
261 // Check for disallowed characters to rule out plain and single.
262 for (i = 0; i < string.length; i++) {
263 char = string.charCodeAt(i);
264 if (!isPrintable(char)) {
267 plain = plain && isPlainSafe(char);
270 // Case: block styles permitted.
271 for (i = 0; i < string.length; i++) {
272 char = string.charCodeAt(i);
273 if (char === CHAR_LINE_FEED) {
275 // Check if any line can be folded.
276 if (shouldTrackWidth) {
277 hasFoldableLine = hasFoldableLine ||
278 // Foldable line = too long, and not more-indented.
279 (i - previousLineBreak - 1 > lineWidth &&
280 string[previousLineBreak + 1] !== ' ');
281 previousLineBreak = i;
283 } else if (!isPrintable(char)) {
286 plain = plain && isPlainSafe(char);
288 // in case the end is missing a \n
289 hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
290 (i - previousLineBreak - 1 > lineWidth &&
291 string[previousLineBreak + 1] !== ' '));
293 // Although every style can represent \n without escaping, prefer block styles
294 // for multiline, since they're more readable and they don't add empty lines.
295 // Also prefer folding a super-long line.
296 if (!hasLineBreak && !hasFoldableLine) {
297 // Strings interpretable as another type have to be quoted;
298 // e.g. the string 'true' vs. the boolean true.
299 return plain && !testAmbiguousType(string)
300 ? STYLE_PLAIN : STYLE_SINGLE;
302 // Edge case: block indentation indicator can only have one digit.
303 if (string[0] === ' ' && indentPerLevel > 9) {
306 // At this point we know block styles are valid.
307 // Prefer literal style unless we want to fold.
308 return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
311 // Note: line breaking/folding is implemented for only the folded style.
312 // NB. We drop the last trailing newline (if any) of a returned block scalar
313 // since the dumper adds its own newline. This always works:
314 // • No ending newline => unaffected; already using strip "-" chomping.
315 // • Ending newline => removed then restored.
316 // Importantly, this keeps the "+" chomp indicator from gaining an extra line.
317 function writeScalar(state, string, level, iskey) {
318 state.dump = (function () {
319 if (string.length === 0) {
322 if (!state.noCompatMode &&
323 DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
324 return "'" + string + "'";
327 var indent = state.indent * Math.max(1, level); // no 0-indent scalars
328 // As indentation gets deeper, let the width decrease monotonically
329 // to the lower bound min(state.lineWidth, 40).
330 // Note that this implies
331 // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
332 // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
333 // This behaves better than a constant minimum width which disallows narrower options,
334 // or an indent threshold which causes the width to suddenly increase.
335 var lineWidth = state.lineWidth === -1
336 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
338 // Without knowing if keys are implicit/explicit, assume implicit for safety.
339 var singleLineOnly = iskey
340 // No block styles in flow mode.
341 || (state.flowLevel > -1 && level >= state.flowLevel);
342 function testAmbiguity(string) {
343 return testImplicitResolving(state, string);
346 switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
350 return "'" + string.replace(/'/g, "''") + "'";
352 return '|' + blockHeader(string, state.indent)
353 + dropEndingNewline(indentString(string, indent));
355 return '>' + blockHeader(string, state.indent)
356 + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
358 return '"' + escapeString(string, lineWidth) + '"';
360 throw new YAMLException('impossible error: invalid scalar style');
365 // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
366 function blockHeader(string, indentPerLevel) {
367 var indentIndicator = (string[0] === ' ') ? String(indentPerLevel) : '';
369 // note the special case: the string '\n' counts as a "trailing" empty line.
370 var clip = string[string.length - 1] === '\n';
371 var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
372 var chomp = keep ? '+' : (clip ? '' : '-');
374 return indentIndicator + chomp + '\n';
377 // (See the note for writeScalar.)
378 function dropEndingNewline(string) {
379 return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
382 // Note: a long line without a suitable break point will exceed the width limit.
383 // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
384 function foldString(string, width) {
385 // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
386 // unless they're before or after a more-indented line, or at the very
387 // beginning or end, in which case $k$ maps to $k$.
388 // Therefore, parse each chunk as newline(s) followed by a content line.
389 var lineRe = /(\n+)([^\n]*)/g;
391 // first line (possibly an empty line)
392 var result = (function () {
393 var nextLF = string.indexOf('\n');
394 nextLF = nextLF !== -1 ? nextLF : string.length;
395 lineRe.lastIndex = nextLF;
396 return foldLine(string.slice(0, nextLF), width);
398 // If we haven't reached the first content line yet, don't add an extra \n.
399 var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
404 while ((match = lineRe.exec(string))) {
405 var prefix = match[1], line = match[2];
406 moreIndented = (line[0] === ' ');
408 + (!prevMoreIndented && !moreIndented && line !== ''
410 + foldLine(line, width);
411 prevMoreIndented = moreIndented;
417 // Greedy line breaking.
418 // Picks the longest line under the limit each time,
419 // otherwise settles for the shortest line over the limit.
420 // NB. More-indented lines *cannot* be folded, as that would add an extra \n.
421 function foldLine(line, width) {
422 if (line === '' || line[0] === ' ') return line;
424 // Since a more-indented line adds a \n, breaks can't be followed by a space.
425 var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
427 // start is an inclusive index. end, curr, and next are exclusive.
428 var start = 0, end, curr = 0, next = 0;
431 // Invariants: 0 <= start <= length-1.
432 // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
434 // A match implies length >= 2, so curr and next are <= length-2.
435 while ((match = breakRe.exec(line))) {
437 // maintain invariant: curr - start <= width
438 if (next - start > width) {
439 end = (curr > start) ? curr : next; // derive end <= length-2
440 result += '\n' + line.slice(start, end);
441 // skip the space that was output as \n
442 start = end + 1; // derive start <= length-1
447 // By the invariants, start <= length-1, so there is something left over.
448 // It is either the whole string or a part starting from non-whitespace.
450 // Insert a break if the remainder is too long and there is a break available.
451 if (line.length - start > width && curr > start) {
452 result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
454 result += line.slice(start);
457 return result.slice(1); // drop extra \n joiner
460 // Escapes a double-quoted string.
461 function escapeString(string) {
466 for (var i = 0; i < string.length; i++) {
467 char = string.charCodeAt(i);
468 escapeSeq = ESCAPE_SEQUENCES[char];
469 result += !escapeSeq && isPrintable(char)
471 : escapeSeq || encodeHex(char);
477 function writeFlowSequence(state, level, object) {
483 for (index = 0, length = object.length; index < length; index += 1) {
484 // Write only valid elements.
485 if (writeNode(state, level, object[index], false, false)) {
486 if (index !== 0) _result += ', ';
487 _result += state.dump;
492 state.dump = '[' + _result + ']';
495 function writeBlockSequence(state, level, object, compact) {
501 for (index = 0, length = object.length; index < length; index += 1) {
502 // Write only valid elements.
503 if (writeNode(state, level + 1, object[index], true, true)) {
504 if (!compact || index !== 0) {
505 _result += generateNextLine(state, level);
507 _result += '- ' + state.dump;
512 state.dump = _result || '[]'; // Empty sequence if no valid values.
515 function writeFlowMapping(state, level, object) {
518 objectKeyList = Object.keys(object),
525 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
528 if (index !== 0) pairBuffer += ', ';
530 objectKey = objectKeyList[index];
531 objectValue = object[objectKey];
533 if (!writeNode(state, level, objectKey, false, false)) {
534 continue; // Skip this pair because of invalid key;
537 if (state.dump.length > 1024) pairBuffer += '? ';
539 pairBuffer += state.dump + ': ';
541 if (!writeNode(state, level, objectValue, false, false)) {
542 continue; // Skip this pair because of invalid value.
545 pairBuffer += state.dump;
547 // Both key and value are valid.
548 _result += pairBuffer;
552 state.dump = '{' + _result + '}';
555 function writeBlockMapping(state, level, object, compact) {
558 objectKeyList = Object.keys(object),
566 // Allow sorting keys so that the output file is deterministic
567 if (state.sortKeys === true) {
569 objectKeyList.sort();
570 } else if (typeof state.sortKeys === 'function') {
571 // Custom sort function
572 objectKeyList.sort(state.sortKeys);
573 } else if (state.sortKeys) {
574 // Something is wrong
575 throw new YAMLException('sortKeys must be a boolean or a function');
578 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
581 if (!compact || index !== 0) {
582 pairBuffer += generateNextLine(state, level);
585 objectKey = objectKeyList[index];
586 objectValue = object[objectKey];
588 if (!writeNode(state, level + 1, objectKey, true, true, true)) {
589 continue; // Skip this pair because of invalid key.
592 explicitPair = (state.tag !== null && state.tag !== '?') ||
593 (state.dump && state.dump.length > 1024);
596 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
603 pairBuffer += state.dump;
606 pairBuffer += generateNextLine(state, level);
609 if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
610 continue; // Skip this pair because of invalid value.
613 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
619 pairBuffer += state.dump;
621 // Both key and value are valid.
622 _result += pairBuffer;
626 state.dump = _result || '{}'; // Empty mapping if no valid pairs.
629 function detectType(state, object, explicit) {
630 var _result, typeList, index, length, type, style;
632 typeList = explicit ? state.explicitTypes : state.implicitTypes;
634 for (index = 0, length = typeList.length; index < length; index += 1) {
635 type = typeList[index];
637 if ((type.instanceOf || type.predicate) &&
638 (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
639 (!type.predicate || type.predicate(object))) {
641 state.tag = explicit ? type.tag : '?';
643 if (type.represent) {
644 style = state.styleMap[type.tag] || type.defaultStyle;
646 if (_toString.call(type.represent) === '[object Function]') {
647 _result = type.represent(object, style);
648 } else if (_hasOwnProperty.call(type.represent, style)) {
649 _result = type.represent[style](object, style);
651 throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
654 state.dump = _result;
664 // Serializes `object` and writes it to global `result`.
665 // Returns true on success, or false on invalid object.
667 function writeNode(state, level, object, block, compact, iskey) {
671 if (!detectType(state, object, false)) {
672 detectType(state, object, true);
675 var type = _toString.call(state.dump);
678 block = (state.flowLevel < 0 || state.flowLevel > level);
681 var objectOrArray = type === '[object Object]' || type === '[object Array]',
686 duplicateIndex = state.duplicates.indexOf(object);
687 duplicate = duplicateIndex !== -1;
690 if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
694 if (duplicate && state.usedDuplicates[duplicateIndex]) {
695 state.dump = '*ref_' + duplicateIndex;
697 if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
698 state.usedDuplicates[duplicateIndex] = true;
700 if (type === '[object Object]') {
701 if (block && (Object.keys(state.dump).length !== 0)) {
702 writeBlockMapping(state, level, state.dump, compact);
704 state.dump = '&ref_' + duplicateIndex + state.dump;
707 writeFlowMapping(state, level, state.dump);
709 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
712 } else if (type === '[object Array]') {
713 if (block && (state.dump.length !== 0)) {
714 writeBlockSequence(state, level, state.dump, compact);
716 state.dump = '&ref_' + duplicateIndex + state.dump;
719 writeFlowSequence(state, level, state.dump);
721 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
724 } else if (type === '[object String]') {
725 if (state.tag !== '?') {
726 writeScalar(state, state.dump, level, iskey);
729 if (state.skipInvalid) return false;
730 throw new YAMLException('unacceptable kind of an object to dump ' + type);
733 if (state.tag !== null && state.tag !== '?') {
734 state.dump = '!<' + state.tag + '> ' + state.dump;
741 function getDuplicateReferences(object, state) {
743 duplicatesIndexes = [],
747 inspectNode(object, objects, duplicatesIndexes);
749 for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
750 state.duplicates.push(objects[duplicatesIndexes[index]]);
752 state.usedDuplicates = new Array(length);
755 function inspectNode(object, objects, duplicatesIndexes) {
760 if (object !== null && typeof object === 'object') {
761 index = objects.indexOf(object);
763 if (duplicatesIndexes.indexOf(index) === -1) {
764 duplicatesIndexes.push(index);
767 objects.push(object);
769 if (Array.isArray(object)) {
770 for (index = 0, length = object.length; index < length; index += 1) {
771 inspectNode(object[index], objects, duplicatesIndexes);
774 objectKeyList = Object.keys(object);
776 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
777 inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
784 function dump(input, options) {
785 options = options || {};
787 var state = new State(options);
789 if (!state.noRefs) getDuplicateReferences(input, state);
791 if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
796 function safeDump(input, options) {
797 return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
800 module.exports.dump = dump;
801 module.exports.safeDump = safeDump;