dumper.js 25 KB

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