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_CARRIAGE_RETURN = 0x0D; /* CR */
16 var CHAR_SPACE = 0x20; /* Space */
17 var CHAR_EXCLAMATION = 0x21; /* ! */
18 var CHAR_DOUBLE_QUOTE = 0x22; /* " */
19 var CHAR_SHARP = 0x23; /* # */
20 var CHAR_PERCENT = 0x25; /* % */
21 var CHAR_AMPERSAND = 0x26; /* & */
22 var CHAR_SINGLE_QUOTE = 0x27; /* ' */
23 var CHAR_ASTERISK = 0x2A; /* * */
24 var CHAR_COMMA = 0x2C; /* , */
25 var CHAR_MINUS = 0x2D; /* - */
26 var CHAR_COLON = 0x3A; /* : */
27 var CHAR_GREATER_THAN = 0x3E; /* > */
28 var CHAR_QUESTION = 0x3F; /* ? */
29 var CHAR_COMMERCIAL_AT = 0x40; /* @ */
30 var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
31 var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
32 var CHAR_GRAVE_ACCENT = 0x60; /* ` */
33 var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
34 var CHAR_VERTICAL_LINE = 0x7C; /* | */
35 var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
37 var ESCAPE_SEQUENCES = {};
39 ESCAPE_SEQUENCES[0x00] = '\\0';
40 ESCAPE_SEQUENCES[0x07] = '\\a';
41 ESCAPE_SEQUENCES[0x08] = '\\b';
42 ESCAPE_SEQUENCES[0x09] = '\\t';
43 ESCAPE_SEQUENCES[0x0A] = '\\n';
44 ESCAPE_SEQUENCES[0x0B] = '\\v';
45 ESCAPE_SEQUENCES[0x0C] = '\\f';
46 ESCAPE_SEQUENCES[0x0D] = '\\r';
47 ESCAPE_SEQUENCES[0x1B] = '\\e';
48 ESCAPE_SEQUENCES[0x22] = '\\"';
49 ESCAPE_SEQUENCES[0x5C] = '\\\\';
50 ESCAPE_SEQUENCES[0x85] = '\\N';
51 ESCAPE_SEQUENCES[0xA0] = '\\_';
52 ESCAPE_SEQUENCES[0x2028] = '\\L';
53 ESCAPE_SEQUENCES[0x2029] = '\\P';
55 var DEPRECATED_BOOLEANS_SYNTAX = [
56 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
57 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
60 function compileStyleMap(schema, map) {
61 var result, keys, index, length, tag, style, type;
63 if (map === null) return {};
66 keys = Object.keys(map);
68 for (index = 0, length = keys.length; index < length; index += 1) {
70 style = String(map[tag]);
72 if (tag.slice(0, 2) === '!!') {
73 tag = 'tag:yaml.org,2002:' + tag.slice(2);
76 type = schema.compiledTypeMap[tag];
78 if (type && _hasOwnProperty.call(type.styleAliases, style)) {
79 style = type.styleAliases[style];
88 function encodeHex(character) {
89 var string, handle, length;
91 string = character.toString(16).toUpperCase();
93 if (character <= 0xFF) {
96 } else if (character <= 0xFFFF) {
99 } else if (character <= 0xFFFFFFFF) {
103 throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
106 return '\\' + handle + common.repeat('0', length - string.length) + string;
109 function State(options) {
110 this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
111 this.indent = Math.max(1, (options['indent'] || 2));
112 this.skipInvalid = options['skipInvalid'] || false;
113 this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
114 this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
115 this.sortKeys = options['sortKeys'] || false;
116 this.lineWidth = options['lineWidth'] || 80;
117 this.noRefs = options['noRefs'] || false;
118 this.noCompatMode = options['noCompatMode'] || false;
120 this.implicitTypes = this.schema.compiledImplicit;
121 this.explicitTypes = this.schema.compiledExplicit;
126 this.duplicates = [];
127 this.usedDuplicates = null;
130 function indentString(string, spaces) {
131 var ind = common.repeat(' ', spaces),
136 length = string.length;
138 while (position < length) {
139 next = string.indexOf('\n', position);
141 line = string.slice(position);
144 line = string.slice(position, next + 1);
148 if (line.length && line !== '\n') result += ind;
156 function generateNextLine(state, level) {
157 return '\n' + common.repeat(' ', state.indent * level);
160 function testImplicitResolving(state, str) {
161 var index, length, type;
163 for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
164 type = state.implicitTypes[index];
166 if (type.resolve(str)) {
174 function StringBuilder(source) {
175 this.source = source;
180 StringBuilder.prototype.takeUpTo = function (position) {
183 if (position < this.checkpoint) {
184 er = new Error('position should be > checkpoint');
185 er.position = position;
186 er.checkpoint = this.checkpoint;
190 this.result += this.source.slice(this.checkpoint, position);
191 this.checkpoint = position;
195 StringBuilder.prototype.escapeChar = function () {
198 character = this.source.charCodeAt(this.checkpoint);
199 esc = ESCAPE_SEQUENCES[character] || encodeHex(character);
201 this.checkpoint += 1;
206 StringBuilder.prototype.finish = function () {
207 if (this.source.length > this.checkpoint) {
208 this.takeUpTo(this.source.length);
212 function writeScalar(state, object, level, iskey) {
213 var simple, first, spaceWrap, folded, literal, single, double,
214 sawLineFeed, linePosition, longestLine, indent, max, character,
215 position, escapeSeq, hexEsc, previous, lineLength, modifier,
216 trailingLineBreaks, result;
218 if (object.length === 0) {
223 if (!state.noCompatMode &&
224 DEPRECATED_BOOLEANS_SYNTAX.indexOf(object) !== -1) {
225 state.dump = "'" + object + "'";
230 first = object.length ? object.charCodeAt(0) : 0;
231 spaceWrap = (CHAR_SPACE === first ||
232 CHAR_SPACE === object.charCodeAt(object.length - 1));
234 // Simplified check for restricted first characters
235 // http://www.yaml.org/spec/1.2/spec.html#ns-plain-first%28c%29
236 if (CHAR_MINUS === first ||
237 CHAR_QUESTION === first ||
238 CHAR_COMMERCIAL_AT === first ||
239 CHAR_GRAVE_ACCENT === first) {
243 // Can only use > and | if not wrapped in spaces or is not a key.
244 // Also, don't use if in flow mode.
245 if (spaceWrap || (state.flowLevel > -1 && state.flowLevel <= level)) {
246 if (spaceWrap) simple = false;
256 double = new StringBuilder(object);
262 indent = state.indent * level;
263 max = state.lineWidth;
265 // Replace -1 with biggest ingeger number according to
266 // http://ecma262-5.com/ELS5_HTML.htm#Section_8.5
267 if (max === -1) max = 9007199254740991;
269 if (indent < 40) max -= indent;
272 for (position = 0; position < object.length; position++) {
273 character = object.charCodeAt(position);
275 // Characters that can never appear in the simple scalar
276 if (!simpleChar(character)) {
279 // Still simple. If we make it all the way through like
280 // this, then we can just dump the string as-is.
285 if (single && character === CHAR_SINGLE_QUOTE) {
289 escapeSeq = ESCAPE_SEQUENCES[character];
290 hexEsc = needsHexEscape(character);
292 if (!escapeSeq && !hexEsc) {
296 if (character !== CHAR_LINE_FEED &&
297 character !== CHAR_DOUBLE_QUOTE &&
298 character !== CHAR_SINGLE_QUOTE) {
301 } else if (character === CHAR_LINE_FEED) {
305 previous = object.charCodeAt(position - 1);
306 if (previous === CHAR_SPACE) {
312 lineLength = position - linePosition;
313 linePosition = position;
314 if (lineLength > longestLine) longestLine = lineLength;
318 if (character !== CHAR_DOUBLE_QUOTE) single = false;
320 double.takeUpTo(position);
324 if (simple && testImplicitResolving(state, object)) simple = false;
327 if (folded || literal) {
328 trailingLineBreaks = 0;
329 if (object.charCodeAt(object.length - 1) === CHAR_LINE_FEED) {
330 trailingLineBreaks += 1;
331 if (object.charCodeAt(object.length - 2) === CHAR_LINE_FEED) {
332 trailingLineBreaks += 1;
336 if (trailingLineBreaks === 0) modifier = '-';
337 else if (trailingLineBreaks === 2) modifier = '+';
340 if (literal && longestLine < max || state.tag !== null) {
344 // If it's literally one line, then don't bother with the literal.
345 // We may still want to do a fold, though, if it's a super long line.
346 if (!sawLineFeed) literal = false;
351 state.dump = '\'' + object + '\'';
353 result = fold(object, max);
354 state.dump = '>' + modifier + '\n' + indentString(result, indent);
355 } else if (literal) {
356 if (!modifier) object = object.replace(/\n$/, '');
357 state.dump = '|' + modifier + '\n' + indentString(object, indent);
360 state.dump = '"' + double.result + '"';
362 throw new Error('Failed to dump scalar value');
368 // The `trailing` var is a regexp match of any trailing `\n` characters.
370 // There are three cases we care about:
372 // 1. One trailing `\n` on the string. Just use `|` or `>`.
373 // This is the assumed default. (trailing = null)
374 // 2. No trailing `\n` on the string. Use `|-` or `>-` to "chomp" the end.
375 // 3. More than one trailing `\n` on the string. Use `|+` or `>+`.
377 // In the case of `>+`, these line breaks are *not* doubled (like the line
378 // breaks within the string), so it's important to only end with the exact
379 // same number as we started.
380 function fold(object, max) {
383 length = object.length,
384 trailing = /\n+$/.exec(object),
388 length = trailing.index + 1;
391 while (position < length) {
392 newLine = object.indexOf('\n', position);
393 if (newLine > length || newLine === -1) {
394 if (result) result += '\n\n';
395 result += foldLine(object.slice(position, length), max);
399 if (result) result += '\n\n';
400 result += foldLine(object.slice(position, newLine), max);
401 position = newLine + 1;
405 if (trailing && trailing[0] !== '\n') result += trailing[0];
410 function foldLine(line, max) {
411 if (line === '') return line;
413 var foldRe = /[^\s] [^\s]/g,
417 match = foldRe.exec(line),
425 // when we cross the max len, if the previous match would've
426 // been ok, use that one, and carry on. If there was no previous
427 // match on this fold section, then just have a long line.
428 if (index - foldStart > max) {
429 if (prevMatch !== foldStart) foldEnd = prevMatch;
430 else foldEnd = index;
432 if (result) result += '\n';
433 folded = line.slice(foldStart, foldEnd);
435 foldStart = foldEnd + 1;
437 prevMatch = index + 1;
438 match = foldRe.exec(line);
441 if (result) result += '\n';
443 // if we end up with one last word at the end, then the last bit might
444 // be slightly bigger than we wanted, because we exited out of the loop.
445 if (foldStart !== prevMatch && line.length - foldStart > max) {
446 result += line.slice(foldStart, prevMatch) + '\n' +
447 line.slice(prevMatch + 1);
449 result += line.slice(foldStart);
455 // Returns true if character can be found in a simple scalar
456 function simpleChar(character) {
457 return CHAR_TAB !== character &&
458 CHAR_LINE_FEED !== character &&
459 CHAR_CARRIAGE_RETURN !== character &&
460 CHAR_COMMA !== character &&
461 CHAR_LEFT_SQUARE_BRACKET !== character &&
462 CHAR_RIGHT_SQUARE_BRACKET !== character &&
463 CHAR_LEFT_CURLY_BRACKET !== character &&
464 CHAR_RIGHT_CURLY_BRACKET !== character &&
465 CHAR_SHARP !== character &&
466 CHAR_AMPERSAND !== character &&
467 CHAR_ASTERISK !== character &&
468 CHAR_EXCLAMATION !== character &&
469 CHAR_VERTICAL_LINE !== character &&
470 CHAR_GREATER_THAN !== character &&
471 CHAR_SINGLE_QUOTE !== character &&
472 CHAR_DOUBLE_QUOTE !== character &&
473 CHAR_PERCENT !== character &&
474 CHAR_COLON !== character &&
475 !ESCAPE_SEQUENCES[character] &&
476 !needsHexEscape(character);
479 // Returns true if the character code needs to be escaped.
480 function needsHexEscape(character) {
481 return !((0x00020 <= character && character <= 0x00007E) ||
482 (character === 0x00085) ||
483 (0x000A0 <= character && character <= 0x00D7FF) ||
484 (0x0E000 <= character && character <= 0x00FFFD) ||
485 (0x10000 <= character && character <= 0x10FFFF));
488 function writeFlowSequence(state, level, object) {
494 for (index = 0, length = object.length; index < length; index += 1) {
495 // Write only valid elements.
496 if (writeNode(state, level, object[index], false, false)) {
497 if (index !== 0) _result += ', ';
498 _result += state.dump;
503 state.dump = '[' + _result + ']';
506 function writeBlockSequence(state, level, object, compact) {
512 for (index = 0, length = object.length; index < length; index += 1) {
513 // Write only valid elements.
514 if (writeNode(state, level + 1, object[index], true, true)) {
515 if (!compact || index !== 0) {
516 _result += generateNextLine(state, level);
518 _result += '- ' + state.dump;
523 state.dump = _result || '[]'; // Empty sequence if no valid values.
526 function writeFlowMapping(state, level, object) {
529 objectKeyList = Object.keys(object),
536 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
539 if (index !== 0) pairBuffer += ', ';
541 objectKey = objectKeyList[index];
542 objectValue = object[objectKey];
544 if (!writeNode(state, level, objectKey, false, false)) {
545 continue; // Skip this pair because of invalid key;
548 if (state.dump.length > 1024) pairBuffer += '? ';
550 pairBuffer += state.dump + ': ';
552 if (!writeNode(state, level, objectValue, false, false)) {
553 continue; // Skip this pair because of invalid value.
556 pairBuffer += state.dump;
558 // Both key and value are valid.
559 _result += pairBuffer;
563 state.dump = '{' + _result + '}';
566 function writeBlockMapping(state, level, object, compact) {
569 objectKeyList = Object.keys(object),
577 // Allow sorting keys so that the output file is deterministic
578 if (state.sortKeys === true) {
580 objectKeyList.sort();
581 } else if (typeof state.sortKeys === 'function') {
582 // Custom sort function
583 objectKeyList.sort(state.sortKeys);
584 } else if (state.sortKeys) {
585 // Something is wrong
586 throw new YAMLException('sortKeys must be a boolean or a function');
589 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
592 if (!compact || index !== 0) {
593 pairBuffer += generateNextLine(state, level);
596 objectKey = objectKeyList[index];
597 objectValue = object[objectKey];
599 if (!writeNode(state, level + 1, objectKey, true, true, true)) {
600 continue; // Skip this pair because of invalid key.
603 explicitPair = (state.tag !== null && state.tag !== '?') ||
604 (state.dump && state.dump.length > 1024);
607 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
614 pairBuffer += state.dump;
617 pairBuffer += generateNextLine(state, level);
620 if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
621 continue; // Skip this pair because of invalid value.
624 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
630 pairBuffer += state.dump;
632 // Both key and value are valid.
633 _result += pairBuffer;
637 state.dump = _result || '{}'; // Empty mapping if no valid pairs.
640 function detectType(state, object, explicit) {
641 var _result, typeList, index, length, type, style;
643 typeList = explicit ? state.explicitTypes : state.implicitTypes;
645 for (index = 0, length = typeList.length; index < length; index += 1) {
646 type = typeList[index];
648 if ((type.instanceOf || type.predicate) &&
649 (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
650 (!type.predicate || type.predicate(object))) {
652 state.tag = explicit ? type.tag : '?';
654 if (type.represent) {
655 style = state.styleMap[type.tag] || type.defaultStyle;
657 if (_toString.call(type.represent) === '[object Function]') {
658 _result = type.represent(object, style);
659 } else if (_hasOwnProperty.call(type.represent, style)) {
660 _result = type.represent[style](object, style);
662 throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
665 state.dump = _result;
675 // Serializes `object` and writes it to global `result`.
676 // Returns true on success, or false on invalid object.
678 function writeNode(state, level, object, block, compact, iskey) {
682 if (!detectType(state, object, false)) {
683 detectType(state, object, true);
686 var type = _toString.call(state.dump);
689 block = (state.flowLevel < 0 || state.flowLevel > level);
692 var objectOrArray = type === '[object Object]' || type === '[object Array]',
697 duplicateIndex = state.duplicates.indexOf(object);
698 duplicate = duplicateIndex !== -1;
701 if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
705 if (duplicate && state.usedDuplicates[duplicateIndex]) {
706 state.dump = '*ref_' + duplicateIndex;
708 if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
709 state.usedDuplicates[duplicateIndex] = true;
711 if (type === '[object Object]') {
712 if (block && (Object.keys(state.dump).length !== 0)) {
713 writeBlockMapping(state, level, state.dump, compact);
715 state.dump = '&ref_' + duplicateIndex + state.dump;
718 writeFlowMapping(state, level, state.dump);
720 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
723 } else if (type === '[object Array]') {
724 if (block && (state.dump.length !== 0)) {
725 writeBlockSequence(state, level, state.dump, compact);
727 state.dump = '&ref_' + duplicateIndex + state.dump;
730 writeFlowSequence(state, level, state.dump);
732 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
735 } else if (type === '[object String]') {
736 if (state.tag !== '?') {
737 writeScalar(state, state.dump, level, iskey);
740 if (state.skipInvalid) return false;
741 throw new YAMLException('unacceptable kind of an object to dump ' + type);
744 if (state.tag !== null && state.tag !== '?') {
745 state.dump = '!<' + state.tag + '> ' + state.dump;
752 function getDuplicateReferences(object, state) {
754 duplicatesIndexes = [],
758 inspectNode(object, objects, duplicatesIndexes);
760 for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
761 state.duplicates.push(objects[duplicatesIndexes[index]]);
763 state.usedDuplicates = new Array(length);
766 function inspectNode(object, objects, duplicatesIndexes) {
771 if (object !== null && typeof object === 'object') {
772 index = objects.indexOf(object);
774 if (duplicatesIndexes.indexOf(index) === -1) {
775 duplicatesIndexes.push(index);
778 objects.push(object);
780 if (Array.isArray(object)) {
781 for (index = 0, length = object.length; index < length; index += 1) {
782 inspectNode(object[index], objects, duplicatesIndexes);
785 objectKeyList = Object.keys(object);
787 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
788 inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
795 function dump(input, options) {
796 options = options || {};
798 var state = new State(options);
800 if (!state.noRefs) getDuplicateReferences(input, state);
802 if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
807 function safeDump(input, options) {
808 return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
811 module.exports.dump = dump;
812 module.exports.safeDump = safeDump;