index.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057
  1. import { d as defaultTagPrefix, _ as _typeof, a as _createClass, b as _classCallCheck, c as _defineProperty, e as _slicedToArray, Y as YAMLSemanticError, T as Type, f as defaultTags, g as YAMLWarning, h as _createForOfIteratorHelper, i as YAMLSyntaxError, C as Char, j as YAMLReferenceError, k as YAMLError } from './errors-2634d01a.js';
  2. import { P as PlainValue, D as Document$1, p as parse$1 } from './parse-d1ba890f.js';
  3. export { p as parseCST } from './parse-d1ba890f.js';
  4. import { b as binaryOptions, a as boolOptions, i as intOptions, n as nullOptions, s as strOptions, N as Node, P as Pair, S as Scalar, c as stringifyString, A as Alias, Y as YAMLSeq, d as YAMLMap, C as Collection, r as resolveScalar, e as createNode, f as isEmptyPath, g as collectionFromPath, t as toJS, h as addComment } from './stringifyNumber-d8af95b1.js';
  5. import { M as Merge, a as MERGE_KEY, S as Schema } from './Schema-ea978338.js';
  6. var defaultOptions = {
  7. anchorPrefix: 'a',
  8. customTags: null,
  9. indent: 2,
  10. indentSeq: true,
  11. keepCstNodes: false,
  12. keepNodeTypes: true,
  13. keepUndefined: false,
  14. mapAsMap: false,
  15. maxAliasCount: 100,
  16. prettyErrors: true,
  17. simpleKeys: false,
  18. version: '1.2'
  19. };
  20. var scalarOptions = {
  21. get binary() {
  22. return binaryOptions;
  23. },
  24. set binary(opt) {
  25. Object.assign(binaryOptions, opt);
  26. },
  27. get bool() {
  28. return boolOptions;
  29. },
  30. set bool(opt) {
  31. Object.assign(boolOptions, opt);
  32. },
  33. get int() {
  34. return intOptions;
  35. },
  36. set int(opt) {
  37. Object.assign(intOptions, opt);
  38. },
  39. get null() {
  40. return nullOptions;
  41. },
  42. set null(opt) {
  43. Object.assign(nullOptions, opt);
  44. },
  45. get str() {
  46. return strOptions;
  47. },
  48. set str(opt) {
  49. Object.assign(strOptions, opt);
  50. }
  51. };
  52. var documentOptions = {
  53. '1.0': {
  54. schema: 'yaml-1.1',
  55. merge: true,
  56. tagPrefixes: [{
  57. handle: '!',
  58. prefix: defaultTagPrefix
  59. }, {
  60. handle: '!!',
  61. prefix: 'tag:private.yaml.org,2002:'
  62. }]
  63. },
  64. '1.1': {
  65. schema: 'yaml-1.1',
  66. merge: true,
  67. tagPrefixes: [{
  68. handle: '!',
  69. prefix: '!'
  70. }, {
  71. handle: '!!',
  72. prefix: defaultTagPrefix
  73. }]
  74. },
  75. '1.2': {
  76. schema: 'core',
  77. merge: false,
  78. resolveKnownTags: true,
  79. tagPrefixes: [{
  80. handle: '!',
  81. prefix: '!'
  82. }, {
  83. handle: '!!',
  84. prefix: defaultTagPrefix
  85. }]
  86. }
  87. };
  88. function stringifyTag(doc, tag) {
  89. if ((doc.version || doc.options.version) === '1.0') {
  90. var priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);
  91. if (priv) return '!' + priv[1];
  92. var vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);
  93. return vocab ? "!".concat(vocab[1], "/").concat(vocab[2]) : "!".concat(tag.replace(/^tag:/, ''));
  94. }
  95. var p = doc.tagPrefixes.find(function (p) {
  96. return tag.indexOf(p.prefix) === 0;
  97. });
  98. if (!p) {
  99. var dtp = doc.getDefaults().tagPrefixes;
  100. p = dtp && dtp.find(function (p) {
  101. return tag.indexOf(p.prefix) === 0;
  102. });
  103. }
  104. if (!p) return tag[0] === '!' ? tag : "!<".concat(tag, ">");
  105. var suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, function (ch) {
  106. return {
  107. '!': '%21',
  108. ',': '%2C',
  109. '[': '%5B',
  110. ']': '%5D',
  111. '{': '%7B',
  112. '}': '%7D'
  113. }[ch];
  114. });
  115. return p.handle + suffix;
  116. }
  117. function getTagObject(tags, item) {
  118. if (item instanceof Alias) return Alias;
  119. if (item.tag) {
  120. var match = tags.filter(function (t) {
  121. return t.tag === item.tag;
  122. });
  123. if (match.length > 0) return match.find(function (t) {
  124. return t.format === item.format;
  125. }) || match[0];
  126. }
  127. var tagObj, obj;
  128. if (item instanceof Scalar) {
  129. obj = item.value;
  130. var _match = tags.filter(function (t) {
  131. return t.identify && t.identify(obj);
  132. });
  133. tagObj = _match.find(function (t) {
  134. return t.format === item.format;
  135. }) || _match.find(function (t) {
  136. return !t.format;
  137. });
  138. } else {
  139. obj = item;
  140. tagObj = tags.find(function (t) {
  141. return t.nodeClass && obj instanceof t.nodeClass;
  142. });
  143. }
  144. if (!tagObj) {
  145. var name = obj && obj.constructor ? obj.constructor.name : _typeof(obj);
  146. throw new Error("Tag not resolved for ".concat(name, " value"));
  147. }
  148. return tagObj;
  149. } // needs to be called before value stringifier to allow for circular anchor refs
  150. function stringifyProps(node, tagObj, _ref) {
  151. var anchors = _ref.anchors,
  152. doc = _ref.doc;
  153. var props = [];
  154. var anchor = doc.anchors.getName(node);
  155. if (anchor) {
  156. anchors[anchor] = node;
  157. props.push("&".concat(anchor));
  158. }
  159. if (node.tag) {
  160. props.push(stringifyTag(doc, node.tag));
  161. } else if (!tagObj.default) {
  162. props.push(stringifyTag(doc, tagObj.tag));
  163. }
  164. return props.join(' ');
  165. }
  166. function stringify(item, ctx, onComment, onChompKeep) {
  167. var schema = ctx.doc.schema;
  168. var tagObj;
  169. if (!(item instanceof Node)) {
  170. item = ctx.doc.createNode(item, {
  171. onTagObj: function onTagObj(o) {
  172. return tagObj = o;
  173. },
  174. wrapScalars: true
  175. });
  176. }
  177. if (item instanceof Pair) return item.toString(ctx, onComment, onChompKeep);
  178. if (!tagObj) tagObj = getTagObject(schema.tags, item);
  179. var props = stringifyProps(item, tagObj, ctx);
  180. if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1;
  181. var str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof Scalar ? stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep);
  182. if (!props) return str;
  183. return item instanceof Scalar || str[0] === '{' || str[0] === '[' ? "".concat(props, " ").concat(str) : "".concat(props, "\n").concat(ctx.indent).concat(str);
  184. }
  185. var Anchors = /*#__PURE__*/function () {
  186. _createClass(Anchors, null, [{
  187. key: "validAnchorNode",
  188. value: function validAnchorNode(node) {
  189. return node instanceof Scalar || node instanceof YAMLSeq || node instanceof YAMLMap;
  190. }
  191. }]);
  192. function Anchors(prefix) {
  193. _classCallCheck(this, Anchors);
  194. _defineProperty(this, "map", Object.create(null));
  195. this.prefix = prefix;
  196. }
  197. _createClass(Anchors, [{
  198. key: "createAlias",
  199. value: function createAlias(node, name) {
  200. this.setAnchor(node, name);
  201. return new Alias(node);
  202. }
  203. }, {
  204. key: "createMergePair",
  205. value: function createMergePair() {
  206. var _this = this;
  207. var merge = new Merge();
  208. for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) {
  209. sources[_key] = arguments[_key];
  210. }
  211. merge.value.items = sources.map(function (s) {
  212. if (s instanceof Alias) {
  213. if (s.source instanceof YAMLMap) return s;
  214. } else if (s instanceof YAMLMap) {
  215. return _this.createAlias(s);
  216. }
  217. throw new Error('Merge sources must be Map nodes or their Aliases');
  218. });
  219. return merge;
  220. }
  221. }, {
  222. key: "getName",
  223. value: function getName(node) {
  224. var map = this.map;
  225. return Object.keys(map).find(function (a) {
  226. return map[a] === node;
  227. });
  228. }
  229. }, {
  230. key: "getNames",
  231. value: function getNames() {
  232. return Object.keys(this.map);
  233. }
  234. }, {
  235. key: "getNode",
  236. value: function getNode(name) {
  237. return this.map[name];
  238. }
  239. }, {
  240. key: "newName",
  241. value: function newName(prefix) {
  242. if (!prefix) prefix = this.prefix;
  243. var names = Object.keys(this.map);
  244. for (var i = 1; true; ++i) {
  245. var name = "".concat(prefix).concat(i);
  246. if (!names.includes(name)) return name;
  247. }
  248. } // During parsing, map & aliases contain CST nodes
  249. }, {
  250. key: "resolveNodes",
  251. value: function resolveNodes() {
  252. var map = this.map,
  253. _cstAliases = this._cstAliases;
  254. Object.keys(map).forEach(function (a) {
  255. map[a] = map[a].resolved;
  256. });
  257. _cstAliases.forEach(function (a) {
  258. a.source = a.source.resolved;
  259. });
  260. delete this._cstAliases;
  261. }
  262. }, {
  263. key: "setAnchor",
  264. value: function setAnchor(node, name) {
  265. if (node != null && !Anchors.validAnchorNode(node)) {
  266. throw new Error('Anchors may only be set for Scalar, Seq and Map nodes');
  267. }
  268. if (name && /[\x00-\x19\s,[\]{}]/.test(name)) {
  269. throw new Error('Anchor names must not contain whitespace or control characters');
  270. }
  271. var map = this.map;
  272. var prev = node && Object.keys(map).find(function (a) {
  273. return map[a] === node;
  274. });
  275. if (prev) {
  276. if (!name) {
  277. return prev;
  278. } else if (prev !== name) {
  279. delete map[prev];
  280. map[name] = node;
  281. }
  282. } else {
  283. if (!name) {
  284. if (!node) return null;
  285. name = this.newName();
  286. }
  287. map[name] = node;
  288. }
  289. return name;
  290. }
  291. }]);
  292. return Anchors;
  293. }();
  294. /**
  295. * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
  296. * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the
  297. * 2021 edition: https://tc39.es/ecma262/#sec-json.parse
  298. *
  299. * Includes extensions for handling Map and Set objects.
  300. */
  301. function applyReviver(reviver, obj, key, val) {
  302. if (val && _typeof(val) === 'object') {
  303. if (Array.isArray(val)) {
  304. for (var i = 0, len = val.length; i < len; ++i) {
  305. var v0 = val[i];
  306. var v1 = applyReviver(reviver, val, String(i), v0);
  307. if (v1 === undefined) delete val[i];else if (v1 !== v0) val[i] = v1;
  308. }
  309. } else if (val instanceof Map) {
  310. for (var _i = 0, _Array$from = Array.from(val.keys()); _i < _Array$from.length; _i++) {
  311. var k = _Array$from[_i];
  312. var _v = val.get(k);
  313. var _v2 = applyReviver(reviver, val, k, _v);
  314. if (_v2 === undefined) val.delete(k);else if (_v2 !== _v) val.set(k, _v2);
  315. }
  316. } else if (val instanceof Set) {
  317. for (var _i2 = 0, _Array$from2 = Array.from(val); _i2 < _Array$from2.length; _i2++) {
  318. var _v3 = _Array$from2[_i2];
  319. var _v4 = applyReviver(reviver, val, _v3, _v3);
  320. if (_v4 === undefined) val.delete(_v3);else if (_v4 !== _v3) {
  321. val.delete(_v3);
  322. val.add(_v4);
  323. }
  324. }
  325. } else {
  326. for (var _i3 = 0, _Object$entries = Object.entries(val); _i3 < _Object$entries.length; _i3++) {
  327. var _Object$entries$_i = _slicedToArray(_Object$entries[_i3], 2),
  328. _k = _Object$entries$_i[0],
  329. _v5 = _Object$entries$_i[1];
  330. var _v6 = applyReviver(reviver, val, _k, _v5);
  331. if (_v6 === undefined) delete val[_k];else if (_v6 !== _v5) val[_k] = _v6;
  332. }
  333. }
  334. }
  335. return reviver.call(obj, key, val);
  336. }
  337. var visit = function visit(node, tags) {
  338. if (node && _typeof(node) === 'object') {
  339. var tag = node.tag;
  340. if (node instanceof Collection) {
  341. if (tag) tags[tag] = true;
  342. node.items.forEach(function (n) {
  343. return visit(n, tags);
  344. });
  345. } else if (node instanceof Pair) {
  346. visit(node.key, tags);
  347. visit(node.value, tags);
  348. } else if (node instanceof Scalar) {
  349. if (tag) tags[tag] = true;
  350. }
  351. }
  352. return tags;
  353. };
  354. var listTagNames = function listTagNames(node) {
  355. return Object.keys(visit(node, {}));
  356. };
  357. function resolveTagHandle(doc, node) {
  358. var _node$tag = node.tag,
  359. handle = _node$tag.handle,
  360. suffix = _node$tag.suffix;
  361. var prefix = doc.tagPrefixes.find(function (p) {
  362. return p.handle === handle;
  363. });
  364. if (!prefix) {
  365. var dtp = doc.getDefaults().tagPrefixes;
  366. if (dtp) prefix = dtp.find(function (p) {
  367. return p.handle === handle;
  368. });
  369. if (!prefix) throw new YAMLSemanticError(node, "The ".concat(handle, " tag handle is non-default and was not declared."));
  370. }
  371. if (!suffix) throw new YAMLSemanticError(node, "The ".concat(handle, " tag has no suffix."));
  372. if (handle === '!' && (doc.version || doc.options.version) === '1.0') {
  373. if (suffix[0] === '^') {
  374. doc.warnings.push(new YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported'));
  375. return suffix;
  376. }
  377. if (/[:/]/.test(suffix)) {
  378. // word/foo -> tag:word.yaml.org,2002:foo
  379. var vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i);
  380. return vocab ? "tag:".concat(vocab[1], ".yaml.org,2002:").concat(vocab[2]) : "tag:".concat(suffix);
  381. }
  382. }
  383. return prefix.prefix + decodeURIComponent(suffix);
  384. }
  385. function resolveTagName(doc, node) {
  386. var tag = node.tag,
  387. type = node.type;
  388. var nonSpecific = false;
  389. if (tag) {
  390. var handle = tag.handle,
  391. suffix = tag.suffix,
  392. verbatim = tag.verbatim;
  393. if (verbatim) {
  394. if (verbatim !== '!' && verbatim !== '!!') return verbatim;
  395. var msg = "Verbatim tags aren't resolved, so ".concat(verbatim, " is invalid.");
  396. doc.errors.push(new YAMLSemanticError(node, msg));
  397. } else if (handle === '!' && !suffix) {
  398. nonSpecific = true;
  399. } else {
  400. try {
  401. return resolveTagHandle(doc, node);
  402. } catch (error) {
  403. doc.errors.push(error);
  404. }
  405. }
  406. }
  407. switch (type) {
  408. case Type.BLOCK_FOLDED:
  409. case Type.BLOCK_LITERAL:
  410. case Type.QUOTE_DOUBLE:
  411. case Type.QUOTE_SINGLE:
  412. return defaultTags.STR;
  413. case Type.FLOW_MAP:
  414. case Type.MAP:
  415. return defaultTags.MAP;
  416. case Type.FLOW_SEQ:
  417. case Type.SEQ:
  418. return defaultTags.SEQ;
  419. case Type.PLAIN:
  420. return nonSpecific ? defaultTags.STR : null;
  421. default:
  422. return null;
  423. }
  424. }
  425. function checkFlowCollectionEnd(errors, cst) {
  426. var char, name;
  427. switch (cst.type) {
  428. case Type.FLOW_MAP:
  429. char = '}';
  430. name = 'flow map';
  431. break;
  432. case Type.FLOW_SEQ:
  433. char = ']';
  434. name = 'flow sequence';
  435. break;
  436. default:
  437. errors.push(new YAMLSemanticError(cst, 'Not a flow collection!?'));
  438. return;
  439. }
  440. var lastItem;
  441. for (var i = cst.items.length - 1; i >= 0; --i) {
  442. var item = cst.items[i];
  443. if (!item || item.type !== Type.COMMENT) {
  444. lastItem = item;
  445. break;
  446. }
  447. }
  448. if (lastItem && lastItem.char !== char) {
  449. var msg = "Expected ".concat(name, " to end with ").concat(char);
  450. var err;
  451. if (typeof lastItem.offset === 'number') {
  452. err = new YAMLSemanticError(cst, msg);
  453. err.offset = lastItem.offset + 1;
  454. } else {
  455. err = new YAMLSemanticError(lastItem, msg);
  456. if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start;
  457. }
  458. errors.push(err);
  459. }
  460. }
  461. function checkFlowCommentSpace(errors, comment) {
  462. var prev = comment.context.src[comment.range.start - 1];
  463. if (prev !== '\n' && prev !== '\t' && prev !== ' ') {
  464. var msg = 'Comments must be separated from other tokens by white space characters';
  465. errors.push(new YAMLSemanticError(comment, msg));
  466. }
  467. }
  468. function getLongKeyError(source, key) {
  469. var sk = String(key);
  470. var k = sk.substr(0, 8) + '...' + sk.substr(-8);
  471. return new YAMLSemanticError(source, "The \"".concat(k, "\" key is too long"));
  472. }
  473. function resolveComments(collection, comments) {
  474. var _iterator = _createForOfIteratorHelper(comments),
  475. _step;
  476. try {
  477. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  478. var _step$value = _step.value,
  479. afterKey = _step$value.afterKey,
  480. before = _step$value.before,
  481. comment = _step$value.comment;
  482. var item = collection.items[before];
  483. if (!item) {
  484. if (comment !== undefined) {
  485. if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment;
  486. }
  487. } else {
  488. if (afterKey && item.value) item = item.value;
  489. if (comment === undefined) {
  490. if (afterKey || !item.commentBefore) item.spaceBefore = true;
  491. } else {
  492. if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment;
  493. }
  494. }
  495. }
  496. } catch (err) {
  497. _iterator.e(err);
  498. } finally {
  499. _iterator.f();
  500. }
  501. }
  502. function resolveMap(doc, cst) {
  503. var _ref = cst.type === Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst),
  504. comments = _ref.comments,
  505. items = _ref.items;
  506. var map = new YAMLMap(doc.schema);
  507. map.items = items;
  508. resolveComments(map, comments);
  509. var hasCollectionKey = false;
  510. for (var i = 0; i < items.length; ++i) {
  511. var iKey = items[i].key;
  512. if (iKey instanceof Collection) hasCollectionKey = true;
  513. if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) {
  514. items[i] = new Merge(items[i]);
  515. var sources = items[i].value.items;
  516. var error = null;
  517. sources.some(function (node) {
  518. if (node instanceof Alias) {
  519. // During parsing, alias sources are CST nodes; to account for
  520. // circular references their resolved values can't be used here.
  521. var type = node.source.type;
  522. if (type === Type.MAP || type === Type.FLOW_MAP) return false;
  523. return error = 'Merge nodes aliases can only point to maps';
  524. }
  525. return error = 'Merge nodes can only have Alias nodes as values';
  526. });
  527. if (error) doc.errors.push(new YAMLSemanticError(cst, error));
  528. } else {
  529. for (var j = i + 1; j < items.length; ++j) {
  530. var jKey = items[j].key;
  531. if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) {
  532. var msg = "Map keys must be unique; \"".concat(iKey, "\" is repeated");
  533. doc.errors.push(new YAMLSemanticError(cst, msg));
  534. break;
  535. }
  536. }
  537. }
  538. }
  539. if (hasCollectionKey && !doc.options.mapAsMap) {
  540. var warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
  541. doc.warnings.push(new YAMLWarning(cst, warn));
  542. }
  543. cst.resolved = map;
  544. return map;
  545. }
  546. var valueHasPairComment = function valueHasPairComment(_ref2) {
  547. var _ref2$context = _ref2.context,
  548. lineStart = _ref2$context.lineStart,
  549. node = _ref2$context.node,
  550. src = _ref2$context.src,
  551. props = _ref2.props;
  552. if (props.length === 0) return false;
  553. var start = props[0].start;
  554. if (node && start > node.valueRange.start) return false;
  555. if (src[start] !== Char.COMMENT) return false;
  556. for (var i = lineStart; i < start; ++i) {
  557. if (src[i] === '\n') return false;
  558. }
  559. return true;
  560. };
  561. function resolvePairComment(item, pair) {
  562. if (!valueHasPairComment(item)) return;
  563. var comment = item.getPropValue(0, Char.COMMENT, true);
  564. var found = false;
  565. var cb = pair.value.commentBefore;
  566. if (cb && cb.startsWith(comment)) {
  567. pair.value.commentBefore = cb.substr(comment.length + 1);
  568. found = true;
  569. } else {
  570. var cc = pair.value.comment;
  571. if (!item.node && cc && cc.startsWith(comment)) {
  572. pair.value.comment = cc.substr(comment.length + 1);
  573. found = true;
  574. }
  575. }
  576. if (found) pair.comment = comment;
  577. }
  578. function resolveBlockMapItems(doc, cst) {
  579. var comments = [];
  580. var items = [];
  581. var key = undefined;
  582. var keyStart = null;
  583. for (var i = 0; i < cst.items.length; ++i) {
  584. var item = cst.items[i];
  585. switch (item.type) {
  586. case Type.BLANK_LINE:
  587. comments.push({
  588. afterKey: !!key,
  589. before: items.length
  590. });
  591. break;
  592. case Type.COMMENT:
  593. comments.push({
  594. afterKey: !!key,
  595. before: items.length,
  596. comment: item.comment
  597. });
  598. break;
  599. case Type.MAP_KEY:
  600. if (key !== undefined) items.push(new Pair(key));
  601. if (item.error) doc.errors.push(item.error);
  602. key = resolveNode(doc, item.node);
  603. keyStart = null;
  604. break;
  605. case Type.MAP_VALUE:
  606. {
  607. if (key === undefined) key = null;
  608. if (item.error) doc.errors.push(item.error);
  609. if (!item.context.atLineStart && item.node && item.node.type === Type.MAP && !item.node.context.atLineStart) {
  610. var msg = 'Nested mappings are not allowed in compact mappings';
  611. doc.errors.push(new YAMLSemanticError(item.node, msg));
  612. }
  613. var valueNode = item.node;
  614. if (!valueNode && item.props.length > 0) {
  615. // Comments on an empty mapping value need to be preserved, so we
  616. // need to construct a minimal empty node here to use instead of the
  617. // missing `item.node`. -- eemeli/yaml#19
  618. valueNode = new PlainValue(Type.PLAIN, []);
  619. valueNode.context = {
  620. parent: item,
  621. src: item.context.src
  622. };
  623. var pos = item.range.start + 1;
  624. valueNode.range = {
  625. start: pos,
  626. end: pos
  627. };
  628. valueNode.valueRange = {
  629. start: pos,
  630. end: pos
  631. };
  632. if (typeof item.range.origStart === 'number') {
  633. var origPos = item.range.origStart + 1;
  634. valueNode.range.origStart = valueNode.range.origEnd = origPos;
  635. valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos;
  636. }
  637. }
  638. var pair = new Pair(key, resolveNode(doc, valueNode));
  639. resolvePairComment(item, pair);
  640. items.push(pair);
  641. if (key && typeof keyStart === 'number') {
  642. if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
  643. }
  644. key = undefined;
  645. keyStart = null;
  646. }
  647. break;
  648. default:
  649. if (key !== undefined) items.push(new Pair(key));
  650. key = resolveNode(doc, item);
  651. keyStart = item.range.start;
  652. if (item.error) doc.errors.push(item.error);
  653. next: for (var j = i + 1;; ++j) {
  654. var nextItem = cst.items[j];
  655. switch (nextItem && nextItem.type) {
  656. case Type.BLANK_LINE:
  657. case Type.COMMENT:
  658. continue next;
  659. case Type.MAP_VALUE:
  660. break next;
  661. default:
  662. {
  663. var _msg = 'Implicit map keys need to be followed by map values';
  664. doc.errors.push(new YAMLSemanticError(item, _msg));
  665. break next;
  666. }
  667. }
  668. }
  669. if (item.valueRangeContainsNewline) {
  670. var _msg2 = 'Implicit map keys need to be on a single line';
  671. doc.errors.push(new YAMLSemanticError(item, _msg2));
  672. }
  673. }
  674. }
  675. if (key !== undefined) items.push(new Pair(key));
  676. return {
  677. comments: comments,
  678. items: items
  679. };
  680. }
  681. function resolveFlowMapItems(doc, cst) {
  682. var comments = [];
  683. var items = [];
  684. var key = undefined;
  685. var explicitKey = false;
  686. var next = '{';
  687. for (var i = 0; i < cst.items.length; ++i) {
  688. var item = cst.items[i];
  689. if (typeof item.char === 'string') {
  690. var char = item.char,
  691. offset = item.offset;
  692. if (char === '?' && key === undefined && !explicitKey) {
  693. explicitKey = true;
  694. next = ':';
  695. continue;
  696. }
  697. if (char === ':') {
  698. if (key === undefined) key = null;
  699. if (next === ':') {
  700. next = ',';
  701. continue;
  702. }
  703. } else {
  704. if (explicitKey) {
  705. if (key === undefined && char !== ',') key = null;
  706. explicitKey = false;
  707. }
  708. if (key !== undefined) {
  709. items.push(new Pair(key));
  710. key = undefined;
  711. if (char === ',') {
  712. next = ':';
  713. continue;
  714. }
  715. }
  716. }
  717. if (char === '}') {
  718. if (i === cst.items.length - 1) continue;
  719. } else if (char === next) {
  720. next = ':';
  721. continue;
  722. }
  723. var msg = "Flow map contains an unexpected ".concat(char);
  724. var err = new YAMLSyntaxError(cst, msg);
  725. err.offset = offset;
  726. doc.errors.push(err);
  727. } else if (item.type === Type.BLANK_LINE) {
  728. comments.push({
  729. afterKey: !!key,
  730. before: items.length
  731. });
  732. } else if (item.type === Type.COMMENT) {
  733. checkFlowCommentSpace(doc.errors, item);
  734. comments.push({
  735. afterKey: !!key,
  736. before: items.length,
  737. comment: item.comment
  738. });
  739. } else if (key === undefined) {
  740. if (next === ',') doc.errors.push(new YAMLSemanticError(item, 'Separator , missing in flow map'));
  741. key = resolveNode(doc, item);
  742. } else {
  743. if (next !== ',') doc.errors.push(new YAMLSemanticError(item, 'Indicator : missing in flow map entry'));
  744. items.push(new Pair(key, resolveNode(doc, item)));
  745. key = undefined;
  746. explicitKey = false;
  747. }
  748. }
  749. checkFlowCollectionEnd(doc.errors, cst);
  750. if (key !== undefined) items.push(new Pair(key));
  751. return {
  752. comments: comments,
  753. items: items
  754. };
  755. }
  756. function resolveSeq(doc, cst) {
  757. var _ref = cst.type === Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst),
  758. comments = _ref.comments,
  759. items = _ref.items;
  760. var seq = new YAMLSeq(doc.schema);
  761. seq.items = items;
  762. resolveComments(seq, comments);
  763. if (!doc.options.mapAsMap && items.some(function (it) {
  764. return it instanceof Pair && it.key instanceof Collection;
  765. })) {
  766. var warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
  767. doc.warnings.push(new YAMLWarning(cst, warn));
  768. }
  769. cst.resolved = seq;
  770. return seq;
  771. }
  772. function resolveBlockSeqItems(doc, cst) {
  773. var comments = [];
  774. var items = [];
  775. for (var i = 0; i < cst.items.length; ++i) {
  776. var item = cst.items[i];
  777. switch (item.type) {
  778. case Type.BLANK_LINE:
  779. comments.push({
  780. before: items.length
  781. });
  782. break;
  783. case Type.COMMENT:
  784. comments.push({
  785. comment: item.comment,
  786. before: items.length
  787. });
  788. break;
  789. case Type.SEQ_ITEM:
  790. if (item.error) doc.errors.push(item.error);
  791. items.push(resolveNode(doc, item.node));
  792. if (item.hasProps) {
  793. var msg = 'Sequence items cannot have tags or anchors before the - indicator';
  794. doc.errors.push(new YAMLSemanticError(item, msg));
  795. }
  796. break;
  797. default:
  798. if (item.error) doc.errors.push(item.error);
  799. doc.errors.push(new YAMLSyntaxError(item, "Unexpected ".concat(item.type, " node in sequence")));
  800. }
  801. }
  802. return {
  803. comments: comments,
  804. items: items
  805. };
  806. }
  807. function resolveFlowSeqItems(doc, cst) {
  808. var comments = [];
  809. var items = [];
  810. var explicitKey = false;
  811. var key = undefined;
  812. var keyStart = null;
  813. var next = '[';
  814. var prevItem = null;
  815. for (var i = 0; i < cst.items.length; ++i) {
  816. var item = cst.items[i];
  817. if (typeof item.char === 'string') {
  818. var char = item.char,
  819. offset = item.offset;
  820. if (char !== ':' && (explicitKey || key !== undefined)) {
  821. if (explicitKey && key === undefined) key = next ? items.pop() : null;
  822. items.push(new Pair(key));
  823. explicitKey = false;
  824. key = undefined;
  825. keyStart = null;
  826. }
  827. if (char === next) {
  828. next = null;
  829. } else if (!next && char === '?') {
  830. explicitKey = true;
  831. } else if (next !== '[' && char === ':' && key === undefined) {
  832. if (next === ',') {
  833. key = items.pop();
  834. if (key instanceof Pair) {
  835. var msg = 'Chaining flow sequence pairs is invalid';
  836. var err = new YAMLSemanticError(cst, msg);
  837. err.offset = offset;
  838. doc.errors.push(err);
  839. }
  840. if (!explicitKey && typeof keyStart === 'number') {
  841. var keyEnd = item.range ? item.range.start : item.offset;
  842. if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
  843. var src = prevItem.context.src;
  844. for (var _i = keyStart; _i < keyEnd; ++_i) {
  845. if (src[_i] === '\n') {
  846. var _msg = 'Implicit keys of flow sequence pairs need to be on a single line';
  847. doc.errors.push(new YAMLSemanticError(prevItem, _msg));
  848. break;
  849. }
  850. }
  851. }
  852. } else {
  853. key = null;
  854. }
  855. keyStart = null;
  856. explicitKey = false;
  857. next = null;
  858. } else if (next === '[' || char !== ']' || i < cst.items.length - 1) {
  859. var _msg2 = "Flow sequence contains an unexpected ".concat(char);
  860. var _err = new YAMLSyntaxError(cst, _msg2);
  861. _err.offset = offset;
  862. doc.errors.push(_err);
  863. }
  864. } else if (item.type === Type.BLANK_LINE) {
  865. comments.push({
  866. before: items.length
  867. });
  868. } else if (item.type === Type.COMMENT) {
  869. checkFlowCommentSpace(doc.errors, item);
  870. comments.push({
  871. comment: item.comment,
  872. before: items.length
  873. });
  874. } else {
  875. if (next) {
  876. var _msg3 = "Expected a ".concat(next, " in flow sequence");
  877. doc.errors.push(new YAMLSemanticError(item, _msg3));
  878. }
  879. var value = resolveNode(doc, item);
  880. if (key === undefined) {
  881. items.push(value);
  882. prevItem = item;
  883. } else {
  884. items.push(new Pair(key, value));
  885. key = undefined;
  886. }
  887. keyStart = item.range.start;
  888. next = ',';
  889. }
  890. }
  891. checkFlowCollectionEnd(doc.errors, cst);
  892. if (key !== undefined) items.push(new Pair(key));
  893. return {
  894. comments: comments,
  895. items: items
  896. };
  897. }
  898. function resolveByTagName(_ref, tagName, value, onError) {
  899. var knownTags = _ref.knownTags,
  900. tags = _ref.tags;
  901. var matchWithTest = [];
  902. var _iterator = _createForOfIteratorHelper(tags),
  903. _step;
  904. try {
  905. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  906. var tag = _step.value;
  907. if (tag.tag === tagName) {
  908. if (tag.test) {
  909. if (typeof value === 'string') matchWithTest.push(tag);else onError("The tag ".concat(tagName, " cannot be applied to a collection"));
  910. } else {
  911. var _res = tag.resolve(value, onError);
  912. return _res instanceof Collection ? _res : new Scalar(_res);
  913. }
  914. }
  915. }
  916. } catch (err) {
  917. _iterator.e(err);
  918. } finally {
  919. _iterator.f();
  920. }
  921. if (matchWithTest.length > 0) return resolveScalar(value, matchWithTest);
  922. var kt = knownTags[tagName];
  923. if (kt) {
  924. tags.push(Object.assign({}, kt, {
  925. default: false,
  926. test: undefined
  927. }));
  928. var res = kt.resolve(value, onError);
  929. return res instanceof Collection ? res : new Scalar(res);
  930. }
  931. return null;
  932. }
  933. function resolveTag(doc, node, tagName) {
  934. var MAP = defaultTags.MAP,
  935. SEQ = defaultTags.SEQ,
  936. STR = defaultTags.STR;
  937. var value, fallback;
  938. var onError = function onError(message) {
  939. return doc.errors.push(new YAMLSemanticError(node, message));
  940. };
  941. try {
  942. switch (node.type) {
  943. case Type.FLOW_MAP:
  944. case Type.MAP:
  945. value = resolveMap(doc, node);
  946. fallback = MAP;
  947. if (tagName === SEQ || tagName === STR) onError("The tag ".concat(tagName, " cannot be applied to a mapping"));
  948. break;
  949. case Type.FLOW_SEQ:
  950. case Type.SEQ:
  951. value = resolveSeq(doc, node);
  952. fallback = SEQ;
  953. if (tagName === MAP || tagName === STR) onError("The tag ".concat(tagName, " cannot be applied to a sequence"));
  954. break;
  955. default:
  956. value = node.strValue || '';
  957. if (typeof value !== 'string') {
  958. value.errors.forEach(function (error) {
  959. return doc.errors.push(error);
  960. });
  961. value = value.str;
  962. }
  963. if (tagName === MAP || tagName === SEQ) onError("The tag ".concat(tagName, " cannot be applied to a scalar"));
  964. fallback = STR;
  965. }
  966. var res = resolveByTagName(doc.schema, tagName, value, onError);
  967. if (res) {
  968. if (tagName && node.tag) res.tag = tagName;
  969. return res;
  970. }
  971. } catch (error) {
  972. /* istanbul ignore if */
  973. if (!error.source) error.source = node;
  974. doc.errors.push(error);
  975. return null;
  976. }
  977. try {
  978. if (!fallback) throw new Error("The tag ".concat(tagName, " is unavailable"));
  979. var msg = "The tag ".concat(tagName, " is unavailable, falling back to ").concat(fallback);
  980. doc.warnings.push(new YAMLWarning(node, msg));
  981. var _res2 = resolveByTagName(doc.schema, fallback, value, onError);
  982. _res2.tag = tagName;
  983. return _res2;
  984. } catch (error) {
  985. var refError = new YAMLReferenceError(node, error.message);
  986. refError.stack = error.stack;
  987. doc.errors.push(refError);
  988. return null;
  989. }
  990. }
  991. var isCollectionItem = function isCollectionItem(node) {
  992. if (!node) return false;
  993. var type = node.type;
  994. return type === Type.MAP_KEY || type === Type.MAP_VALUE || type === Type.SEQ_ITEM;
  995. };
  996. function resolveNodeProps(errors, node) {
  997. var comments = {
  998. before: [],
  999. after: []
  1000. };
  1001. var hasAnchor = false;
  1002. var hasTag = false;
  1003. var props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props;
  1004. var _iterator = _createForOfIteratorHelper(props),
  1005. _step;
  1006. try {
  1007. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  1008. var _step$value = _step.value,
  1009. start = _step$value.start,
  1010. end = _step$value.end;
  1011. switch (node.context.src[start]) {
  1012. case Char.COMMENT:
  1013. {
  1014. if (!node.commentHasRequiredWhitespace(start)) {
  1015. var msg = 'Comments must be separated from other tokens by white space characters';
  1016. errors.push(new YAMLSemanticError(node, msg));
  1017. }
  1018. var header = node.header,
  1019. valueRange = node.valueRange;
  1020. var cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before;
  1021. cc.push(node.context.src.slice(start + 1, end));
  1022. break;
  1023. }
  1024. // Actual anchor & tag resolution is handled by schema, here we just complain
  1025. case Char.ANCHOR:
  1026. if (hasAnchor) {
  1027. var _msg = 'A node can have at most one anchor';
  1028. errors.push(new YAMLSemanticError(node, _msg));
  1029. }
  1030. hasAnchor = true;
  1031. break;
  1032. case Char.TAG:
  1033. if (hasTag) {
  1034. var _msg2 = 'A node can have at most one tag';
  1035. errors.push(new YAMLSemanticError(node, _msg2));
  1036. }
  1037. hasTag = true;
  1038. break;
  1039. }
  1040. }
  1041. } catch (err) {
  1042. _iterator.e(err);
  1043. } finally {
  1044. _iterator.f();
  1045. }
  1046. return {
  1047. comments: comments,
  1048. hasAnchor: hasAnchor,
  1049. hasTag: hasTag
  1050. };
  1051. }
  1052. function resolveNodeValue(doc, node) {
  1053. var anchors = doc.anchors,
  1054. errors = doc.errors,
  1055. schema = doc.schema;
  1056. if (node.type === Type.ALIAS) {
  1057. var name = node.rawValue;
  1058. var src = anchors.getNode(name);
  1059. if (!src) {
  1060. var msg = "Aliased anchor not found: ".concat(name);
  1061. errors.push(new YAMLReferenceError(node, msg));
  1062. return null;
  1063. } // Lazy resolution for circular references
  1064. var res = new Alias(src);
  1065. anchors._cstAliases.push(res);
  1066. return res;
  1067. }
  1068. var tagName = resolveTagName(doc, node);
  1069. if (tagName) return resolveTag(doc, node, tagName);
  1070. if (node.type !== Type.PLAIN) {
  1071. var _msg3 = "Failed to resolve ".concat(node.type, " node here");
  1072. errors.push(new YAMLSyntaxError(node, _msg3));
  1073. return null;
  1074. }
  1075. try {
  1076. var str = node.strValue || '';
  1077. if (typeof str !== 'string') {
  1078. str.errors.forEach(function (error) {
  1079. return doc.errors.push(error);
  1080. });
  1081. str = str.str;
  1082. }
  1083. return resolveScalar(str, schema.tags);
  1084. } catch (error) {
  1085. if (!error.source) error.source = node;
  1086. errors.push(error);
  1087. return null;
  1088. }
  1089. } // sets node.resolved on success
  1090. function resolveNode(doc, node) {
  1091. if (!node) return null;
  1092. if (node.error) doc.errors.push(node.error);
  1093. var _resolveNodeProps = resolveNodeProps(doc.errors, node),
  1094. comments = _resolveNodeProps.comments,
  1095. hasAnchor = _resolveNodeProps.hasAnchor,
  1096. hasTag = _resolveNodeProps.hasTag;
  1097. if (hasAnchor) {
  1098. var anchors = doc.anchors;
  1099. var name = node.anchor;
  1100. var prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor
  1101. // name have already been resolved, so it may safely be renamed.
  1102. if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as
  1103. // anchors need to be available during resolution to allow for
  1104. // circular references.
  1105. anchors.map[name] = node;
  1106. }
  1107. if (node.type === Type.ALIAS && (hasAnchor || hasTag)) {
  1108. var msg = 'An alias node must not specify any properties';
  1109. doc.errors.push(new YAMLSemanticError(node, msg));
  1110. }
  1111. var res = resolveNodeValue(doc, node);
  1112. if (res) {
  1113. res.range = [node.range.start, node.range.end];
  1114. if (doc.options.keepCstNodes) res.cstNode = node;
  1115. if (doc.options.keepNodeTypes) res.type = node.type;
  1116. var cb = comments.before.join('\n');
  1117. if (cb) {
  1118. res.commentBefore = res.commentBefore ? "".concat(res.commentBefore, "\n").concat(cb) : cb;
  1119. }
  1120. var ca = comments.after.join('\n');
  1121. if (ca) res.comment = res.comment ? "".concat(res.comment, "\n").concat(ca) : ca;
  1122. }
  1123. return node.resolved = res;
  1124. }
  1125. function parseContents(doc, contents) {
  1126. var comments = {
  1127. before: [],
  1128. after: []
  1129. };
  1130. var body = undefined;
  1131. var spaceBefore = false;
  1132. var _iterator = _createForOfIteratorHelper(contents),
  1133. _step;
  1134. try {
  1135. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  1136. var node = _step.value;
  1137. if (node.valueRange) {
  1138. if (body !== undefined) {
  1139. var msg = 'Document contains trailing content not separated by a ... or --- line';
  1140. doc.errors.push(new YAMLSyntaxError(node, msg));
  1141. break;
  1142. }
  1143. var res = resolveNode(doc, node);
  1144. if (spaceBefore) {
  1145. res.spaceBefore = true;
  1146. spaceBefore = false;
  1147. }
  1148. body = res;
  1149. } else if (node.comment !== null) {
  1150. var cc = body === undefined ? comments.before : comments.after;
  1151. cc.push(node.comment);
  1152. } else if (node.type === Type.BLANK_LINE) {
  1153. spaceBefore = true;
  1154. if (body === undefined && comments.before.length > 0 && !doc.commentBefore) {
  1155. // space-separated comments at start are parsed as document comments
  1156. doc.commentBefore = comments.before.join('\n');
  1157. comments.before = [];
  1158. }
  1159. }
  1160. }
  1161. } catch (err) {
  1162. _iterator.e(err);
  1163. } finally {
  1164. _iterator.f();
  1165. }
  1166. doc.contents = body || null;
  1167. if (!body) {
  1168. doc.comment = comments.before.concat(comments.after).join('\n') || null;
  1169. } else {
  1170. var cb = comments.before.join('\n');
  1171. if (cb) {
  1172. var cbNode = body instanceof Collection && body.items[0] ? body.items[0] : body;
  1173. cbNode.commentBefore = cbNode.commentBefore ? "".concat(cb, "\n").concat(cbNode.commentBefore) : cb;
  1174. }
  1175. doc.comment = comments.after.join('\n') || null;
  1176. }
  1177. }
  1178. function resolveTagDirective(_ref, directive) {
  1179. var tagPrefixes = _ref.tagPrefixes;
  1180. var _directive$parameters = _slicedToArray(directive.parameters, 2),
  1181. handle = _directive$parameters[0],
  1182. prefix = _directive$parameters[1];
  1183. if (!handle || !prefix) {
  1184. var msg = 'Insufficient parameters given for %TAG directive';
  1185. throw new YAMLSemanticError(directive, msg);
  1186. }
  1187. if (tagPrefixes.some(function (p) {
  1188. return p.handle === handle;
  1189. })) {
  1190. var _msg = 'The %TAG directive must only be given at most once per handle in the same document.';
  1191. throw new YAMLSemanticError(directive, _msg);
  1192. }
  1193. return {
  1194. handle: handle,
  1195. prefix: prefix
  1196. };
  1197. }
  1198. function resolveYamlDirective(doc, directive) {
  1199. var _directive$parameters2 = _slicedToArray(directive.parameters, 1),
  1200. version = _directive$parameters2[0];
  1201. if (directive.name === 'YAML:1.0') version = '1.0';
  1202. if (!version) {
  1203. var msg = 'Insufficient parameters given for %YAML directive';
  1204. throw new YAMLSemanticError(directive, msg);
  1205. }
  1206. if (!documentOptions[version]) {
  1207. var v0 = doc.version || doc.options.version;
  1208. var _msg2 = "Document will be parsed as YAML ".concat(v0, " rather than YAML ").concat(version);
  1209. doc.warnings.push(new YAMLWarning(directive, _msg2));
  1210. }
  1211. return version;
  1212. }
  1213. function parseDirectives(doc, directives, prevDoc) {
  1214. var directiveComments = [];
  1215. var hasDirectives = false;
  1216. var _iterator = _createForOfIteratorHelper(directives),
  1217. _step;
  1218. try {
  1219. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  1220. var directive = _step.value;
  1221. var comment = directive.comment,
  1222. name = directive.name;
  1223. switch (name) {
  1224. case 'TAG':
  1225. try {
  1226. doc.tagPrefixes.push(resolveTagDirective(doc, directive));
  1227. } catch (error) {
  1228. doc.errors.push(error);
  1229. }
  1230. hasDirectives = true;
  1231. break;
  1232. case 'YAML':
  1233. case 'YAML:1.0':
  1234. if (doc.version) {
  1235. var msg = 'The %YAML directive must only be given at most once per document.';
  1236. doc.errors.push(new YAMLSemanticError(directive, msg));
  1237. }
  1238. try {
  1239. doc.version = resolveYamlDirective(doc, directive);
  1240. } catch (error) {
  1241. doc.errors.push(error);
  1242. }
  1243. hasDirectives = true;
  1244. break;
  1245. default:
  1246. if (name) {
  1247. var _msg3 = "YAML only supports %TAG and %YAML directives, and not %".concat(name);
  1248. doc.warnings.push(new YAMLWarning(directive, _msg3));
  1249. }
  1250. }
  1251. if (comment) directiveComments.push(comment);
  1252. }
  1253. } catch (err) {
  1254. _iterator.e(err);
  1255. } finally {
  1256. _iterator.f();
  1257. }
  1258. if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) {
  1259. var copyTagPrefix = function copyTagPrefix(_ref2) {
  1260. var handle = _ref2.handle,
  1261. prefix = _ref2.prefix;
  1262. return {
  1263. handle: handle,
  1264. prefix: prefix
  1265. };
  1266. };
  1267. doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix);
  1268. doc.version = prevDoc.version;
  1269. }
  1270. doc.commentBefore = directiveComments.join('\n') || null;
  1271. }
  1272. function assertCollection(contents) {
  1273. if (contents instanceof Collection) return true;
  1274. throw new Error('Expected a YAML collection as document contents');
  1275. }
  1276. var Document = /*#__PURE__*/function () {
  1277. function Document(value, replacer, options) {
  1278. _classCallCheck(this, Document);
  1279. if (options === undefined && replacer && _typeof(replacer) === 'object' && !Array.isArray(replacer)) {
  1280. options = replacer;
  1281. replacer = undefined;
  1282. }
  1283. this.options = Object.assign({}, defaultOptions, options);
  1284. this.anchors = new Anchors(this.options.anchorPrefix);
  1285. this.commentBefore = null;
  1286. this.comment = null;
  1287. this.directivesEndMarker = null;
  1288. this.errors = [];
  1289. this.schema = null;
  1290. this.tagPrefixes = [];
  1291. this.version = null;
  1292. this.warnings = [];
  1293. if (value === undefined) {
  1294. // note that this.schema is left as null here
  1295. this.contents = null;
  1296. } else if (value instanceof Document$1) {
  1297. this.parse(value);
  1298. } else {
  1299. this.contents = this.createNode(value, {
  1300. replacer: replacer
  1301. });
  1302. }
  1303. }
  1304. _createClass(Document, [{
  1305. key: "add",
  1306. value: function add(value) {
  1307. assertCollection(this.contents);
  1308. return this.contents.add(value);
  1309. }
  1310. }, {
  1311. key: "addIn",
  1312. value: function addIn(path, value) {
  1313. assertCollection(this.contents);
  1314. this.contents.addIn(path, value);
  1315. }
  1316. }, {
  1317. key: "createNode",
  1318. value: function createNode$1(value) {
  1319. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  1320. keepUndefined = _ref.keepUndefined,
  1321. onTagObj = _ref.onTagObj,
  1322. replacer = _ref.replacer,
  1323. tag = _ref.tag,
  1324. wrapScalars = _ref.wrapScalars;
  1325. this.setSchema();
  1326. if (typeof replacer === 'function') value = replacer.call({
  1327. '': value
  1328. }, '', value);else if (Array.isArray(replacer)) {
  1329. var keyToStr = function keyToStr(v) {
  1330. return typeof v === 'number' || v instanceof String || v instanceof Number;
  1331. };
  1332. var asStr = replacer.filter(keyToStr).map(String);
  1333. if (asStr.length > 0) replacer = replacer.concat(asStr);
  1334. }
  1335. if (typeof keepUndefined !== 'boolean') keepUndefined = !!this.options.keepUndefined;
  1336. var aliasNodes = [];
  1337. var ctx = {
  1338. keepUndefined: keepUndefined,
  1339. onAlias: function onAlias(source) {
  1340. var alias = new Alias(source);
  1341. aliasNodes.push(alias);
  1342. return alias;
  1343. },
  1344. onTagObj: onTagObj,
  1345. prevObjects: new Map(),
  1346. replacer: replacer,
  1347. schema: this.schema,
  1348. wrapScalars: wrapScalars !== false
  1349. };
  1350. var node = createNode(value, tag, ctx);
  1351. for (var _i = 0, _aliasNodes = aliasNodes; _i < _aliasNodes.length; _i++) {
  1352. var alias = _aliasNodes[_i];
  1353. // With circular references, the source node is only resolved after all of
  1354. // its child nodes are. This is why anchors are set only after all of the
  1355. // nodes have been created.
  1356. alias.source = alias.source.node;
  1357. var name = this.anchors.getName(alias.source);
  1358. if (!name) {
  1359. name = this.anchors.newName();
  1360. this.anchors.map[name] = alias.source;
  1361. }
  1362. }
  1363. return node;
  1364. }
  1365. }, {
  1366. key: "createPair",
  1367. value: function createPair(key, value) {
  1368. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1369. var k = this.createNode(key, options);
  1370. var v = this.createNode(value, options);
  1371. return new Pair(k, v);
  1372. }
  1373. }, {
  1374. key: "delete",
  1375. value: function _delete(key) {
  1376. assertCollection(this.contents);
  1377. return this.contents.delete(key);
  1378. }
  1379. }, {
  1380. key: "deleteIn",
  1381. value: function deleteIn(path) {
  1382. if (isEmptyPath(path)) {
  1383. if (this.contents == null) return false;
  1384. this.contents = null;
  1385. return true;
  1386. }
  1387. assertCollection(this.contents);
  1388. return this.contents.deleteIn(path);
  1389. }
  1390. }, {
  1391. key: "getDefaults",
  1392. value: function getDefaults() {
  1393. return Document.defaults[this.version] || Document.defaults[this.options.version] || {};
  1394. }
  1395. }, {
  1396. key: "get",
  1397. value: function get(key, keepScalar) {
  1398. return this.contents instanceof Collection ? this.contents.get(key, keepScalar) : undefined;
  1399. }
  1400. }, {
  1401. key: "getIn",
  1402. value: function getIn(path, keepScalar) {
  1403. if (isEmptyPath(path)) return !keepScalar && this.contents instanceof Scalar ? this.contents.value : this.contents;
  1404. return this.contents instanceof Collection ? this.contents.getIn(path, keepScalar) : undefined;
  1405. }
  1406. }, {
  1407. key: "has",
  1408. value: function has(key) {
  1409. return this.contents instanceof Collection ? this.contents.has(key) : false;
  1410. }
  1411. }, {
  1412. key: "hasIn",
  1413. value: function hasIn(path) {
  1414. if (isEmptyPath(path)) return this.contents !== undefined;
  1415. return this.contents instanceof Collection ? this.contents.hasIn(path) : false;
  1416. }
  1417. }, {
  1418. key: "set",
  1419. value: function set(key, value) {
  1420. if (this.contents == null) {
  1421. this.setSchema();
  1422. this.contents = collectionFromPath(this.schema, [key], value);
  1423. } else {
  1424. assertCollection(this.contents);
  1425. this.contents.set(key, value);
  1426. }
  1427. }
  1428. }, {
  1429. key: "setIn",
  1430. value: function setIn(path, value) {
  1431. if (isEmptyPath(path)) this.contents = value;else if (this.contents == null) {
  1432. this.setSchema();
  1433. this.contents = collectionFromPath(this.schema, path, value);
  1434. } else {
  1435. assertCollection(this.contents);
  1436. this.contents.setIn(path, value);
  1437. }
  1438. }
  1439. }, {
  1440. key: "setSchema",
  1441. value: function setSchema(id, customTags) {
  1442. if (!id && !customTags && this.schema) return;
  1443. if (typeof id === 'number') id = id.toFixed(1);
  1444. if (id === '1.0' || id === '1.1' || id === '1.2') {
  1445. if (this.version) this.version = id;else this.options.version = id;
  1446. delete this.options.schema;
  1447. } else if (id && typeof id === 'string') {
  1448. this.options.schema = id;
  1449. }
  1450. if (Array.isArray(customTags)) this.options.customTags = customTags;
  1451. var opt = Object.assign({}, this.getDefaults(), this.options);
  1452. this.schema = new Schema(opt);
  1453. }
  1454. }, {
  1455. key: "parse",
  1456. value: function parse(node, prevDoc) {
  1457. if (this.options.keepCstNodes) this.cstNode = node;
  1458. if (this.options.keepNodeTypes) this.type = 'DOCUMENT';
  1459. var _node$directives = node.directives,
  1460. directives = _node$directives === void 0 ? [] : _node$directives,
  1461. _node$contents = node.contents,
  1462. contents = _node$contents === void 0 ? [] : _node$contents,
  1463. directivesEndMarker = node.directivesEndMarker,
  1464. error = node.error,
  1465. valueRange = node.valueRange;
  1466. if (error) {
  1467. if (!error.source) error.source = this;
  1468. this.errors.push(error);
  1469. }
  1470. parseDirectives(this, directives, prevDoc);
  1471. if (directivesEndMarker) this.directivesEndMarker = true;
  1472. this.range = valueRange ? [valueRange.start, valueRange.end] : null;
  1473. this.setSchema();
  1474. this.anchors._cstAliases = [];
  1475. parseContents(this, contents);
  1476. this.anchors.resolveNodes();
  1477. if (this.options.prettyErrors) {
  1478. var _iterator = _createForOfIteratorHelper(this.errors),
  1479. _step;
  1480. try {
  1481. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  1482. var _error = _step.value;
  1483. if (_error instanceof YAMLError) _error.makePretty();
  1484. }
  1485. } catch (err) {
  1486. _iterator.e(err);
  1487. } finally {
  1488. _iterator.f();
  1489. }
  1490. var _iterator2 = _createForOfIteratorHelper(this.warnings),
  1491. _step2;
  1492. try {
  1493. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  1494. var warn = _step2.value;
  1495. if (warn instanceof YAMLError) warn.makePretty();
  1496. }
  1497. } catch (err) {
  1498. _iterator2.e(err);
  1499. } finally {
  1500. _iterator2.f();
  1501. }
  1502. }
  1503. return this;
  1504. }
  1505. }, {
  1506. key: "listNonDefaultTags",
  1507. value: function listNonDefaultTags() {
  1508. return listTagNames(this.contents).filter(function (t) {
  1509. return t.indexOf(defaultTagPrefix) !== 0;
  1510. });
  1511. }
  1512. }, {
  1513. key: "setTagPrefix",
  1514. value: function setTagPrefix(handle, prefix) {
  1515. if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !');
  1516. if (prefix) {
  1517. var prev = this.tagPrefixes.find(function (p) {
  1518. return p.handle === handle;
  1519. });
  1520. if (prev) prev.prefix = prefix;else this.tagPrefixes.push({
  1521. handle: handle,
  1522. prefix: prefix
  1523. });
  1524. } else {
  1525. this.tagPrefixes = this.tagPrefixes.filter(function (p) {
  1526. return p.handle !== handle;
  1527. });
  1528. }
  1529. }
  1530. }, {
  1531. key: "toJS",
  1532. value: function toJS$1() {
  1533. var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  1534. json = _ref2.json,
  1535. jsonArg = _ref2.jsonArg,
  1536. mapAsMap = _ref2.mapAsMap,
  1537. onAnchor = _ref2.onAnchor,
  1538. reviver = _ref2.reviver;
  1539. var anchorNodes = Object.values(this.anchors.map).map(function (node) {
  1540. return [node, {
  1541. alias: [],
  1542. aliasCount: 0,
  1543. count: 1
  1544. }];
  1545. });
  1546. var anchors = anchorNodes.length > 0 ? new Map(anchorNodes) : null;
  1547. var ctx = {
  1548. anchors: anchors,
  1549. doc: this,
  1550. indentStep: ' ',
  1551. keep: !json,
  1552. mapAsMap: typeof mapAsMap === 'boolean' ? mapAsMap : !!this.options.mapAsMap,
  1553. maxAliasCount: this.options.maxAliasCount,
  1554. stringify: stringify // Requiring directly in Pair would create circular dependencies
  1555. };
  1556. var res = toJS(this.contents, jsonArg || '', ctx);
  1557. if (typeof onAnchor === 'function' && anchors) {
  1558. var _iterator3 = _createForOfIteratorHelper(anchors.values()),
  1559. _step3;
  1560. try {
  1561. for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
  1562. var _step3$value = _step3.value,
  1563. count = _step3$value.count,
  1564. _res = _step3$value.res;
  1565. onAnchor(_res, count);
  1566. }
  1567. } catch (err) {
  1568. _iterator3.e(err);
  1569. } finally {
  1570. _iterator3.f();
  1571. }
  1572. }
  1573. return typeof reviver === 'function' ? applyReviver(reviver, {
  1574. '': res
  1575. }, '', res) : res;
  1576. }
  1577. }, {
  1578. key: "toJSON",
  1579. value: function toJSON(jsonArg, onAnchor) {
  1580. return this.toJS({
  1581. json: true,
  1582. jsonArg: jsonArg,
  1583. mapAsMap: false,
  1584. onAnchor: onAnchor
  1585. });
  1586. }
  1587. }, {
  1588. key: "toString",
  1589. value: function toString() {
  1590. if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified');
  1591. var indentSize = this.options.indent;
  1592. if (!Number.isInteger(indentSize) || indentSize <= 0) {
  1593. var s = JSON.stringify(indentSize);
  1594. throw new Error("\"indent\" option must be a positive integer, not ".concat(s));
  1595. }
  1596. this.setSchema();
  1597. var lines = [];
  1598. var hasDirectives = false;
  1599. if (this.version) {
  1600. var vd = '%YAML 1.2';
  1601. if (this.schema.name === 'yaml-1.1') {
  1602. if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1';
  1603. }
  1604. lines.push(vd);
  1605. hasDirectives = true;
  1606. }
  1607. var tagNames = this.listNonDefaultTags();
  1608. this.tagPrefixes.forEach(function (_ref3) {
  1609. var handle = _ref3.handle,
  1610. prefix = _ref3.prefix;
  1611. if (tagNames.some(function (t) {
  1612. return t.indexOf(prefix) === 0;
  1613. })) {
  1614. lines.push("%TAG ".concat(handle, " ").concat(prefix));
  1615. hasDirectives = true;
  1616. }
  1617. });
  1618. if (hasDirectives || this.directivesEndMarker) lines.push('---');
  1619. if (this.commentBefore) {
  1620. if (hasDirectives || !this.directivesEndMarker) lines.unshift('');
  1621. lines.unshift(this.commentBefore.replace(/^/gm, '#'));
  1622. }
  1623. var ctx = {
  1624. anchors: Object.create(null),
  1625. doc: this,
  1626. indent: '',
  1627. indentStep: ' '.repeat(indentSize),
  1628. stringify: stringify // Requiring directly in nodes would create circular dependencies
  1629. };
  1630. var chompKeep = false;
  1631. var contentComment = null;
  1632. if (this.contents) {
  1633. if (this.contents instanceof Node) {
  1634. if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push('');
  1635. if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment
  1636. ctx.forceBlockIndent = !!this.comment;
  1637. contentComment = this.contents.comment;
  1638. }
  1639. var onChompKeep = contentComment ? null : function () {
  1640. return chompKeep = true;
  1641. };
  1642. var body = stringify(this.contents, ctx, function () {
  1643. return contentComment = null;
  1644. }, onChompKeep);
  1645. lines.push(addComment(body, '', contentComment));
  1646. } else {
  1647. lines.push(stringify(this.contents, ctx));
  1648. }
  1649. if (this.comment) {
  1650. if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push('');
  1651. lines.push(this.comment.replace(/^/gm, '#'));
  1652. }
  1653. return lines.join('\n') + '\n';
  1654. }
  1655. }]);
  1656. return Document;
  1657. }();
  1658. _defineProperty(Document, "defaults", documentOptions);
  1659. /* global console, process, YAML_SILENCE_WARNINGS */
  1660. function warn(warning, type) {
  1661. if (typeof YAML_SILENCE_WARNINGS !== 'undefined' && YAML_SILENCE_WARNINGS) return;
  1662. if (typeof process !== 'undefined') {
  1663. if (process.env.YAML_SILENCE_WARNINGS) return; // This will throw in Jest if `warning` is an Error instance due to
  1664. // https://github.com/facebook/jest/issues/2549
  1665. if (process.emitWarning) {
  1666. process.emitWarning(warning, type);
  1667. return;
  1668. }
  1669. } // eslint-disable-next-line no-console
  1670. console.warn(type ? "".concat(type, ": ").concat(warning) : warning);
  1671. }
  1672. function parseAllDocuments(src, options) {
  1673. var stream = [];
  1674. var prev;
  1675. var _iterator = _createForOfIteratorHelper(parse$1(src)),
  1676. _step;
  1677. try {
  1678. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  1679. var cstDoc = _step.value;
  1680. var doc = new Document(undefined, null, options);
  1681. doc.parse(cstDoc, prev);
  1682. stream.push(doc);
  1683. prev = doc;
  1684. }
  1685. } catch (err) {
  1686. _iterator.e(err);
  1687. } finally {
  1688. _iterator.f();
  1689. }
  1690. return stream;
  1691. }
  1692. function parseDocument(src, options) {
  1693. var cst = parse$1(src);
  1694. var doc = new Document(cst[0], null, options);
  1695. if (cst.length > 1) {
  1696. var errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()';
  1697. doc.errors.unshift(new YAMLSemanticError(cst[1], errMsg));
  1698. }
  1699. return doc;
  1700. }
  1701. function parse(src, reviver, options) {
  1702. if (options === undefined && reviver && _typeof(reviver) === 'object') {
  1703. options = reviver;
  1704. reviver = undefined;
  1705. }
  1706. var doc = parseDocument(src, options);
  1707. doc.warnings.forEach(function (warning) {
  1708. return warn(warning);
  1709. });
  1710. if (doc.errors.length > 0) throw doc.errors[0];
  1711. return doc.toJS({
  1712. reviver: reviver
  1713. });
  1714. }
  1715. function stringify$1(value, replacer, options) {
  1716. if (typeof options === 'string') options = options.length;
  1717. if (typeof options === 'number') {
  1718. var indent = Math.round(options);
  1719. options = indent < 1 ? undefined : indent > 8 ? {
  1720. indent: 8
  1721. } : {
  1722. indent: indent
  1723. };
  1724. }
  1725. if (value === undefined) {
  1726. var _ref = options || replacer || {},
  1727. keepUndefined = _ref.keepUndefined;
  1728. if (!keepUndefined) return undefined;
  1729. }
  1730. return new Document(value, replacer, options).toString();
  1731. }
  1732. export { Document, defaultOptions, parse, parseAllDocuments, parseDocument, scalarOptions, stringify$1 as stringify };