dumper.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. 'use strict';
  2. /*eslint-disable no-use-before-define*/
  3. var common = require('./common');
  4. var YAMLException = require('./exception');
  5. var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
  6. var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
  7. var _toString = Object.prototype.toString;
  8. var _hasOwnProperty = Object.prototype.hasOwnProperty;
  9. var CHAR_TAB = 0x09; /* Tab */
  10. var CHAR_LINE_FEED = 0x0A; /* LF */
  11. var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
  12. var CHAR_SPACE = 0x20; /* Space */
  13. var CHAR_EXCLAMATION = 0x21; /* ! */
  14. var CHAR_DOUBLE_QUOTE = 0x22; /* " */
  15. var CHAR_SHARP = 0x23; /* # */
  16. var CHAR_PERCENT = 0x25; /* % */
  17. var CHAR_AMPERSAND = 0x26; /* & */
  18. var CHAR_SINGLE_QUOTE = 0x27; /* ' */
  19. var CHAR_ASTERISK = 0x2A; /* * */
  20. var CHAR_COMMA = 0x2C; /* , */
  21. var CHAR_MINUS = 0x2D; /* - */
  22. var CHAR_COLON = 0x3A; /* : */
  23. var CHAR_EQUALS = 0x3D; /* = */
  24. var CHAR_GREATER_THAN = 0x3E; /* > */
  25. var CHAR_QUESTION = 0x3F; /* ? */
  26. var CHAR_COMMERCIAL_AT = 0x40; /* @ */
  27. var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
  28. var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
  29. var CHAR_GRAVE_ACCENT = 0x60; /* ` */
  30. var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
  31. var CHAR_VERTICAL_LINE = 0x7C; /* | */
  32. var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
  33. var ESCAPE_SEQUENCES = {};
  34. ESCAPE_SEQUENCES[0x00] = '\\0';
  35. ESCAPE_SEQUENCES[0x07] = '\\a';
  36. ESCAPE_SEQUENCES[0x08] = '\\b';
  37. ESCAPE_SEQUENCES[0x09] = '\\t';
  38. ESCAPE_SEQUENCES[0x0A] = '\\n';
  39. ESCAPE_SEQUENCES[0x0B] = '\\v';
  40. ESCAPE_SEQUENCES[0x0C] = '\\f';
  41. ESCAPE_SEQUENCES[0x0D] = '\\r';
  42. ESCAPE_SEQUENCES[0x1B] = '\\e';
  43. ESCAPE_SEQUENCES[0x22] = '\\"';
  44. ESCAPE_SEQUENCES[0x5C] = '\\\\';
  45. ESCAPE_SEQUENCES[0x85] = '\\N';
  46. ESCAPE_SEQUENCES[0xA0] = '\\_';
  47. ESCAPE_SEQUENCES[0x2028] = '\\L';
  48. ESCAPE_SEQUENCES[0x2029] = '\\P';
  49. var DEPRECATED_BOOLEANS_SYNTAX = [
  50. 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
  51. 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
  52. ];
  53. function compileStyleMap(schema, map) {
  54. var result, keys, index, length, tag, style, type;
  55. if (map === null) return {};
  56. result = {};
  57. keys = Object.keys(map);
  58. for (index = 0, length = keys.length; index < length; index += 1) {
  59. tag = keys[index];
  60. style = String(map[tag]);
  61. if (tag.slice(0, 2) === '!!') {
  62. tag = 'tag:yaml.org,2002:' + tag.slice(2);
  63. }
  64. type = schema.compiledTypeMap['fallback'][tag];
  65. if (type && _hasOwnProperty.call(type.styleAliases, style)) {
  66. style = type.styleAliases[style];
  67. }
  68. result[tag] = style;
  69. }
  70. return result;
  71. }
  72. function encodeHex(character) {
  73. var string, handle, length;
  74. string = character.toString(16).toUpperCase();
  75. if (character <= 0xFF) {
  76. handle = 'x';
  77. length = 2;
  78. } else if (character <= 0xFFFF) {
  79. handle = 'u';
  80. length = 4;
  81. } else if (character <= 0xFFFFFFFF) {
  82. handle = 'U';
  83. length = 8;
  84. } else {
  85. throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
  86. }
  87. return '\\' + handle + common.repeat('0', length - string.length) + string;
  88. }
  89. function State(options) {
  90. this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
  91. this.indent = Math.max(1, (options['indent'] || 2));
  92. this.noArrayIndent = options['noArrayIndent'] || false;
  93. this.skipInvalid = options['skipInvalid'] || false;
  94. this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
  95. this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
  96. this.sortKeys = options['sortKeys'] || false;
  97. this.lineWidth = options['lineWidth'] || 80;
  98. this.noRefs = options['noRefs'] || false;
  99. this.noCompatMode = options['noCompatMode'] || false;
  100. this.condenseFlow = options['condenseFlow'] || false;
  101. this.implicitTypes = this.schema.compiledImplicit;
  102. this.explicitTypes = this.schema.compiledExplicit;
  103. this.tag = null;
  104. this.result = '';
  105. this.duplicates = [];
  106. this.usedDuplicates = null;
  107. }
  108. // Indents every line in a string. Empty lines (\n only) are not indented.
  109. function indentString(string, spaces) {
  110. var ind = common.repeat(' ', spaces),
  111. position = 0,
  112. next = -1,
  113. result = '',
  114. line,
  115. length = string.length;
  116. while (position < length) {
  117. next = string.indexOf('\n', position);
  118. if (next === -1) {
  119. line = string.slice(position);
  120. position = length;
  121. } else {
  122. line = string.slice(position, next + 1);
  123. position = next + 1;
  124. }
  125. if (line.length && line !== '\n') result += ind;
  126. result += line;
  127. }
  128. return result;
  129. }
  130. function generateNextLine(state, level) {
  131. return '\n' + common.repeat(' ', state.indent * level);
  132. }
  133. function testImplicitResolving(state, str) {
  134. var index, length, type;
  135. for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
  136. type = state.implicitTypes[index];
  137. if (type.resolve(str)) {
  138. return true;
  139. }
  140. }
  141. return false;
  142. }
  143. // [33] s-white ::= s-space | s-tab
  144. function isWhitespace(c) {
  145. return c === CHAR_SPACE || c === CHAR_TAB;
  146. }
  147. // Returns true if the character can be printed without escaping.
  148. // From YAML 1.2: "any allowed characters known to be non-printable
  149. // should also be escaped. [However,] This isn’t mandatory"
  150. // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
  151. function isPrintable(c) {
  152. return (0x00020 <= c && c <= 0x00007E)
  153. || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
  154. || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
  155. || (0x10000 <= c && c <= 0x10FFFF);
  156. }
  157. // [34] ns-char ::= nb-char - s-white
  158. // [27] nb-char ::= c-printable - b-char - c-byte-order-mark
  159. // [26] b-char ::= b-line-feed | b-carriage-return
  160. // [24] b-line-feed ::= #xA /* LF */
  161. // [25] b-carriage-return ::= #xD /* CR */
  162. // [3] c-byte-order-mark ::= #xFEFF
  163. function isNsChar(c) {
  164. return isPrintable(c) && !isWhitespace(c)
  165. // byte-order-mark
  166. && c !== 0xFEFF
  167. // b-char
  168. && c !== CHAR_CARRIAGE_RETURN
  169. && c !== CHAR_LINE_FEED;
  170. }
  171. // Simplified test for values allowed after the first character in plain style.
  172. function isPlainSafe(c, prev) {
  173. // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
  174. // where nb-char ::= c-printable - b-char - c-byte-order-mark.
  175. return isPrintable(c) && c !== 0xFEFF
  176. // - c-flow-indicator
  177. && c !== CHAR_COMMA
  178. && c !== CHAR_LEFT_SQUARE_BRACKET
  179. && c !== CHAR_RIGHT_SQUARE_BRACKET
  180. && c !== CHAR_LEFT_CURLY_BRACKET
  181. && c !== CHAR_RIGHT_CURLY_BRACKET
  182. // - ":" - "#"
  183. // /* An ns-char preceding */ "#"
  184. && c !== CHAR_COLON
  185. && ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));
  186. }
  187. // Simplified test for values allowed as the first character in plain style.
  188. function isPlainSafeFirst(c) {
  189. // Uses a subset of ns-char - c-indicator
  190. // where ns-char = nb-char - s-white.
  191. return isPrintable(c) && c !== 0xFEFF
  192. && !isWhitespace(c) // - s-white
  193. // - (c-indicator ::=
  194. // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
  195. && c !== CHAR_MINUS
  196. && c !== CHAR_QUESTION
  197. && c !== CHAR_COLON
  198. && c !== CHAR_COMMA
  199. && c !== CHAR_LEFT_SQUARE_BRACKET
  200. && c !== CHAR_RIGHT_SQUARE_BRACKET
  201. && c !== CHAR_LEFT_CURLY_BRACKET
  202. && c !== CHAR_RIGHT_CURLY_BRACKET
  203. // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
  204. && c !== CHAR_SHARP
  205. && c !== CHAR_AMPERSAND
  206. && c !== CHAR_ASTERISK
  207. && c !== CHAR_EXCLAMATION
  208. && c !== CHAR_VERTICAL_LINE
  209. && c !== CHAR_EQUALS
  210. && c !== CHAR_GREATER_THAN
  211. && c !== CHAR_SINGLE_QUOTE
  212. && c !== CHAR_DOUBLE_QUOTE
  213. // | “%” | “@” | “`”)
  214. && c !== CHAR_PERCENT
  215. && c !== CHAR_COMMERCIAL_AT
  216. && c !== CHAR_GRAVE_ACCENT;
  217. }
  218. // Determines whether block indentation indicator is required.
  219. function needIndentIndicator(string) {
  220. var leadingSpaceRe = /^\n* /;
  221. return leadingSpaceRe.test(string);
  222. }
  223. var STYLE_PLAIN = 1,
  224. STYLE_SINGLE = 2,
  225. STYLE_LITERAL = 3,
  226. STYLE_FOLDED = 4,
  227. STYLE_DOUBLE = 5;
  228. // Determines which scalar styles are possible and returns the preferred style.
  229. // lineWidth = -1 => no limit.
  230. // Pre-conditions: str.length > 0.
  231. // Post-conditions:
  232. // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
  233. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
  234. // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
  235. function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
  236. var i;
  237. var char, prev_char;
  238. var hasLineBreak = false;
  239. var hasFoldableLine = false; // only checked if shouldTrackWidth
  240. var shouldTrackWidth = lineWidth !== -1;
  241. var previousLineBreak = -1; // count the first line correctly
  242. var plain = isPlainSafeFirst(string.charCodeAt(0))
  243. && !isWhitespace(string.charCodeAt(string.length - 1));
  244. if (singleLineOnly) {
  245. // Case: no block styles.
  246. // Check for disallowed characters to rule out plain and single.
  247. for (i = 0; i < string.length; i++) {
  248. char = string.charCodeAt(i);
  249. if (!isPrintable(char)) {
  250. return STYLE_DOUBLE;
  251. }
  252. prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
  253. plain = plain && isPlainSafe(char, prev_char);
  254. }
  255. } else {
  256. // Case: block styles permitted.
  257. for (i = 0; i < string.length; i++) {
  258. char = string.charCodeAt(i);
  259. if (char === CHAR_LINE_FEED) {
  260. hasLineBreak = true;
  261. // Check if any line can be folded.
  262. if (shouldTrackWidth) {
  263. hasFoldableLine = hasFoldableLine ||
  264. // Foldable line = too long, and not more-indented.
  265. (i - previousLineBreak - 1 > lineWidth &&
  266. string[previousLineBreak + 1] !== ' ');
  267. previousLineBreak = i;
  268. }
  269. } else if (!isPrintable(char)) {
  270. return STYLE_DOUBLE;
  271. }
  272. prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
  273. plain = plain && isPlainSafe(char, prev_char);
  274. }
  275. // in case the end is missing a \n
  276. hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
  277. (i - previousLineBreak - 1 > lineWidth &&
  278. string[previousLineBreak + 1] !== ' '));
  279. }
  280. // Although every style can represent \n without escaping, prefer block styles
  281. // for multiline, since they're more readable and they don't add empty lines.
  282. // Also prefer folding a super-long line.
  283. if (!hasLineBreak && !hasFoldableLine) {
  284. // Strings interpretable as another type have to be quoted;
  285. // e.g. the string 'true' vs. the boolean true.
  286. return plain && !testAmbiguousType(string)
  287. ? STYLE_PLAIN : STYLE_SINGLE;
  288. }
  289. // Edge case: block indentation indicator can only have one digit.
  290. if (indentPerLevel > 9 && needIndentIndicator(string)) {
  291. return STYLE_DOUBLE;
  292. }
  293. // At this point we know block styles are valid.
  294. // Prefer literal style unless we want to fold.
  295. return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
  296. }
  297. // Note: line breaking/folding is implemented for only the folded style.
  298. // NB. We drop the last trailing newline (if any) of a returned block scalar
  299. // since the dumper adds its own newline. This always works:
  300. // • No ending newline => unaffected; already using strip "-" chomping.
  301. // • Ending newline => removed then restored.
  302. // Importantly, this keeps the "+" chomp indicator from gaining an extra line.
  303. function writeScalar(state, string, level, iskey) {
  304. state.dump = (function () {
  305. if (string.length === 0) {
  306. return "''";
  307. }
  308. if (!state.noCompatMode &&
  309. DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
  310. return "'" + string + "'";
  311. }
  312. var indent = state.indent * Math.max(1, level); // no 0-indent scalars
  313. // As indentation gets deeper, let the width decrease monotonically
  314. // to the lower bound min(state.lineWidth, 40).
  315. // Note that this implies
  316. // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
  317. // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
  318. // This behaves better than a constant minimum width which disallows narrower options,
  319. // or an indent threshold which causes the width to suddenly increase.
  320. var lineWidth = state.lineWidth === -1
  321. ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
  322. // Without knowing if keys are implicit/explicit, assume implicit for safety.
  323. var singleLineOnly = iskey
  324. // No block styles in flow mode.
  325. || (state.flowLevel > -1 && level >= state.flowLevel);
  326. function testAmbiguity(string) {
  327. return testImplicitResolving(state, string);
  328. }
  329. switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
  330. case STYLE_PLAIN:
  331. return string;
  332. case STYLE_SINGLE:
  333. return "'" + string.replace(/'/g, "''") + "'";
  334. case STYLE_LITERAL:
  335. return '|' + blockHeader(string, state.indent)
  336. + dropEndingNewline(indentString(string, indent));
  337. case STYLE_FOLDED:
  338. return '>' + blockHeader(string, state.indent)
  339. + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
  340. case STYLE_DOUBLE:
  341. return '"' + escapeString(string, lineWidth) + '"';
  342. default:
  343. throw new YAMLException('impossible error: invalid scalar style');
  344. }
  345. }());
  346. }
  347. // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
  348. function blockHeader(string, indentPerLevel) {
  349. var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
  350. // note the special case: the string '\n' counts as a "trailing" empty line.
  351. var clip = string[string.length - 1] === '\n';
  352. var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
  353. var chomp = keep ? '+' : (clip ? '' : '-');
  354. return indentIndicator + chomp + '\n';
  355. }
  356. // (See the note for writeScalar.)
  357. function dropEndingNewline(string) {
  358. return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
  359. }
  360. // Note: a long line without a suitable break point will exceed the width limit.
  361. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
  362. function foldString(string, width) {
  363. // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
  364. // unless they're before or after a more-indented line, or at the very
  365. // beginning or end, in which case $k$ maps to $k$.
  366. // Therefore, parse each chunk as newline(s) followed by a content line.
  367. var lineRe = /(\n+)([^\n]*)/g;
  368. // first line (possibly an empty line)
  369. var result = (function () {
  370. var nextLF = string.indexOf('\n');
  371. nextLF = nextLF !== -1 ? nextLF : string.length;
  372. lineRe.lastIndex = nextLF;
  373. return foldLine(string.slice(0, nextLF), width);
  374. }());
  375. // If we haven't reached the first content line yet, don't add an extra \n.
  376. var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
  377. var moreIndented;
  378. // rest of the lines
  379. var match;
  380. while ((match = lineRe.exec(string))) {
  381. var prefix = match[1], line = match[2];
  382. moreIndented = (line[0] === ' ');
  383. result += prefix
  384. + (!prevMoreIndented && !moreIndented && line !== ''
  385. ? '\n' : '')
  386. + foldLine(line, width);
  387. prevMoreIndented = moreIndented;
  388. }
  389. return result;
  390. }
  391. // Greedy line breaking.
  392. // Picks the longest line under the limit each time,
  393. // otherwise settles for the shortest line over the limit.
  394. // NB. More-indented lines *cannot* be folded, as that would add an extra \n.
  395. function foldLine(line, width) {
  396. if (line === '' || line[0] === ' ') return line;
  397. // Since a more-indented line adds a \n, breaks can't be followed by a space.
  398. var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
  399. var match;
  400. // start is an inclusive index. end, curr, and next are exclusive.
  401. var start = 0, end, curr = 0, next = 0;
  402. var result = '';
  403. // Invariants: 0 <= start <= length-1.
  404. // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
  405. // Inside the loop:
  406. // A match implies length >= 2, so curr and next are <= length-2.
  407. while ((match = breakRe.exec(line))) {
  408. next = match.index;
  409. // maintain invariant: curr - start <= width
  410. if (next - start > width) {
  411. end = (curr > start) ? curr : next; // derive end <= length-2
  412. result += '\n' + line.slice(start, end);
  413. // skip the space that was output as \n
  414. start = end + 1; // derive start <= length-1
  415. }
  416. curr = next;
  417. }
  418. // By the invariants, start <= length-1, so there is something left over.
  419. // It is either the whole string or a part starting from non-whitespace.
  420. result += '\n';
  421. // Insert a break if the remainder is too long and there is a break available.
  422. if (line.length - start > width && curr > start) {
  423. result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
  424. } else {
  425. result += line.slice(start);
  426. }
  427. return result.slice(1); // drop extra \n joiner
  428. }
  429. // Escapes a double-quoted string.
  430. function escapeString(string) {
  431. var result = '';
  432. var char, nextChar;
  433. var escapeSeq;
  434. for (var i = 0; i < string.length; i++) {
  435. char = string.charCodeAt(i);
  436. // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
  437. if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
  438. nextChar = string.charCodeAt(i + 1);
  439. if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
  440. // Combine the surrogate pair and store it escaped.
  441. result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
  442. // Advance index one extra since we already used that char here.
  443. i++; continue;
  444. }
  445. }
  446. escapeSeq = ESCAPE_SEQUENCES[char];
  447. result += !escapeSeq && isPrintable(char)
  448. ? string[i]
  449. : escapeSeq || encodeHex(char);
  450. }
  451. return result;
  452. }
  453. function writeFlowSequence(state, level, object) {
  454. var _result = '',
  455. _tag = state.tag,
  456. index,
  457. length;
  458. for (index = 0, length = object.length; index < length; index += 1) {
  459. // Write only valid elements.
  460. if (writeNode(state, level, object[index], false, false)) {
  461. if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
  462. _result += state.dump;
  463. }
  464. }
  465. state.tag = _tag;
  466. state.dump = '[' + _result + ']';
  467. }
  468. function writeBlockSequence(state, level, object, compact) {
  469. var _result = '',
  470. _tag = state.tag,
  471. index,
  472. length;
  473. for (index = 0, length = object.length; index < length; index += 1) {
  474. // Write only valid elements.
  475. if (writeNode(state, level + 1, object[index], true, true)) {
  476. if (!compact || index !== 0) {
  477. _result += generateNextLine(state, level);
  478. }
  479. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  480. _result += '-';
  481. } else {
  482. _result += '- ';
  483. }
  484. _result += state.dump;
  485. }
  486. }
  487. state.tag = _tag;
  488. state.dump = _result || '[]'; // Empty sequence if no valid values.
  489. }
  490. function writeFlowMapping(state, level, object) {
  491. var _result = '',
  492. _tag = state.tag,
  493. objectKeyList = Object.keys(object),
  494. index,
  495. length,
  496. objectKey,
  497. objectValue,
  498. pairBuffer;
  499. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  500. pairBuffer = '';
  501. if (index !== 0) pairBuffer += ', ';
  502. if (state.condenseFlow) pairBuffer += '"';
  503. objectKey = objectKeyList[index];
  504. objectValue = object[objectKey];
  505. if (!writeNode(state, level, objectKey, false, false)) {
  506. continue; // Skip this pair because of invalid key;
  507. }
  508. if (state.dump.length > 1024) pairBuffer += '? ';
  509. pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
  510. if (!writeNode(state, level, objectValue, false, false)) {
  511. continue; // Skip this pair because of invalid value.
  512. }
  513. pairBuffer += state.dump;
  514. // Both key and value are valid.
  515. _result += pairBuffer;
  516. }
  517. state.tag = _tag;
  518. state.dump = '{' + _result + '}';
  519. }
  520. function writeBlockMapping(state, level, object, compact) {
  521. var _result = '',
  522. _tag = state.tag,
  523. objectKeyList = Object.keys(object),
  524. index,
  525. length,
  526. objectKey,
  527. objectValue,
  528. explicitPair,
  529. pairBuffer;
  530. // Allow sorting keys so that the output file is deterministic
  531. if (state.sortKeys === true) {
  532. // Default sorting
  533. objectKeyList.sort();
  534. } else if (typeof state.sortKeys === 'function') {
  535. // Custom sort function
  536. objectKeyList.sort(state.sortKeys);
  537. } else if (state.sortKeys) {
  538. // Something is wrong
  539. throw new YAMLException('sortKeys must be a boolean or a function');
  540. }
  541. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  542. pairBuffer = '';
  543. if (!compact || index !== 0) {
  544. pairBuffer += generateNextLine(state, level);
  545. }
  546. objectKey = objectKeyList[index];
  547. objectValue = object[objectKey];
  548. if (!writeNode(state, level + 1, objectKey, true, true, true)) {
  549. continue; // Skip this pair because of invalid key.
  550. }
  551. explicitPair = (state.tag !== null && state.tag !== '?') ||
  552. (state.dump && state.dump.length > 1024);
  553. if (explicitPair) {
  554. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  555. pairBuffer += '?';
  556. } else {
  557. pairBuffer += '? ';
  558. }
  559. }
  560. pairBuffer += state.dump;
  561. if (explicitPair) {
  562. pairBuffer += generateNextLine(state, level);
  563. }
  564. if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
  565. continue; // Skip this pair because of invalid value.
  566. }
  567. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  568. pairBuffer += ':';
  569. } else {
  570. pairBuffer += ': ';
  571. }
  572. pairBuffer += state.dump;
  573. // Both key and value are valid.
  574. _result += pairBuffer;
  575. }
  576. state.tag = _tag;
  577. state.dump = _result || '{}'; // Empty mapping if no valid pairs.
  578. }
  579. function detectType(state, object, explicit) {
  580. var _result, typeList, index, length, type, style;
  581. typeList = explicit ? state.explicitTypes : state.implicitTypes;
  582. for (index = 0, length = typeList.length; index < length; index += 1) {
  583. type = typeList[index];
  584. if ((type.instanceOf || type.predicate) &&
  585. (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
  586. (!type.predicate || type.predicate(object))) {
  587. state.tag = explicit ? type.tag : '?';
  588. if (type.represent) {
  589. style = state.styleMap[type.tag] || type.defaultStyle;
  590. if (_toString.call(type.represent) === '[object Function]') {
  591. _result = type.represent(object, style);
  592. } else if (_hasOwnProperty.call(type.represent, style)) {
  593. _result = type.represent[style](object, style);
  594. } else {
  595. throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
  596. }
  597. state.dump = _result;
  598. }
  599. return true;
  600. }
  601. }
  602. return false;
  603. }
  604. // Serializes `object` and writes it to global `result`.
  605. // Returns true on success, or false on invalid object.
  606. //
  607. function writeNode(state, level, object, block, compact, iskey) {
  608. state.tag = null;
  609. state.dump = object;
  610. if (!detectType(state, object, false)) {
  611. detectType(state, object, true);
  612. }
  613. var type = _toString.call(state.dump);
  614. if (block) {
  615. block = (state.flowLevel < 0 || state.flowLevel > level);
  616. }
  617. var objectOrArray = type === '[object Object]' || type === '[object Array]',
  618. duplicateIndex,
  619. duplicate;
  620. if (objectOrArray) {
  621. duplicateIndex = state.duplicates.indexOf(object);
  622. duplicate = duplicateIndex !== -1;
  623. }
  624. if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
  625. compact = false;
  626. }
  627. if (duplicate && state.usedDuplicates[duplicateIndex]) {
  628. state.dump = '*ref_' + duplicateIndex;
  629. } else {
  630. if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
  631. state.usedDuplicates[duplicateIndex] = true;
  632. }
  633. if (type === '[object Object]') {
  634. if (block && (Object.keys(state.dump).length !== 0)) {
  635. writeBlockMapping(state, level, state.dump, compact);
  636. if (duplicate) {
  637. state.dump = '&ref_' + duplicateIndex + state.dump;
  638. }
  639. } else {
  640. writeFlowMapping(state, level, state.dump);
  641. if (duplicate) {
  642. state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
  643. }
  644. }
  645. } else if (type === '[object Array]') {
  646. var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;
  647. if (block && (state.dump.length !== 0)) {
  648. writeBlockSequence(state, arrayLevel, state.dump, compact);
  649. if (duplicate) {
  650. state.dump = '&ref_' + duplicateIndex + state.dump;
  651. }
  652. } else {
  653. writeFlowSequence(state, arrayLevel, state.dump);
  654. if (duplicate) {
  655. state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
  656. }
  657. }
  658. } else if (type === '[object String]') {
  659. if (state.tag !== '?') {
  660. writeScalar(state, state.dump, level, iskey);
  661. }
  662. } else {
  663. if (state.skipInvalid) return false;
  664. throw new YAMLException('unacceptable kind of an object to dump ' + type);
  665. }
  666. if (state.tag !== null && state.tag !== '?') {
  667. state.dump = '!<' + state.tag + '> ' + state.dump;
  668. }
  669. }
  670. return true;
  671. }
  672. function getDuplicateReferences(object, state) {
  673. var objects = [],
  674. duplicatesIndexes = [],
  675. index,
  676. length;
  677. inspectNode(object, objects, duplicatesIndexes);
  678. for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
  679. state.duplicates.push(objects[duplicatesIndexes[index]]);
  680. }
  681. state.usedDuplicates = new Array(length);
  682. }
  683. function inspectNode(object, objects, duplicatesIndexes) {
  684. var objectKeyList,
  685. index,
  686. length;
  687. if (object !== null && typeof object === 'object') {
  688. index = objects.indexOf(object);
  689. if (index !== -1) {
  690. if (duplicatesIndexes.indexOf(index) === -1) {
  691. duplicatesIndexes.push(index);
  692. }
  693. } else {
  694. objects.push(object);
  695. if (Array.isArray(object)) {
  696. for (index = 0, length = object.length; index < length; index += 1) {
  697. inspectNode(object[index], objects, duplicatesIndexes);
  698. }
  699. } else {
  700. objectKeyList = Object.keys(object);
  701. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  702. inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
  703. }
  704. }
  705. }
  706. }
  707. }
  708. function dump(input, options) {
  709. options = options || {};
  710. var state = new State(options);
  711. if (!state.noRefs) getDuplicateReferences(input, state);
  712. if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
  713. return '';
  714. }
  715. function safeDump(input, options) {
  716. return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
  717. }
  718. module.exports.dump = dump;
  719. module.exports.safeDump = safeDump;