Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / prettier / third-party.js
1 'use strict';
2
3 var os = require('os');
4 var path = require('path');
5 var Module = require('module');
6 var fs = require('fs');
7 var util = require('util');
8
9 function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
11 var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
12 var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
13 var Module__default = /*#__PURE__*/_interopDefaultLegacy(Module);
14 var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
15 var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
16
17 function createCommonjsModule(fn, basedir, module) {
18         return module = {
19                 path: basedir,
20                 exports: {},
21                 require: function (path, base) {
22                         return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
23                 }
24         }, fn(module, module.exports), module.exports;
25 }
26
27 function commonjsRequire () {
28         throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
29 }
30
31 const resolveFrom = (fromDir, moduleId, silent) => {
32   if (typeof fromDir !== 'string') {
33     throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDir}\``);
34   }
35
36   if (typeof moduleId !== 'string') {
37     throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
38   }
39
40   try {
41     fromDir = fs__default['default'].realpathSync(fromDir);
42   } catch (err) {
43     if (err.code === 'ENOENT') {
44       fromDir = path__default['default'].resolve(fromDir);
45     } else if (silent) {
46       return null;
47     } else {
48       throw err;
49     }
50   }
51
52   const fromFile = path__default['default'].join(fromDir, 'noop.js');
53
54   const resolveFileName = () => Module__default['default']._resolveFilename(moduleId, {
55     id: fromFile,
56     filename: fromFile,
57     paths: Module__default['default']._nodeModulePaths(fromDir)
58   });
59
60   if (silent) {
61     try {
62       return resolveFileName();
63     } catch (err) {
64       return null;
65     }
66   }
67
68   return resolveFileName();
69 };
70
71 var resolveFrom_1 = (fromDir, moduleId) => resolveFrom(fromDir, moduleId);
72
73 var silent = (fromDir, moduleId) => resolveFrom(fromDir, moduleId, true);
74 resolveFrom_1.silent = silent;
75
76 var importFresh = moduleId => {
77   if (typeof moduleId !== 'string') {
78     throw new TypeError('Expected a string');
79   }
80
81   const parentPath = __filename;
82   const filePath = resolveFrom_1(path__default['default'].dirname(parentPath), moduleId);
83   const oldModule = eval('require').cache[filePath]; // Delete itself from module parent
84
85   if (oldModule && oldModule.parent) {
86     let i = oldModule.parent.children.length;
87
88     while (i--) {
89       if (oldModule.parent.children[i].id === filePath) {
90         oldModule.parent.children.splice(i, 1);
91       }
92     }
93   }
94
95   delete eval('require').cache[filePath]; // Delete module from cache
96
97   const parent = eval('require').cache[parentPath]; // If `filePath` and `parentPath` are the same, cache will already be deleted so we won't get a memory leak in next step
98
99   return parent === undefined ? eval('require')(filePath) : parent.require(filePath); // In case cache doesn't have parent, fall back to normal require
100 };
101
102 var isArrayish = function isArrayish(obj) {
103   if (!obj) {
104     return false;
105   }
106
107   return obj instanceof Array || Array.isArray(obj) || obj.length >= 0 && obj.splice instanceof Function;
108 };
109
110 var errorEx = function errorEx(name, properties) {
111   if (!name || name.constructor !== String) {
112     properties = name || {};
113     name = Error.name;
114   }
115
116   var errorExError = function ErrorEXError(message) {
117     if (!this) {
118       return new ErrorEXError(message);
119     }
120
121     message = message instanceof Error ? message.message : message || this.message;
122     Error.call(this, message);
123     Error.captureStackTrace(this, errorExError);
124     this.name = name;
125     Object.defineProperty(this, 'message', {
126       configurable: true,
127       enumerable: false,
128       get: function () {
129         var newMessage = message.split(/\r?\n/g);
130
131         for (var key in properties) {
132           if (!properties.hasOwnProperty(key)) {
133             continue;
134           }
135
136           var modifier = properties[key];
137
138           if ('message' in modifier) {
139             newMessage = modifier.message(this[key], newMessage) || newMessage;
140
141             if (!isArrayish(newMessage)) {
142               newMessage = [newMessage];
143             }
144           }
145         }
146
147         return newMessage.join('\n');
148       },
149       set: function (v) {
150         message = v;
151       }
152     });
153     var overwrittenStack = null;
154     var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack');
155     var stackGetter = stackDescriptor.get;
156     var stackValue = stackDescriptor.value;
157     delete stackDescriptor.value;
158     delete stackDescriptor.writable;
159
160     stackDescriptor.set = function (newstack) {
161       overwrittenStack = newstack;
162     };
163
164     stackDescriptor.get = function () {
165       var stack = (overwrittenStack || (stackGetter ? stackGetter.call(this) : stackValue)).split(/\r?\n+/g); // starting in Node 7, the stack builder caches the message.
166       // just replace it.
167
168       if (!overwrittenStack) {
169         stack[0] = this.name + ': ' + this.message;
170       }
171
172       var lineCount = 1;
173
174       for (var key in properties) {
175         if (!properties.hasOwnProperty(key)) {
176           continue;
177         }
178
179         var modifier = properties[key];
180
181         if ('line' in modifier) {
182           var line = modifier.line(this[key]);
183
184           if (line) {
185             stack.splice(lineCount++, 0, '    ' + line);
186           }
187         }
188
189         if ('stack' in modifier) {
190           modifier.stack(this[key], stack);
191         }
192       }
193
194       return stack.join('\n');
195     };
196
197     Object.defineProperty(this, 'stack', stackDescriptor);
198   };
199
200   if (Object.setPrototypeOf) {
201     Object.setPrototypeOf(errorExError.prototype, Error.prototype);
202     Object.setPrototypeOf(errorExError, Error);
203   } else {
204     util__default['default'].inherits(errorExError, Error);
205   }
206
207   return errorExError;
208 };
209
210 errorEx.append = function (str, def) {
211   return {
212     message: function (v, message) {
213       v = v || def;
214
215       if (v) {
216         message[0] += ' ' + str.replace('%s', v.toString());
217       }
218
219       return message;
220     }
221   };
222 };
223
224 errorEx.line = function (str, def) {
225   return {
226     line: function (v) {
227       v = v || def;
228
229       if (v) {
230         return str.replace('%s', v.toString());
231       }
232
233       return null;
234     }
235   };
236 };
237
238 var errorEx_1 = errorEx;
239
240 var jsonParseBetterErrors = parseJson;
241
242 function parseJson(txt, reviver, context) {
243   context = context || 20;
244
245   try {
246     return JSON.parse(txt, reviver);
247   } catch (e) {
248     if (typeof txt !== 'string') {
249       const isEmptyArray = Array.isArray(txt) && txt.length === 0;
250       const errorMessage = 'Cannot parse ' + (isEmptyArray ? 'an empty array' : String(txt));
251       throw new TypeError(errorMessage);
252     }
253
254     const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i);
255     const errIdx = syntaxErr ? +syntaxErr[1] : e.message.match(/^Unexpected end of JSON.*/i) ? txt.length - 1 : null;
256
257     if (errIdx != null) {
258       const start = errIdx <= context ? 0 : errIdx - context;
259       const end = errIdx + context >= txt.length ? txt.length : errIdx + context;
260       e.message += ` while parsing near '${start === 0 ? '' : '...'}${txt.slice(start, end)}${end === txt.length ? '' : '...'}'`;
261     } else {
262       e.message += ` while parsing '${txt.slice(0, context * 2)}'`;
263     }
264
265     throw e;
266   }
267 }
268
269 var dist = createCommonjsModule(function (module, exports) {
270
271   var LF = '\n';
272   var CR = '\r';
273
274   var LinesAndColumns = function () {
275     function LinesAndColumns(string) {
276       this.string = string;
277       var offsets = [0];
278
279       for (var offset = 0; offset < string.length;) {
280         switch (string[offset]) {
281           case LF:
282             offset += LF.length;
283             offsets.push(offset);
284             break;
285
286           case CR:
287             offset += CR.length;
288
289             if (string[offset] === LF) {
290               offset += LF.length;
291             }
292
293             offsets.push(offset);
294             break;
295
296           default:
297             offset++;
298             break;
299         }
300       }
301
302       this.offsets = offsets;
303     }
304
305     LinesAndColumns.prototype.locationForIndex = function (index) {
306       if (index < 0 || index > this.string.length) {
307         return null;
308       }
309
310       var line = 0;
311       var offsets = this.offsets;
312
313       while (offsets[line + 1] <= index) {
314         line++;
315       }
316
317       var column = index - offsets[line];
318       return {
319         line: line,
320         column: column
321       };
322     };
323
324     LinesAndColumns.prototype.indexForLocation = function (location) {
325       var line = location.line,
326           column = location.column;
327
328       if (line < 0 || line >= this.offsets.length) {
329         return null;
330       }
331
332       if (column < 0 || column > this.lengthOfLine(line)) {
333         return null;
334       }
335
336       return this.offsets[line] + column;
337     };
338
339     LinesAndColumns.prototype.lengthOfLine = function (line) {
340       var offset = this.offsets[line];
341       var nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1];
342       return nextOffset - offset;
343     };
344
345     return LinesAndColumns;
346   }();
347
348   exports.__esModule = true;
349   exports["default"] = LinesAndColumns;
350 });
351
352 var jsTokens = createCommonjsModule(function (module, exports) {
353   // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
354   // License: MIT. (See LICENSE.)
355   Object.defineProperty(exports, "__esModule", {
356     value: true
357   }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
358   // (run `npm run build`).
359
360   exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g;
361
362   exports.matchToToken = function (match) {
363     var token = {
364       type: "invalid",
365       value: match[0],
366       closed: undefined
367     };
368     if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace";
369     return token;
370   };
371 });
372
373 var identifier = createCommonjsModule(function (module, exports) {
374
375   Object.defineProperty(exports, "__esModule", {
376     value: true
377   });
378   exports.isIdentifierStart = isIdentifierStart;
379   exports.isIdentifierChar = isIdentifierChar;
380   exports.isIdentifierName = isIdentifierName;
381   let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
382   let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
383   const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
384   const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
385   nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
386   const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
387   const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
388
389   function isInAstralSet(code, set) {
390     let pos = 0x10000;
391
392     for (let i = 0, length = set.length; i < length; i += 2) {
393       pos += set[i];
394       if (pos > code) return false;
395       pos += set[i + 1];
396       if (pos >= code) return true;
397     }
398
399     return false;
400   }
401
402   function isIdentifierStart(code) {
403     if (code < 65) return code === 36;
404     if (code <= 90) return true;
405     if (code < 97) return code === 95;
406     if (code <= 122) return true;
407
408     if (code <= 0xffff) {
409       return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
410     }
411
412     return isInAstralSet(code, astralIdentifierStartCodes);
413   }
414
415   function isIdentifierChar(code) {
416     if (code < 48) return code === 36;
417     if (code < 58) return true;
418     if (code < 65) return false;
419     if (code <= 90) return true;
420     if (code < 97) return code === 95;
421     if (code <= 122) return true;
422
423     if (code <= 0xffff) {
424       return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
425     }
426
427     return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
428   }
429
430   function isIdentifierName(name) {
431     let isFirst = true;
432
433     for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) {
434       const char = _Array$from[_i];
435       const cp = char.codePointAt(0);
436
437       if (isFirst) {
438         if (!isIdentifierStart(cp)) {
439           return false;
440         }
441
442         isFirst = false;
443       } else if (!isIdentifierChar(cp)) {
444         return false;
445       }
446     }
447
448     return !isFirst;
449   }
450 });
451
452 var keyword = createCommonjsModule(function (module, exports) {
453
454   Object.defineProperty(exports, "__esModule", {
455     value: true
456   });
457   exports.isReservedWord = isReservedWord;
458   exports.isStrictReservedWord = isStrictReservedWord;
459   exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
460   exports.isStrictBindReservedWord = isStrictBindReservedWord;
461   exports.isKeyword = isKeyword;
462   const reservedWords = {
463     keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
464     strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
465     strictBind: ["eval", "arguments"]
466   };
467   const keywords = new Set(reservedWords.keyword);
468   const reservedWordsStrictSet = new Set(reservedWords.strict);
469   const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
470
471   function isReservedWord(word, inModule) {
472     return inModule && word === "await" || word === "enum";
473   }
474
475   function isStrictReservedWord(word, inModule) {
476     return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
477   }
478
479   function isStrictBindOnlyReservedWord(word) {
480     return reservedWordsStrictBindSet.has(word);
481   }
482
483   function isStrictBindReservedWord(word, inModule) {
484     return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
485   }
486
487   function isKeyword(word) {
488     return keywords.has(word);
489   }
490 });
491
492 var lib = createCommonjsModule(function (module, exports) {
493
494   Object.defineProperty(exports, "__esModule", {
495     value: true
496   });
497   Object.defineProperty(exports, "isIdentifierName", {
498     enumerable: true,
499     get: function () {
500       return identifier.isIdentifierName;
501     }
502   });
503   Object.defineProperty(exports, "isIdentifierChar", {
504     enumerable: true,
505     get: function () {
506       return identifier.isIdentifierChar;
507     }
508   });
509   Object.defineProperty(exports, "isIdentifierStart", {
510     enumerable: true,
511     get: function () {
512       return identifier.isIdentifierStart;
513     }
514   });
515   Object.defineProperty(exports, "isReservedWord", {
516     enumerable: true,
517     get: function () {
518       return keyword.isReservedWord;
519     }
520   });
521   Object.defineProperty(exports, "isStrictBindOnlyReservedWord", {
522     enumerable: true,
523     get: function () {
524       return keyword.isStrictBindOnlyReservedWord;
525     }
526   });
527   Object.defineProperty(exports, "isStrictBindReservedWord", {
528     enumerable: true,
529     get: function () {
530       return keyword.isStrictBindReservedWord;
531     }
532   });
533   Object.defineProperty(exports, "isStrictReservedWord", {
534     enumerable: true,
535     get: function () {
536       return keyword.isStrictReservedWord;
537     }
538   });
539   Object.defineProperty(exports, "isKeyword", {
540     enumerable: true,
541     get: function () {
542       return keyword.isKeyword;
543     }
544   });
545 });
546
547 var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
548
549 var escapeStringRegexp = function (str) {
550   if (typeof str !== 'string') {
551     throw new TypeError('Expected a string');
552   }
553
554   return str.replace(matchOperatorsRe, '\\$&');
555 };
556
557 var colorName = {
558   "aliceblue": [240, 248, 255],
559   "antiquewhite": [250, 235, 215],
560   "aqua": [0, 255, 255],
561   "aquamarine": [127, 255, 212],
562   "azure": [240, 255, 255],
563   "beige": [245, 245, 220],
564   "bisque": [255, 228, 196],
565   "black": [0, 0, 0],
566   "blanchedalmond": [255, 235, 205],
567   "blue": [0, 0, 255],
568   "blueviolet": [138, 43, 226],
569   "brown": [165, 42, 42],
570   "burlywood": [222, 184, 135],
571   "cadetblue": [95, 158, 160],
572   "chartreuse": [127, 255, 0],
573   "chocolate": [210, 105, 30],
574   "coral": [255, 127, 80],
575   "cornflowerblue": [100, 149, 237],
576   "cornsilk": [255, 248, 220],
577   "crimson": [220, 20, 60],
578   "cyan": [0, 255, 255],
579   "darkblue": [0, 0, 139],
580   "darkcyan": [0, 139, 139],
581   "darkgoldenrod": [184, 134, 11],
582   "darkgray": [169, 169, 169],
583   "darkgreen": [0, 100, 0],
584   "darkgrey": [169, 169, 169],
585   "darkkhaki": [189, 183, 107],
586   "darkmagenta": [139, 0, 139],
587   "darkolivegreen": [85, 107, 47],
588   "darkorange": [255, 140, 0],
589   "darkorchid": [153, 50, 204],
590   "darkred": [139, 0, 0],
591   "darksalmon": [233, 150, 122],
592   "darkseagreen": [143, 188, 143],
593   "darkslateblue": [72, 61, 139],
594   "darkslategray": [47, 79, 79],
595   "darkslategrey": [47, 79, 79],
596   "darkturquoise": [0, 206, 209],
597   "darkviolet": [148, 0, 211],
598   "deeppink": [255, 20, 147],
599   "deepskyblue": [0, 191, 255],
600   "dimgray": [105, 105, 105],
601   "dimgrey": [105, 105, 105],
602   "dodgerblue": [30, 144, 255],
603   "firebrick": [178, 34, 34],
604   "floralwhite": [255, 250, 240],
605   "forestgreen": [34, 139, 34],
606   "fuchsia": [255, 0, 255],
607   "gainsboro": [220, 220, 220],
608   "ghostwhite": [248, 248, 255],
609   "gold": [255, 215, 0],
610   "goldenrod": [218, 165, 32],
611   "gray": [128, 128, 128],
612   "green": [0, 128, 0],
613   "greenyellow": [173, 255, 47],
614   "grey": [128, 128, 128],
615   "honeydew": [240, 255, 240],
616   "hotpink": [255, 105, 180],
617   "indianred": [205, 92, 92],
618   "indigo": [75, 0, 130],
619   "ivory": [255, 255, 240],
620   "khaki": [240, 230, 140],
621   "lavender": [230, 230, 250],
622   "lavenderblush": [255, 240, 245],
623   "lawngreen": [124, 252, 0],
624   "lemonchiffon": [255, 250, 205],
625   "lightblue": [173, 216, 230],
626   "lightcoral": [240, 128, 128],
627   "lightcyan": [224, 255, 255],
628   "lightgoldenrodyellow": [250, 250, 210],
629   "lightgray": [211, 211, 211],
630   "lightgreen": [144, 238, 144],
631   "lightgrey": [211, 211, 211],
632   "lightpink": [255, 182, 193],
633   "lightsalmon": [255, 160, 122],
634   "lightseagreen": [32, 178, 170],
635   "lightskyblue": [135, 206, 250],
636   "lightslategray": [119, 136, 153],
637   "lightslategrey": [119, 136, 153],
638   "lightsteelblue": [176, 196, 222],
639   "lightyellow": [255, 255, 224],
640   "lime": [0, 255, 0],
641   "limegreen": [50, 205, 50],
642   "linen": [250, 240, 230],
643   "magenta": [255, 0, 255],
644   "maroon": [128, 0, 0],
645   "mediumaquamarine": [102, 205, 170],
646   "mediumblue": [0, 0, 205],
647   "mediumorchid": [186, 85, 211],
648   "mediumpurple": [147, 112, 219],
649   "mediumseagreen": [60, 179, 113],
650   "mediumslateblue": [123, 104, 238],
651   "mediumspringgreen": [0, 250, 154],
652   "mediumturquoise": [72, 209, 204],
653   "mediumvioletred": [199, 21, 133],
654   "midnightblue": [25, 25, 112],
655   "mintcream": [245, 255, 250],
656   "mistyrose": [255, 228, 225],
657   "moccasin": [255, 228, 181],
658   "navajowhite": [255, 222, 173],
659   "navy": [0, 0, 128],
660   "oldlace": [253, 245, 230],
661   "olive": [128, 128, 0],
662   "olivedrab": [107, 142, 35],
663   "orange": [255, 165, 0],
664   "orangered": [255, 69, 0],
665   "orchid": [218, 112, 214],
666   "palegoldenrod": [238, 232, 170],
667   "palegreen": [152, 251, 152],
668   "paleturquoise": [175, 238, 238],
669   "palevioletred": [219, 112, 147],
670   "papayawhip": [255, 239, 213],
671   "peachpuff": [255, 218, 185],
672   "peru": [205, 133, 63],
673   "pink": [255, 192, 203],
674   "plum": [221, 160, 221],
675   "powderblue": [176, 224, 230],
676   "purple": [128, 0, 128],
677   "rebeccapurple": [102, 51, 153],
678   "red": [255, 0, 0],
679   "rosybrown": [188, 143, 143],
680   "royalblue": [65, 105, 225],
681   "saddlebrown": [139, 69, 19],
682   "salmon": [250, 128, 114],
683   "sandybrown": [244, 164, 96],
684   "seagreen": [46, 139, 87],
685   "seashell": [255, 245, 238],
686   "sienna": [160, 82, 45],
687   "silver": [192, 192, 192],
688   "skyblue": [135, 206, 235],
689   "slateblue": [106, 90, 205],
690   "slategray": [112, 128, 144],
691   "slategrey": [112, 128, 144],
692   "snow": [255, 250, 250],
693   "springgreen": [0, 255, 127],
694   "steelblue": [70, 130, 180],
695   "tan": [210, 180, 140],
696   "teal": [0, 128, 128],
697   "thistle": [216, 191, 216],
698   "tomato": [255, 99, 71],
699   "turquoise": [64, 224, 208],
700   "violet": [238, 130, 238],
701   "wheat": [245, 222, 179],
702   "white": [255, 255, 255],
703   "whitesmoke": [245, 245, 245],
704   "yellow": [255, 255, 0],
705   "yellowgreen": [154, 205, 50]
706 };
707
708 var conversions = createCommonjsModule(function (module) {
709   /* MIT license */
710   // NOTE: conversions should only return primitive values (i.e. arrays, or
711   //       values that give correct `typeof` results).
712   //       do not use box values types (i.e. Number(), String(), etc.)
713   var reverseKeywords = {};
714
715   for (var key in colorName) {
716     if (colorName.hasOwnProperty(key)) {
717       reverseKeywords[colorName[key]] = key;
718     }
719   }
720
721   var convert = module.exports = {
722     rgb: {
723       channels: 3,
724       labels: 'rgb'
725     },
726     hsl: {
727       channels: 3,
728       labels: 'hsl'
729     },
730     hsv: {
731       channels: 3,
732       labels: 'hsv'
733     },
734     hwb: {
735       channels: 3,
736       labels: 'hwb'
737     },
738     cmyk: {
739       channels: 4,
740       labels: 'cmyk'
741     },
742     xyz: {
743       channels: 3,
744       labels: 'xyz'
745     },
746     lab: {
747       channels: 3,
748       labels: 'lab'
749     },
750     lch: {
751       channels: 3,
752       labels: 'lch'
753     },
754     hex: {
755       channels: 1,
756       labels: ['hex']
757     },
758     keyword: {
759       channels: 1,
760       labels: ['keyword']
761     },
762     ansi16: {
763       channels: 1,
764       labels: ['ansi16']
765     },
766     ansi256: {
767       channels: 1,
768       labels: ['ansi256']
769     },
770     hcg: {
771       channels: 3,
772       labels: ['h', 'c', 'g']
773     },
774     apple: {
775       channels: 3,
776       labels: ['r16', 'g16', 'b16']
777     },
778     gray: {
779       channels: 1,
780       labels: ['gray']
781     }
782   }; // hide .channels and .labels properties
783
784   for (var model in convert) {
785     if (convert.hasOwnProperty(model)) {
786       if (!('channels' in convert[model])) {
787         throw new Error('missing channels property: ' + model);
788       }
789
790       if (!('labels' in convert[model])) {
791         throw new Error('missing channel labels property: ' + model);
792       }
793
794       if (convert[model].labels.length !== convert[model].channels) {
795         throw new Error('channel and label counts mismatch: ' + model);
796       }
797
798       var channels = convert[model].channels;
799       var labels = convert[model].labels;
800       delete convert[model].channels;
801       delete convert[model].labels;
802       Object.defineProperty(convert[model], 'channels', {
803         value: channels
804       });
805       Object.defineProperty(convert[model], 'labels', {
806         value: labels
807       });
808     }
809   }
810
811   convert.rgb.hsl = function (rgb) {
812     var r = rgb[0] / 255;
813     var g = rgb[1] / 255;
814     var b = rgb[2] / 255;
815     var min = Math.min(r, g, b);
816     var max = Math.max(r, g, b);
817     var delta = max - min;
818     var h;
819     var s;
820     var l;
821
822     if (max === min) {
823       h = 0;
824     } else if (r === max) {
825       h = (g - b) / delta;
826     } else if (g === max) {
827       h = 2 + (b - r) / delta;
828     } else if (b === max) {
829       h = 4 + (r - g) / delta;
830     }
831
832     h = Math.min(h * 60, 360);
833
834     if (h < 0) {
835       h += 360;
836     }
837
838     l = (min + max) / 2;
839
840     if (max === min) {
841       s = 0;
842     } else if (l <= 0.5) {
843       s = delta / (max + min);
844     } else {
845       s = delta / (2 - max - min);
846     }
847
848     return [h, s * 100, l * 100];
849   };
850
851   convert.rgb.hsv = function (rgb) {
852     var rdif;
853     var gdif;
854     var bdif;
855     var h;
856     var s;
857     var r = rgb[0] / 255;
858     var g = rgb[1] / 255;
859     var b = rgb[2] / 255;
860     var v = Math.max(r, g, b);
861     var diff = v - Math.min(r, g, b);
862
863     var diffc = function (c) {
864       return (v - c) / 6 / diff + 1 / 2;
865     };
866
867     if (diff === 0) {
868       h = s = 0;
869     } else {
870       s = diff / v;
871       rdif = diffc(r);
872       gdif = diffc(g);
873       bdif = diffc(b);
874
875       if (r === v) {
876         h = bdif - gdif;
877       } else if (g === v) {
878         h = 1 / 3 + rdif - bdif;
879       } else if (b === v) {
880         h = 2 / 3 + gdif - rdif;
881       }
882
883       if (h < 0) {
884         h += 1;
885       } else if (h > 1) {
886         h -= 1;
887       }
888     }
889
890     return [h * 360, s * 100, v * 100];
891   };
892
893   convert.rgb.hwb = function (rgb) {
894     var r = rgb[0];
895     var g = rgb[1];
896     var b = rgb[2];
897     var h = convert.rgb.hsl(rgb)[0];
898     var w = 1 / 255 * Math.min(r, Math.min(g, b));
899     b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
900     return [h, w * 100, b * 100];
901   };
902
903   convert.rgb.cmyk = function (rgb) {
904     var r = rgb[0] / 255;
905     var g = rgb[1] / 255;
906     var b = rgb[2] / 255;
907     var c;
908     var m;
909     var y;
910     var k;
911     k = Math.min(1 - r, 1 - g, 1 - b);
912     c = (1 - r - k) / (1 - k) || 0;
913     m = (1 - g - k) / (1 - k) || 0;
914     y = (1 - b - k) / (1 - k) || 0;
915     return [c * 100, m * 100, y * 100, k * 100];
916   };
917   /**
918    * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
919    * */
920
921
922   function comparativeDistance(x, y) {
923     return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
924   }
925
926   convert.rgb.keyword = function (rgb) {
927     var reversed = reverseKeywords[rgb];
928
929     if (reversed) {
930       return reversed;
931     }
932
933     var currentClosestDistance = Infinity;
934     var currentClosestKeyword;
935
936     for (var keyword in colorName) {
937       if (colorName.hasOwnProperty(keyword)) {
938         var value = colorName[keyword]; // Compute comparative distance
939
940         var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
941
942         if (distance < currentClosestDistance) {
943           currentClosestDistance = distance;
944           currentClosestKeyword = keyword;
945         }
946       }
947     }
948
949     return currentClosestKeyword;
950   };
951
952   convert.keyword.rgb = function (keyword) {
953     return colorName[keyword];
954   };
955
956   convert.rgb.xyz = function (rgb) {
957     var r = rgb[0] / 255;
958     var g = rgb[1] / 255;
959     var b = rgb[2] / 255; // assume sRGB
960
961     r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
962     g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
963     b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
964     var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
965     var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
966     var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
967     return [x * 100, y * 100, z * 100];
968   };
969
970   convert.rgb.lab = function (rgb) {
971     var xyz = convert.rgb.xyz(rgb);
972     var x = xyz[0];
973     var y = xyz[1];
974     var z = xyz[2];
975     var l;
976     var a;
977     var b;
978     x /= 95.047;
979     y /= 100;
980     z /= 108.883;
981     x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
982     y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
983     z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
984     l = 116 * y - 16;
985     a = 500 * (x - y);
986     b = 200 * (y - z);
987     return [l, a, b];
988   };
989
990   convert.hsl.rgb = function (hsl) {
991     var h = hsl[0] / 360;
992     var s = hsl[1] / 100;
993     var l = hsl[2] / 100;
994     var t1;
995     var t2;
996     var t3;
997     var rgb;
998     var val;
999
1000     if (s === 0) {
1001       val = l * 255;
1002       return [val, val, val];
1003     }
1004
1005     if (l < 0.5) {
1006       t2 = l * (1 + s);
1007     } else {
1008       t2 = l + s - l * s;
1009     }
1010
1011     t1 = 2 * l - t2;
1012     rgb = [0, 0, 0];
1013
1014     for (var i = 0; i < 3; i++) {
1015       t3 = h + 1 / 3 * -(i - 1);
1016
1017       if (t3 < 0) {
1018         t3++;
1019       }
1020
1021       if (t3 > 1) {
1022         t3--;
1023       }
1024
1025       if (6 * t3 < 1) {
1026         val = t1 + (t2 - t1) * 6 * t3;
1027       } else if (2 * t3 < 1) {
1028         val = t2;
1029       } else if (3 * t3 < 2) {
1030         val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
1031       } else {
1032         val = t1;
1033       }
1034
1035       rgb[i] = val * 255;
1036     }
1037
1038     return rgb;
1039   };
1040
1041   convert.hsl.hsv = function (hsl) {
1042     var h = hsl[0];
1043     var s = hsl[1] / 100;
1044     var l = hsl[2] / 100;
1045     var smin = s;
1046     var lmin = Math.max(l, 0.01);
1047     var sv;
1048     var v;
1049     l *= 2;
1050     s *= l <= 1 ? l : 2 - l;
1051     smin *= lmin <= 1 ? lmin : 2 - lmin;
1052     v = (l + s) / 2;
1053     sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
1054     return [h, sv * 100, v * 100];
1055   };
1056
1057   convert.hsv.rgb = function (hsv) {
1058     var h = hsv[0] / 60;
1059     var s = hsv[1] / 100;
1060     var v = hsv[2] / 100;
1061     var hi = Math.floor(h) % 6;
1062     var f = h - Math.floor(h);
1063     var p = 255 * v * (1 - s);
1064     var q = 255 * v * (1 - s * f);
1065     var t = 255 * v * (1 - s * (1 - f));
1066     v *= 255;
1067
1068     switch (hi) {
1069       case 0:
1070         return [v, t, p];
1071
1072       case 1:
1073         return [q, v, p];
1074
1075       case 2:
1076         return [p, v, t];
1077
1078       case 3:
1079         return [p, q, v];
1080
1081       case 4:
1082         return [t, p, v];
1083
1084       case 5:
1085         return [v, p, q];
1086     }
1087   };
1088
1089   convert.hsv.hsl = function (hsv) {
1090     var h = hsv[0];
1091     var s = hsv[1] / 100;
1092     var v = hsv[2] / 100;
1093     var vmin = Math.max(v, 0.01);
1094     var lmin;
1095     var sl;
1096     var l;
1097     l = (2 - s) * v;
1098     lmin = (2 - s) * vmin;
1099     sl = s * vmin;
1100     sl /= lmin <= 1 ? lmin : 2 - lmin;
1101     sl = sl || 0;
1102     l /= 2;
1103     return [h, sl * 100, l * 100];
1104   }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
1105
1106
1107   convert.hwb.rgb = function (hwb) {
1108     var h = hwb[0] / 360;
1109     var wh = hwb[1] / 100;
1110     var bl = hwb[2] / 100;
1111     var ratio = wh + bl;
1112     var i;
1113     var v;
1114     var f;
1115     var n; // wh + bl cant be > 1
1116
1117     if (ratio > 1) {
1118       wh /= ratio;
1119       bl /= ratio;
1120     }
1121
1122     i = Math.floor(6 * h);
1123     v = 1 - bl;
1124     f = 6 * h - i;
1125
1126     if ((i & 0x01) !== 0) {
1127       f = 1 - f;
1128     }
1129
1130     n = wh + f * (v - wh); // linear interpolation
1131
1132     var r;
1133     var g;
1134     var b;
1135
1136     switch (i) {
1137       default:
1138       case 6:
1139       case 0:
1140         r = v;
1141         g = n;
1142         b = wh;
1143         break;
1144
1145       case 1:
1146         r = n;
1147         g = v;
1148         b = wh;
1149         break;
1150
1151       case 2:
1152         r = wh;
1153         g = v;
1154         b = n;
1155         break;
1156
1157       case 3:
1158         r = wh;
1159         g = n;
1160         b = v;
1161         break;
1162
1163       case 4:
1164         r = n;
1165         g = wh;
1166         b = v;
1167         break;
1168
1169       case 5:
1170         r = v;
1171         g = wh;
1172         b = n;
1173         break;
1174     }
1175
1176     return [r * 255, g * 255, b * 255];
1177   };
1178
1179   convert.cmyk.rgb = function (cmyk) {
1180     var c = cmyk[0] / 100;
1181     var m = cmyk[1] / 100;
1182     var y = cmyk[2] / 100;
1183     var k = cmyk[3] / 100;
1184     var r;
1185     var g;
1186     var b;
1187     r = 1 - Math.min(1, c * (1 - k) + k);
1188     g = 1 - Math.min(1, m * (1 - k) + k);
1189     b = 1 - Math.min(1, y * (1 - k) + k);
1190     return [r * 255, g * 255, b * 255];
1191   };
1192
1193   convert.xyz.rgb = function (xyz) {
1194     var x = xyz[0] / 100;
1195     var y = xyz[1] / 100;
1196     var z = xyz[2] / 100;
1197     var r;
1198     var g;
1199     var b;
1200     r = x * 3.2406 + y * -1.5372 + z * -0.4986;
1201     g = x * -0.9689 + y * 1.8758 + z * 0.0415;
1202     b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
1203
1204     r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
1205     g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
1206     b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
1207     r = Math.min(Math.max(0, r), 1);
1208     g = Math.min(Math.max(0, g), 1);
1209     b = Math.min(Math.max(0, b), 1);
1210     return [r * 255, g * 255, b * 255];
1211   };
1212
1213   convert.xyz.lab = function (xyz) {
1214     var x = xyz[0];
1215     var y = xyz[1];
1216     var z = xyz[2];
1217     var l;
1218     var a;
1219     var b;
1220     x /= 95.047;
1221     y /= 100;
1222     z /= 108.883;
1223     x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
1224     y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
1225     z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
1226     l = 116 * y - 16;
1227     a = 500 * (x - y);
1228     b = 200 * (y - z);
1229     return [l, a, b];
1230   };
1231
1232   convert.lab.xyz = function (lab) {
1233     var l = lab[0];
1234     var a = lab[1];
1235     var b = lab[2];
1236     var x;
1237     var y;
1238     var z;
1239     y = (l + 16) / 116;
1240     x = a / 500 + y;
1241     z = y - b / 200;
1242     var y2 = Math.pow(y, 3);
1243     var x2 = Math.pow(x, 3);
1244     var z2 = Math.pow(z, 3);
1245     y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
1246     x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
1247     z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
1248     x *= 95.047;
1249     y *= 100;
1250     z *= 108.883;
1251     return [x, y, z];
1252   };
1253
1254   convert.lab.lch = function (lab) {
1255     var l = lab[0];
1256     var a = lab[1];
1257     var b = lab[2];
1258     var hr;
1259     var h;
1260     var c;
1261     hr = Math.atan2(b, a);
1262     h = hr * 360 / 2 / Math.PI;
1263
1264     if (h < 0) {
1265       h += 360;
1266     }
1267
1268     c = Math.sqrt(a * a + b * b);
1269     return [l, c, h];
1270   };
1271
1272   convert.lch.lab = function (lch) {
1273     var l = lch[0];
1274     var c = lch[1];
1275     var h = lch[2];
1276     var a;
1277     var b;
1278     var hr;
1279     hr = h / 360 * 2 * Math.PI;
1280     a = c * Math.cos(hr);
1281     b = c * Math.sin(hr);
1282     return [l, a, b];
1283   };
1284
1285   convert.rgb.ansi16 = function (args) {
1286     var r = args[0];
1287     var g = args[1];
1288     var b = args[2];
1289     var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
1290
1291     value = Math.round(value / 50);
1292
1293     if (value === 0) {
1294       return 30;
1295     }
1296
1297     var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
1298
1299     if (value === 2) {
1300       ansi += 60;
1301     }
1302
1303     return ansi;
1304   };
1305
1306   convert.hsv.ansi16 = function (args) {
1307     // optimization here; we already know the value and don't need to get
1308     // it converted for us.
1309     return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
1310   };
1311
1312   convert.rgb.ansi256 = function (args) {
1313     var r = args[0];
1314     var g = args[1];
1315     var b = args[2]; // we use the extended greyscale palette here, with the exception of
1316     // black and white. normal palette only has 4 greyscale shades.
1317
1318     if (r === g && g === b) {
1319       if (r < 8) {
1320         return 16;
1321       }
1322
1323       if (r > 248) {
1324         return 231;
1325       }
1326
1327       return Math.round((r - 8) / 247 * 24) + 232;
1328     }
1329
1330     var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
1331     return ansi;
1332   };
1333
1334   convert.ansi16.rgb = function (args) {
1335     var color = args % 10; // handle greyscale
1336
1337     if (color === 0 || color === 7) {
1338       if (args > 50) {
1339         color += 3.5;
1340       }
1341
1342       color = color / 10.5 * 255;
1343       return [color, color, color];
1344     }
1345
1346     var mult = (~~(args > 50) + 1) * 0.5;
1347     var r = (color & 1) * mult * 255;
1348     var g = (color >> 1 & 1) * mult * 255;
1349     var b = (color >> 2 & 1) * mult * 255;
1350     return [r, g, b];
1351   };
1352
1353   convert.ansi256.rgb = function (args) {
1354     // handle greyscale
1355     if (args >= 232) {
1356       var c = (args - 232) * 10 + 8;
1357       return [c, c, c];
1358     }
1359
1360     args -= 16;
1361     var rem;
1362     var r = Math.floor(args / 36) / 5 * 255;
1363     var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
1364     var b = rem % 6 / 5 * 255;
1365     return [r, g, b];
1366   };
1367
1368   convert.rgb.hex = function (args) {
1369     var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
1370     var string = integer.toString(16).toUpperCase();
1371     return '000000'.substring(string.length) + string;
1372   };
1373
1374   convert.hex.rgb = function (args) {
1375     var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
1376
1377     if (!match) {
1378       return [0, 0, 0];
1379     }
1380
1381     var colorString = match[0];
1382
1383     if (match[0].length === 3) {
1384       colorString = colorString.split('').map(function (char) {
1385         return char + char;
1386       }).join('');
1387     }
1388
1389     var integer = parseInt(colorString, 16);
1390     var r = integer >> 16 & 0xFF;
1391     var g = integer >> 8 & 0xFF;
1392     var b = integer & 0xFF;
1393     return [r, g, b];
1394   };
1395
1396   convert.rgb.hcg = function (rgb) {
1397     var r = rgb[0] / 255;
1398     var g = rgb[1] / 255;
1399     var b = rgb[2] / 255;
1400     var max = Math.max(Math.max(r, g), b);
1401     var min = Math.min(Math.min(r, g), b);
1402     var chroma = max - min;
1403     var grayscale;
1404     var hue;
1405
1406     if (chroma < 1) {
1407       grayscale = min / (1 - chroma);
1408     } else {
1409       grayscale = 0;
1410     }
1411
1412     if (chroma <= 0) {
1413       hue = 0;
1414     } else if (max === r) {
1415       hue = (g - b) / chroma % 6;
1416     } else if (max === g) {
1417       hue = 2 + (b - r) / chroma;
1418     } else {
1419       hue = 4 + (r - g) / chroma + 4;
1420     }
1421
1422     hue /= 6;
1423     hue %= 1;
1424     return [hue * 360, chroma * 100, grayscale * 100];
1425   };
1426
1427   convert.hsl.hcg = function (hsl) {
1428     var s = hsl[1] / 100;
1429     var l = hsl[2] / 100;
1430     var c = 1;
1431     var f = 0;
1432
1433     if (l < 0.5) {
1434       c = 2.0 * s * l;
1435     } else {
1436       c = 2.0 * s * (1.0 - l);
1437     }
1438
1439     if (c < 1.0) {
1440       f = (l - 0.5 * c) / (1.0 - c);
1441     }
1442
1443     return [hsl[0], c * 100, f * 100];
1444   };
1445
1446   convert.hsv.hcg = function (hsv) {
1447     var s = hsv[1] / 100;
1448     var v = hsv[2] / 100;
1449     var c = s * v;
1450     var f = 0;
1451
1452     if (c < 1.0) {
1453       f = (v - c) / (1 - c);
1454     }
1455
1456     return [hsv[0], c * 100, f * 100];
1457   };
1458
1459   convert.hcg.rgb = function (hcg) {
1460     var h = hcg[0] / 360;
1461     var c = hcg[1] / 100;
1462     var g = hcg[2] / 100;
1463
1464     if (c === 0.0) {
1465       return [g * 255, g * 255, g * 255];
1466     }
1467
1468     var pure = [0, 0, 0];
1469     var hi = h % 1 * 6;
1470     var v = hi % 1;
1471     var w = 1 - v;
1472     var mg = 0;
1473
1474     switch (Math.floor(hi)) {
1475       case 0:
1476         pure[0] = 1;
1477         pure[1] = v;
1478         pure[2] = 0;
1479         break;
1480
1481       case 1:
1482         pure[0] = w;
1483         pure[1] = 1;
1484         pure[2] = 0;
1485         break;
1486
1487       case 2:
1488         pure[0] = 0;
1489         pure[1] = 1;
1490         pure[2] = v;
1491         break;
1492
1493       case 3:
1494         pure[0] = 0;
1495         pure[1] = w;
1496         pure[2] = 1;
1497         break;
1498
1499       case 4:
1500         pure[0] = v;
1501         pure[1] = 0;
1502         pure[2] = 1;
1503         break;
1504
1505       default:
1506         pure[0] = 1;
1507         pure[1] = 0;
1508         pure[2] = w;
1509     }
1510
1511     mg = (1.0 - c) * g;
1512     return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
1513   };
1514
1515   convert.hcg.hsv = function (hcg) {
1516     var c = hcg[1] / 100;
1517     var g = hcg[2] / 100;
1518     var v = c + g * (1.0 - c);
1519     var f = 0;
1520
1521     if (v > 0.0) {
1522       f = c / v;
1523     }
1524
1525     return [hcg[0], f * 100, v * 100];
1526   };
1527
1528   convert.hcg.hsl = function (hcg) {
1529     var c = hcg[1] / 100;
1530     var g = hcg[2] / 100;
1531     var l = g * (1.0 - c) + 0.5 * c;
1532     var s = 0;
1533
1534     if (l > 0.0 && l < 0.5) {
1535       s = c / (2 * l);
1536     } else if (l >= 0.5 && l < 1.0) {
1537       s = c / (2 * (1 - l));
1538     }
1539
1540     return [hcg[0], s * 100, l * 100];
1541   };
1542
1543   convert.hcg.hwb = function (hcg) {
1544     var c = hcg[1] / 100;
1545     var g = hcg[2] / 100;
1546     var v = c + g * (1.0 - c);
1547     return [hcg[0], (v - c) * 100, (1 - v) * 100];
1548   };
1549
1550   convert.hwb.hcg = function (hwb) {
1551     var w = hwb[1] / 100;
1552     var b = hwb[2] / 100;
1553     var v = 1 - b;
1554     var c = v - w;
1555     var g = 0;
1556
1557     if (c < 1) {
1558       g = (v - c) / (1 - c);
1559     }
1560
1561     return [hwb[0], c * 100, g * 100];
1562   };
1563
1564   convert.apple.rgb = function (apple) {
1565     return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
1566   };
1567
1568   convert.rgb.apple = function (rgb) {
1569     return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
1570   };
1571
1572   convert.gray.rgb = function (args) {
1573     return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
1574   };
1575
1576   convert.gray.hsl = convert.gray.hsv = function (args) {
1577     return [0, 0, args[0]];
1578   };
1579
1580   convert.gray.hwb = function (gray) {
1581     return [0, 100, gray[0]];
1582   };
1583
1584   convert.gray.cmyk = function (gray) {
1585     return [0, 0, 0, gray[0]];
1586   };
1587
1588   convert.gray.lab = function (gray) {
1589     return [gray[0], 0, 0];
1590   };
1591
1592   convert.gray.hex = function (gray) {
1593     var val = Math.round(gray[0] / 100 * 255) & 0xFF;
1594     var integer = (val << 16) + (val << 8) + val;
1595     var string = integer.toString(16).toUpperCase();
1596     return '000000'.substring(string.length) + string;
1597   };
1598
1599   convert.rgb.gray = function (rgb) {
1600     var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
1601     return [val / 255 * 100];
1602   };
1603 });
1604
1605 /*
1606         this function routes a model to all other models.
1607
1608         all functions that are routed have a property `.conversion` attached
1609         to the returned synthetic function. This property is an array
1610         of strings, each with the steps in between the 'from' and 'to'
1611         color models (inclusive).
1612
1613         conversions that are not possible simply are not included.
1614 */
1615
1616 function buildGraph() {
1617   var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
1618
1619   var models = Object.keys(conversions);
1620
1621   for (var len = models.length, i = 0; i < len; i++) {
1622     graph[models[i]] = {
1623       // http://jsperf.com/1-vs-infinity
1624       // micro-opt, but this is simple.
1625       distance: -1,
1626       parent: null
1627     };
1628   }
1629
1630   return graph;
1631 } // https://en.wikipedia.org/wiki/Breadth-first_search
1632
1633
1634 function deriveBFS(fromModel) {
1635   var graph = buildGraph();
1636   var queue = [fromModel]; // unshift -> queue -> pop
1637
1638   graph[fromModel].distance = 0;
1639
1640   while (queue.length) {
1641     var current = queue.pop();
1642     var adjacents = Object.keys(conversions[current]);
1643
1644     for (var len = adjacents.length, i = 0; i < len; i++) {
1645       var adjacent = adjacents[i];
1646       var node = graph[adjacent];
1647
1648       if (node.distance === -1) {
1649         node.distance = graph[current].distance + 1;
1650         node.parent = current;
1651         queue.unshift(adjacent);
1652       }
1653     }
1654   }
1655
1656   return graph;
1657 }
1658
1659 function link(from, to) {
1660   return function (args) {
1661     return to(from(args));
1662   };
1663 }
1664
1665 function wrapConversion(toModel, graph) {
1666   var path = [graph[toModel].parent, toModel];
1667   var fn = conversions[graph[toModel].parent][toModel];
1668   var cur = graph[toModel].parent;
1669
1670   while (graph[cur].parent) {
1671     path.unshift(graph[cur].parent);
1672     fn = link(conversions[graph[cur].parent][cur], fn);
1673     cur = graph[cur].parent;
1674   }
1675
1676   fn.conversion = path;
1677   return fn;
1678 }
1679
1680 var route = function (fromModel) {
1681   var graph = deriveBFS(fromModel);
1682   var conversion = {};
1683   var models = Object.keys(graph);
1684
1685   for (var len = models.length, i = 0; i < len; i++) {
1686     var toModel = models[i];
1687     var node = graph[toModel];
1688
1689     if (node.parent === null) {
1690       // no possible conversion, or this node is the source model.
1691       continue;
1692     }
1693
1694     conversion[toModel] = wrapConversion(toModel, graph);
1695   }
1696
1697   return conversion;
1698 };
1699
1700 var convert = {};
1701 var models = Object.keys(conversions);
1702
1703 function wrapRaw(fn) {
1704   var wrappedFn = function (args) {
1705     if (args === undefined || args === null) {
1706       return args;
1707     }
1708
1709     if (arguments.length > 1) {
1710       args = Array.prototype.slice.call(arguments);
1711     }
1712
1713     return fn(args);
1714   }; // preserve .conversion property if there is one
1715
1716
1717   if ('conversion' in fn) {
1718     wrappedFn.conversion = fn.conversion;
1719   }
1720
1721   return wrappedFn;
1722 }
1723
1724 function wrapRounded(fn) {
1725   var wrappedFn = function (args) {
1726     if (args === undefined || args === null) {
1727       return args;
1728     }
1729
1730     if (arguments.length > 1) {
1731       args = Array.prototype.slice.call(arguments);
1732     }
1733
1734     var result = fn(args); // we're assuming the result is an array here.
1735     // see notice in conversions.js; don't use box types
1736     // in conversion functions.
1737
1738     if (typeof result === 'object') {
1739       for (var len = result.length, i = 0; i < len; i++) {
1740         result[i] = Math.round(result[i]);
1741       }
1742     }
1743
1744     return result;
1745   }; // preserve .conversion property if there is one
1746
1747
1748   if ('conversion' in fn) {
1749     wrappedFn.conversion = fn.conversion;
1750   }
1751
1752   return wrappedFn;
1753 }
1754
1755 models.forEach(function (fromModel) {
1756   convert[fromModel] = {};
1757   Object.defineProperty(convert[fromModel], 'channels', {
1758     value: conversions[fromModel].channels
1759   });
1760   Object.defineProperty(convert[fromModel], 'labels', {
1761     value: conversions[fromModel].labels
1762   });
1763   var routes = route(fromModel);
1764   var routeModels = Object.keys(routes);
1765   routeModels.forEach(function (toModel) {
1766     var fn = routes[toModel];
1767     convert[fromModel][toModel] = wrapRounded(fn);
1768     convert[fromModel][toModel].raw = wrapRaw(fn);
1769   });
1770 });
1771 var colorConvert = convert;
1772
1773 var ansiStyles = createCommonjsModule(function (module) {
1774
1775   const wrapAnsi16 = (fn, offset) => function () {
1776     const code = fn.apply(colorConvert, arguments);
1777     return `\u001B[${code + offset}m`;
1778   };
1779
1780   const wrapAnsi256 = (fn, offset) => function () {
1781     const code = fn.apply(colorConvert, arguments);
1782     return `\u001B[${38 + offset};5;${code}m`;
1783   };
1784
1785   const wrapAnsi16m = (fn, offset) => function () {
1786     const rgb = fn.apply(colorConvert, arguments);
1787     return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
1788   };
1789
1790   function assembleStyles() {
1791     const codes = new Map();
1792     const styles = {
1793       modifier: {
1794         reset: [0, 0],
1795         // 21 isn't widely supported and 22 does the same thing
1796         bold: [1, 22],
1797         dim: [2, 22],
1798         italic: [3, 23],
1799         underline: [4, 24],
1800         inverse: [7, 27],
1801         hidden: [8, 28],
1802         strikethrough: [9, 29]
1803       },
1804       color: {
1805         black: [30, 39],
1806         red: [31, 39],
1807         green: [32, 39],
1808         yellow: [33, 39],
1809         blue: [34, 39],
1810         magenta: [35, 39],
1811         cyan: [36, 39],
1812         white: [37, 39],
1813         gray: [90, 39],
1814         // Bright color
1815         redBright: [91, 39],
1816         greenBright: [92, 39],
1817         yellowBright: [93, 39],
1818         blueBright: [94, 39],
1819         magentaBright: [95, 39],
1820         cyanBright: [96, 39],
1821         whiteBright: [97, 39]
1822       },
1823       bgColor: {
1824         bgBlack: [40, 49],
1825         bgRed: [41, 49],
1826         bgGreen: [42, 49],
1827         bgYellow: [43, 49],
1828         bgBlue: [44, 49],
1829         bgMagenta: [45, 49],
1830         bgCyan: [46, 49],
1831         bgWhite: [47, 49],
1832         // Bright color
1833         bgBlackBright: [100, 49],
1834         bgRedBright: [101, 49],
1835         bgGreenBright: [102, 49],
1836         bgYellowBright: [103, 49],
1837         bgBlueBright: [104, 49],
1838         bgMagentaBright: [105, 49],
1839         bgCyanBright: [106, 49],
1840         bgWhiteBright: [107, 49]
1841       }
1842     }; // Fix humans
1843
1844     styles.color.grey = styles.color.gray;
1845
1846     for (const groupName of Object.keys(styles)) {
1847       const group = styles[groupName];
1848
1849       for (const styleName of Object.keys(group)) {
1850         const style = group[styleName];
1851         styles[styleName] = {
1852           open: `\u001B[${style[0]}m`,
1853           close: `\u001B[${style[1]}m`
1854         };
1855         group[styleName] = styles[styleName];
1856         codes.set(style[0], style[1]);
1857       }
1858
1859       Object.defineProperty(styles, groupName, {
1860         value: group,
1861         enumerable: false
1862       });
1863       Object.defineProperty(styles, 'codes', {
1864         value: codes,
1865         enumerable: false
1866       });
1867     }
1868
1869     const ansi2ansi = n => n;
1870
1871     const rgb2rgb = (r, g, b) => [r, g, b];
1872
1873     styles.color.close = '\u001B[39m';
1874     styles.bgColor.close = '\u001B[49m';
1875     styles.color.ansi = {
1876       ansi: wrapAnsi16(ansi2ansi, 0)
1877     };
1878     styles.color.ansi256 = {
1879       ansi256: wrapAnsi256(ansi2ansi, 0)
1880     };
1881     styles.color.ansi16m = {
1882       rgb: wrapAnsi16m(rgb2rgb, 0)
1883     };
1884     styles.bgColor.ansi = {
1885       ansi: wrapAnsi16(ansi2ansi, 10)
1886     };
1887     styles.bgColor.ansi256 = {
1888       ansi256: wrapAnsi256(ansi2ansi, 10)
1889     };
1890     styles.bgColor.ansi16m = {
1891       rgb: wrapAnsi16m(rgb2rgb, 10)
1892     };
1893
1894     for (let key of Object.keys(colorConvert)) {
1895       if (typeof colorConvert[key] !== 'object') {
1896         continue;
1897       }
1898
1899       const suite = colorConvert[key];
1900
1901       if (key === 'ansi16') {
1902         key = 'ansi';
1903       }
1904
1905       if ('ansi16' in suite) {
1906         styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
1907         styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
1908       }
1909
1910       if ('ansi256' in suite) {
1911         styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
1912         styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
1913       }
1914
1915       if ('rgb' in suite) {
1916         styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
1917         styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
1918       }
1919     }
1920
1921     return styles;
1922   } // Make the export immutable
1923
1924
1925   Object.defineProperty(module, 'exports', {
1926     enumerable: true,
1927     get: assembleStyles
1928   });
1929 });
1930
1931 var hasFlag = (flag, argv) => {
1932   argv = argv || process.argv;
1933   const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
1934   const pos = argv.indexOf(prefix + flag);
1935   const terminatorPos = argv.indexOf('--');
1936   return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
1937 };
1938
1939 const env = process.env;
1940 let forceColor;
1941
1942 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
1943   forceColor = false;
1944 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
1945   forceColor = true;
1946 }
1947
1948 if ('FORCE_COLOR' in env) {
1949   forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
1950 }
1951
1952 function translateLevel(level) {
1953   if (level === 0) {
1954     return false;
1955   }
1956
1957   return {
1958     level,
1959     hasBasic: true,
1960     has256: level >= 2,
1961     has16m: level >= 3
1962   };
1963 }
1964
1965 function supportsColor(stream) {
1966   if (forceColor === false) {
1967     return 0;
1968   }
1969
1970   if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
1971     return 3;
1972   }
1973
1974   if (hasFlag('color=256')) {
1975     return 2;
1976   }
1977
1978   if (stream && !stream.isTTY && forceColor !== true) {
1979     return 0;
1980   }
1981
1982   const min = forceColor ? 1 : 0;
1983
1984   if (process.platform === 'win32') {
1985     // Node.js 7.5.0 is the first version of Node.js to include a patch to
1986     // libuv that enables 256 color output on Windows. Anything earlier and it
1987     // won't work. However, here we target Node.js 8 at minimum as it is an LTS
1988     // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
1989     // release that supports 256 colors. Windows 10 build 14931 is the first release
1990     // that supports 16m/TrueColor.
1991     const osRelease = os__default['default'].release().split('.');
1992
1993     if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
1994       return Number(osRelease[2]) >= 14931 ? 3 : 2;
1995     }
1996
1997     return 1;
1998   }
1999
2000   if ('CI' in env) {
2001     if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
2002       return 1;
2003     }
2004
2005     return min;
2006   }
2007
2008   if ('TEAMCITY_VERSION' in env) {
2009     return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2010   }
2011
2012   if (env.COLORTERM === 'truecolor') {
2013     return 3;
2014   }
2015
2016   if ('TERM_PROGRAM' in env) {
2017     const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
2018
2019     switch (env.TERM_PROGRAM) {
2020       case 'iTerm.app':
2021         return version >= 3 ? 3 : 2;
2022
2023       case 'Apple_Terminal':
2024         return 2;
2025       // No default
2026     }
2027   }
2028
2029   if (/-256(color)?$/i.test(env.TERM)) {
2030     return 2;
2031   }
2032
2033   if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
2034     return 1;
2035   }
2036
2037   if ('COLORTERM' in env) {
2038     return 1;
2039   }
2040
2041   if (env.TERM === 'dumb') {
2042     return min;
2043   }
2044
2045   return min;
2046 }
2047
2048 function getSupportLevel(stream) {
2049   const level = supportsColor(stream);
2050   return translateLevel(level);
2051 }
2052
2053 var supportsColor_1 = {
2054   supportsColor: getSupportLevel,
2055   stdout: getSupportLevel(process.stdout),
2056   stderr: getSupportLevel(process.stderr)
2057 };
2058
2059 const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
2060 const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
2061 const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
2062 const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
2063 const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
2064
2065 function unescape(c) {
2066   if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
2067     return String.fromCharCode(parseInt(c.slice(1), 16));
2068   }
2069
2070   return ESCAPES.get(c) || c;
2071 }
2072
2073 function parseArguments(name, args) {
2074   const results = [];
2075   const chunks = args.trim().split(/\s*,\s*/g);
2076   let matches;
2077
2078   for (const chunk of chunks) {
2079     if (!isNaN(chunk)) {
2080       results.push(Number(chunk));
2081     } else if (matches = chunk.match(STRING_REGEX)) {
2082       results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
2083     } else {
2084       throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
2085     }
2086   }
2087
2088   return results;
2089 }
2090
2091 function parseStyle(style) {
2092   STYLE_REGEX.lastIndex = 0;
2093   const results = [];
2094   let matches;
2095
2096   while ((matches = STYLE_REGEX.exec(style)) !== null) {
2097     const name = matches[1];
2098
2099     if (matches[2]) {
2100       const args = parseArguments(name, matches[2]);
2101       results.push([name].concat(args));
2102     } else {
2103       results.push([name]);
2104     }
2105   }
2106
2107   return results;
2108 }
2109
2110 function buildStyle(chalk, styles) {
2111   const enabled = {};
2112
2113   for (const layer of styles) {
2114     for (const style of layer.styles) {
2115       enabled[style[0]] = layer.inverse ? null : style.slice(1);
2116     }
2117   }
2118
2119   let current = chalk;
2120
2121   for (const styleName of Object.keys(enabled)) {
2122     if (Array.isArray(enabled[styleName])) {
2123       if (!(styleName in current)) {
2124         throw new Error(`Unknown Chalk style: ${styleName}`);
2125       }
2126
2127       if (enabled[styleName].length > 0) {
2128         current = current[styleName].apply(current, enabled[styleName]);
2129       } else {
2130         current = current[styleName];
2131       }
2132     }
2133   }
2134
2135   return current;
2136 }
2137
2138 var templates = (chalk, tmp) => {
2139   const styles = [];
2140   const chunks = [];
2141   let chunk = []; // eslint-disable-next-line max-params
2142
2143   tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
2144     if (escapeChar) {
2145       chunk.push(unescape(escapeChar));
2146     } else if (style) {
2147       const str = chunk.join('');
2148       chunk = [];
2149       chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
2150       styles.push({
2151         inverse,
2152         styles: parseStyle(style)
2153       });
2154     } else if (close) {
2155       if (styles.length === 0) {
2156         throw new Error('Found extraneous } in Chalk template literal');
2157       }
2158
2159       chunks.push(buildStyle(chalk, styles)(chunk.join('')));
2160       chunk = [];
2161       styles.pop();
2162     } else {
2163       chunk.push(chr);
2164     }
2165   });
2166   chunks.push(chunk.join(''));
2167
2168   if (styles.length > 0) {
2169     const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
2170     throw new Error(errMsg);
2171   }
2172
2173   return chunks.join('');
2174 };
2175
2176 var chalk = createCommonjsModule(function (module) {
2177
2178   const stdoutColor = supportsColor_1.stdout;
2179   const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` â†’ `ansiStyles.color[name]` mapping
2180
2181   const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
2182
2183   const skipModels = new Set(['gray']);
2184   const styles = Object.create(null);
2185
2186   function applyOptions(obj, options) {
2187     options = options || {}; // Detect level if not set manually
2188
2189     const scLevel = stdoutColor ? stdoutColor.level : 0;
2190     obj.level = options.level === undefined ? scLevel : options.level;
2191     obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
2192   }
2193
2194   function Chalk(options) {
2195     // We check for this.template here since calling `chalk.constructor()`
2196     // by itself will have a `this` of a previously constructed chalk object
2197     if (!this || !(this instanceof Chalk) || this.template) {
2198       const chalk = {};
2199       applyOptions(chalk, options);
2200
2201       chalk.template = function () {
2202         const args = [].slice.call(arguments);
2203         return chalkTag.apply(null, [chalk.template].concat(args));
2204       };
2205
2206       Object.setPrototypeOf(chalk, Chalk.prototype);
2207       Object.setPrototypeOf(chalk.template, chalk);
2208       chalk.template.constructor = Chalk;
2209       return chalk.template;
2210     }
2211
2212     applyOptions(this, options);
2213   } // Use bright blue on Windows as the normal blue color is illegible
2214
2215
2216   if (isSimpleWindowsTerm) {
2217     ansiStyles.blue.open = '\u001B[94m';
2218   }
2219
2220   for (const key of Object.keys(ansiStyles)) {
2221     ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
2222     styles[key] = {
2223       get() {
2224         const codes = ansiStyles[key];
2225         return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
2226       }
2227
2228     };
2229   }
2230
2231   styles.visible = {
2232     get() {
2233       return build.call(this, this._styles || [], true, 'visible');
2234     }
2235
2236   };
2237   ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
2238
2239   for (const model of Object.keys(ansiStyles.color.ansi)) {
2240     if (skipModels.has(model)) {
2241       continue;
2242     }
2243
2244     styles[model] = {
2245       get() {
2246         const level = this.level;
2247         return function () {
2248           const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
2249           const codes = {
2250             open,
2251             close: ansiStyles.color.close,
2252             closeRe: ansiStyles.color.closeRe
2253           };
2254           return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
2255         };
2256       }
2257
2258     };
2259   }
2260
2261   ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
2262
2263   for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
2264     if (skipModels.has(model)) {
2265       continue;
2266     }
2267
2268     const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
2269     styles[bgModel] = {
2270       get() {
2271         const level = this.level;
2272         return function () {
2273           const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
2274           const codes = {
2275             open,
2276             close: ansiStyles.bgColor.close,
2277             closeRe: ansiStyles.bgColor.closeRe
2278           };
2279           return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
2280         };
2281       }
2282
2283     };
2284   }
2285
2286   const proto = Object.defineProperties(() => {}, styles);
2287
2288   function build(_styles, _empty, key) {
2289     const builder = function () {
2290       return applyStyle.apply(builder, arguments);
2291     };
2292
2293     builder._styles = _styles;
2294     builder._empty = _empty;
2295     const self = this;
2296     Object.defineProperty(builder, 'level', {
2297       enumerable: true,
2298
2299       get() {
2300         return self.level;
2301       },
2302
2303       set(level) {
2304         self.level = level;
2305       }
2306
2307     });
2308     Object.defineProperty(builder, 'enabled', {
2309       enumerable: true,
2310
2311       get() {
2312         return self.enabled;
2313       },
2314
2315       set(enabled) {
2316         self.enabled = enabled;
2317       }
2318
2319     }); // See below for fix regarding invisible grey/dim combination on Windows
2320
2321     builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
2322     // no way to create a function with a different prototype
2323
2324     builder.__proto__ = proto; // eslint-disable-line no-proto
2325
2326     return builder;
2327   }
2328
2329   function applyStyle() {
2330     // Support varags, but simply cast to string in case there's only one arg
2331     const args = arguments;
2332     const argsLen = args.length;
2333     let str = String(arguments[0]);
2334
2335     if (argsLen === 0) {
2336       return '';
2337     }
2338
2339     if (argsLen > 1) {
2340       // Don't slice `arguments`, it prevents V8 optimizations
2341       for (let a = 1; a < argsLen; a++) {
2342         str += ' ' + args[a];
2343       }
2344     }
2345
2346     if (!this.enabled || this.level <= 0 || !str) {
2347       return this._empty ? '' : str;
2348     } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
2349     // see https://github.com/chalk/chalk/issues/58
2350     // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
2351
2352
2353     const originalDim = ansiStyles.dim.open;
2354
2355     if (isSimpleWindowsTerm && this.hasGrey) {
2356       ansiStyles.dim.open = '';
2357     }
2358
2359     for (const code of this._styles.slice().reverse()) {
2360       // Replace any instances already present with a re-opening code
2361       // otherwise only the part of the string until said closing code
2362       // will be colored, and the rest will simply be 'plain'.
2363       str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
2364       // after next line to fix a bleed issue on macOS
2365       // https://github.com/chalk/chalk/pull/92
2366
2367       str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
2368     } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
2369
2370
2371     ansiStyles.dim.open = originalDim;
2372     return str;
2373   }
2374
2375   function chalkTag(chalk, strings) {
2376     if (!Array.isArray(strings)) {
2377       // If chalk() was called by itself or with a string,
2378       // return the string itself as a string.
2379       return [].slice.call(arguments, 1).join(' ');
2380     }
2381
2382     const args = [].slice.call(arguments, 2);
2383     const parts = [strings.raw[0]];
2384
2385     for (let i = 1; i < strings.length; i++) {
2386       parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
2387       parts.push(String(strings.raw[i]));
2388     }
2389
2390     return templates(chalk, parts.join(''));
2391   }
2392
2393   Object.defineProperties(Chalk.prototype, styles);
2394   module.exports = Chalk(); // eslint-disable-line new-cap
2395
2396   module.exports.supportsColor = stdoutColor;
2397   module.exports.default = module.exports; // For TypeScript
2398 });
2399
2400 var lib$1 = createCommonjsModule(function (module, exports) {
2401
2402   Object.defineProperty(exports, "__esModule", {
2403     value: true
2404   });
2405   exports.shouldHighlight = shouldHighlight;
2406   exports.getChalk = getChalk;
2407   exports.default = highlight;
2408
2409   var _jsTokens = _interopRequireWildcard(jsTokens);
2410
2411   var _chalk = _interopRequireDefault(chalk);
2412
2413   function _interopRequireDefault(obj) {
2414     return obj && obj.__esModule ? obj : {
2415       default: obj
2416     };
2417   }
2418
2419   function _getRequireWildcardCache() {
2420     if (typeof WeakMap !== "function") return null;
2421     var cache = new WeakMap();
2422
2423     _getRequireWildcardCache = function () {
2424       return cache;
2425     };
2426
2427     return cache;
2428   }
2429
2430   function _interopRequireWildcard(obj) {
2431     if (obj && obj.__esModule) {
2432       return obj;
2433     }
2434
2435     if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
2436       return {
2437         default: obj
2438       };
2439     }
2440
2441     var cache = _getRequireWildcardCache();
2442
2443     if (cache && cache.has(obj)) {
2444       return cache.get(obj);
2445     }
2446
2447     var newObj = {};
2448     var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
2449
2450     for (var key in obj) {
2451       if (Object.prototype.hasOwnProperty.call(obj, key)) {
2452         var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
2453
2454         if (desc && (desc.get || desc.set)) {
2455           Object.defineProperty(newObj, key, desc);
2456         } else {
2457           newObj[key] = obj[key];
2458         }
2459       }
2460     }
2461
2462     newObj.default = obj;
2463
2464     if (cache) {
2465       cache.set(obj, newObj);
2466     }
2467
2468     return newObj;
2469   }
2470
2471   function getDefs(chalk) {
2472     return {
2473       keyword: chalk.cyan,
2474       capitalized: chalk.yellow,
2475       jsx_tag: chalk.yellow,
2476       punctuator: chalk.yellow,
2477       number: chalk.magenta,
2478       string: chalk.green,
2479       regex: chalk.magenta,
2480       comment: chalk.grey,
2481       invalid: chalk.white.bgRed.bold
2482     };
2483   }
2484
2485   const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
2486   const JSX_TAG = /^[a-z][\w-]*$/i;
2487   const BRACKET = /^[()[\]{}]$/;
2488
2489   function getTokenType(match) {
2490     const [offset, text] = match.slice(-2);
2491     const token = (0, _jsTokens.matchToToken)(match);
2492
2493     if (token.type === "name") {
2494       if ((0, lib.isKeyword)(token.value) || (0, lib.isReservedWord)(token.value)) {
2495         return "keyword";
2496       }
2497
2498       if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
2499         return "jsx_tag";
2500       }
2501
2502       if (token.value[0] !== token.value[0].toLowerCase()) {
2503         return "capitalized";
2504       }
2505     }
2506
2507     if (token.type === "punctuator" && BRACKET.test(token.value)) {
2508       return "bracket";
2509     }
2510
2511     if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
2512       return "punctuator";
2513     }
2514
2515     return token.type;
2516   }
2517
2518   function highlightTokens(defs, text) {
2519     return text.replace(_jsTokens.default, function (...args) {
2520       const type = getTokenType(args);
2521       const colorize = defs[type];
2522
2523       if (colorize) {
2524         return args[0].split(NEWLINE).map(str => colorize(str)).join("\n");
2525       } else {
2526         return args[0];
2527       }
2528     });
2529   }
2530
2531   function shouldHighlight(options) {
2532     return _chalk.default.supportsColor || options.forceColor;
2533   }
2534
2535   function getChalk(options) {
2536     let chalk = _chalk.default;
2537
2538     if (options.forceColor) {
2539       chalk = new _chalk.default.constructor({
2540         enabled: true,
2541         level: 1
2542       });
2543     }
2544
2545     return chalk;
2546   }
2547
2548   function highlight(code, options = {}) {
2549     if (shouldHighlight(options)) {
2550       const chalk = getChalk(options);
2551       const defs = getDefs(chalk);
2552       return highlightTokens(defs, code);
2553     } else {
2554       return code;
2555     }
2556   }
2557 });
2558
2559 var lib$2 = createCommonjsModule(function (module, exports) {
2560
2561   Object.defineProperty(exports, "__esModule", {
2562     value: true
2563   });
2564   exports.codeFrameColumns = codeFrameColumns;
2565   exports.default = _default;
2566
2567   var _highlight = _interopRequireWildcard(lib$1);
2568
2569   function _getRequireWildcardCache() {
2570     if (typeof WeakMap !== "function") return null;
2571     var cache = new WeakMap();
2572
2573     _getRequireWildcardCache = function () {
2574       return cache;
2575     };
2576
2577     return cache;
2578   }
2579
2580   function _interopRequireWildcard(obj) {
2581     if (obj && obj.__esModule) {
2582       return obj;
2583     }
2584
2585     if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
2586       return {
2587         default: obj
2588       };
2589     }
2590
2591     var cache = _getRequireWildcardCache();
2592
2593     if (cache && cache.has(obj)) {
2594       return cache.get(obj);
2595     }
2596
2597     var newObj = {};
2598     var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
2599
2600     for (var key in obj) {
2601       if (Object.prototype.hasOwnProperty.call(obj, key)) {
2602         var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
2603
2604         if (desc && (desc.get || desc.set)) {
2605           Object.defineProperty(newObj, key, desc);
2606         } else {
2607           newObj[key] = obj[key];
2608         }
2609       }
2610     }
2611
2612     newObj.default = obj;
2613
2614     if (cache) {
2615       cache.set(obj, newObj);
2616     }
2617
2618     return newObj;
2619   }
2620
2621   let deprecationWarningShown = false;
2622
2623   function getDefs(chalk) {
2624     return {
2625       gutter: chalk.grey,
2626       marker: chalk.red.bold,
2627       message: chalk.red.bold
2628     };
2629   }
2630
2631   const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
2632
2633   function getMarkerLines(loc, source, opts) {
2634     const startLoc = Object.assign({
2635       column: 0,
2636       line: -1
2637     }, loc.start);
2638     const endLoc = Object.assign({}, startLoc, loc.end);
2639     const {
2640       linesAbove = 2,
2641       linesBelow = 3
2642     } = opts || {};
2643     const startLine = startLoc.line;
2644     const startColumn = startLoc.column;
2645     const endLine = endLoc.line;
2646     const endColumn = endLoc.column;
2647     let start = Math.max(startLine - (linesAbove + 1), 0);
2648     let end = Math.min(source.length, endLine + linesBelow);
2649
2650     if (startLine === -1) {
2651       start = 0;
2652     }
2653
2654     if (endLine === -1) {
2655       end = source.length;
2656     }
2657
2658     const lineDiff = endLine - startLine;
2659     const markerLines = {};
2660
2661     if (lineDiff) {
2662       for (let i = 0; i <= lineDiff; i++) {
2663         const lineNumber = i + startLine;
2664
2665         if (!startColumn) {
2666           markerLines[lineNumber] = true;
2667         } else if (i === 0) {
2668           const sourceLength = source[lineNumber - 1].length;
2669           markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
2670         } else if (i === lineDiff) {
2671           markerLines[lineNumber] = [0, endColumn];
2672         } else {
2673           const sourceLength = source[lineNumber - i].length;
2674           markerLines[lineNumber] = [0, sourceLength];
2675         }
2676       }
2677     } else {
2678       if (startColumn === endColumn) {
2679         if (startColumn) {
2680           markerLines[startLine] = [startColumn, 0];
2681         } else {
2682           markerLines[startLine] = true;
2683         }
2684       } else {
2685         markerLines[startLine] = [startColumn, endColumn - startColumn];
2686       }
2687     }
2688
2689     return {
2690       start,
2691       end,
2692       markerLines
2693     };
2694   }
2695
2696   function codeFrameColumns(rawLines, loc, opts = {}) {
2697     const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
2698     const chalk = (0, _highlight.getChalk)(opts);
2699     const defs = getDefs(chalk);
2700
2701     const maybeHighlight = (chalkFn, string) => {
2702       return highlighted ? chalkFn(string) : string;
2703     };
2704
2705     const lines = rawLines.split(NEWLINE);
2706     const {
2707       start,
2708       end,
2709       markerLines
2710     } = getMarkerLines(loc, lines, opts);
2711     const hasColumns = loc.start && typeof loc.start.column === "number";
2712     const numberMaxWidth = String(end).length;
2713     const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
2714     let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
2715       const number = start + 1 + index;
2716       const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
2717       const gutter = ` ${paddedNumber} | `;
2718       const hasMarker = markerLines[number];
2719       const lastMarkerLine = !markerLines[number + 1];
2720
2721       if (hasMarker) {
2722         let markerLine = "";
2723
2724         if (Array.isArray(hasMarker)) {
2725           const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
2726           const numberOfMarkers = hasMarker[1] || 1;
2727           markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
2728
2729           if (lastMarkerLine && opts.message) {
2730             markerLine += " " + maybeHighlight(defs.message, opts.message);
2731           }
2732         }
2733
2734         return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
2735       } else {
2736         return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
2737       }
2738     }).join("\n");
2739
2740     if (opts.message && !hasColumns) {
2741       frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
2742     }
2743
2744     if (highlighted) {
2745       return chalk.reset(frame);
2746     } else {
2747       return frame;
2748     }
2749   }
2750
2751   function _default(rawLines, lineNumber, colNumber, opts = {}) {
2752     if (!deprecationWarningShown) {
2753       deprecationWarningShown = true;
2754       const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
2755
2756       if (process.emitWarning) {
2757         process.emitWarning(message, "DeprecationWarning");
2758       } else {
2759         const deprecationError = new Error(message);
2760         deprecationError.name = "DeprecationWarning";
2761         console.warn(new Error(message));
2762       }
2763     }
2764
2765     colNumber = Math.max(colNumber, 0);
2766     const location = {
2767       start: {
2768         column: colNumber,
2769         line: lineNumber
2770       }
2771     };
2772     return codeFrameColumns(rawLines, location, opts);
2773   }
2774 });
2775
2776 const {
2777   default: LinesAndColumns
2778 } = dist;
2779 const {
2780   codeFrameColumns
2781 } = lib$2;
2782 const JSONError = errorEx_1('JSONError', {
2783   fileName: errorEx_1.append('in %s'),
2784   codeFrame: errorEx_1.append('\n\n%s\n')
2785 });
2786
2787 var parseJson$1 = (string, reviver, filename) => {
2788   if (typeof reviver === 'string') {
2789     filename = reviver;
2790     reviver = null;
2791   }
2792
2793   try {
2794     try {
2795       return JSON.parse(string, reviver);
2796     } catch (error) {
2797       jsonParseBetterErrors(string, reviver);
2798       throw error;
2799     }
2800   } catch (error) {
2801     error.message = error.message.replace(/\n/g, '');
2802     const indexMatch = error.message.match(/in JSON at position (\d+) while parsing near/);
2803     const jsonError = new JSONError(error);
2804
2805     if (filename) {
2806       jsonError.fileName = filename;
2807     }
2808
2809     if (indexMatch && indexMatch.length > 0) {
2810       const lines = new LinesAndColumns(string);
2811       const index = Number(indexMatch[1]);
2812       const location = lines.locationForIndex(index);
2813       const codeFrame = codeFrameColumns(string, {
2814         start: {
2815           line: location.line + 1,
2816           column: location.column + 1
2817         }
2818       }, {
2819         highlightCode: true
2820       });
2821       jsonError.codeFrame = codeFrame;
2822     }
2823
2824     throw jsonError;
2825   }
2826 };
2827
2828 const Char = {
2829   ANCHOR: '&',
2830   COMMENT: '#',
2831   TAG: '!',
2832   DIRECTIVES_END: '-',
2833   DOCUMENT_END: '.'
2834 };
2835 const Type = {
2836   ALIAS: 'ALIAS',
2837   BLANK_LINE: 'BLANK_LINE',
2838   BLOCK_FOLDED: 'BLOCK_FOLDED',
2839   BLOCK_LITERAL: 'BLOCK_LITERAL',
2840   COMMENT: 'COMMENT',
2841   DIRECTIVE: 'DIRECTIVE',
2842   DOCUMENT: 'DOCUMENT',
2843   FLOW_MAP: 'FLOW_MAP',
2844   FLOW_SEQ: 'FLOW_SEQ',
2845   MAP: 'MAP',
2846   MAP_KEY: 'MAP_KEY',
2847   MAP_VALUE: 'MAP_VALUE',
2848   PLAIN: 'PLAIN',
2849   QUOTE_DOUBLE: 'QUOTE_DOUBLE',
2850   QUOTE_SINGLE: 'QUOTE_SINGLE',
2851   SEQ: 'SEQ',
2852   SEQ_ITEM: 'SEQ_ITEM'
2853 };
2854 const defaultTagPrefix = 'tag:yaml.org,2002:';
2855 const defaultTags = {
2856   MAP: 'tag:yaml.org,2002:map',
2857   SEQ: 'tag:yaml.org,2002:seq',
2858   STR: 'tag:yaml.org,2002:str'
2859 };
2860
2861 function findLineStarts(src) {
2862   const ls = [0];
2863   let offset = src.indexOf('\n');
2864
2865   while (offset !== -1) {
2866     offset += 1;
2867     ls.push(offset);
2868     offset = src.indexOf('\n', offset);
2869   }
2870
2871   return ls;
2872 }
2873
2874 function getSrcInfo(cst) {
2875   let lineStarts, src;
2876
2877   if (typeof cst === 'string') {
2878     lineStarts = findLineStarts(cst);
2879     src = cst;
2880   } else {
2881     if (Array.isArray(cst)) cst = cst[0];
2882
2883     if (cst && cst.context) {
2884       if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src);
2885       lineStarts = cst.lineStarts;
2886       src = cst.context.src;
2887     }
2888   }
2889
2890   return {
2891     lineStarts,
2892     src
2893   };
2894 }
2895 /**
2896  * @typedef {Object} LinePos - One-indexed position in the source
2897  * @property {number} line
2898  * @property {number} col
2899  */
2900
2901 /**
2902  * Determine the line/col position matching a character offset.
2903  *
2904  * Accepts a source string or a CST document as the second parameter. With
2905  * the latter, starting indices for lines are cached in the document as
2906  * `lineStarts: number[]`.
2907  *
2908  * Returns a one-indexed `{ line, col }` location if found, or
2909  * `undefined` otherwise.
2910  *
2911  * @param {number} offset
2912  * @param {string|Document|Document[]} cst
2913  * @returns {?LinePos}
2914  */
2915
2916
2917 function getLinePos(offset, cst) {
2918   if (typeof offset !== 'number' || offset < 0) return null;
2919   const {
2920     lineStarts,
2921     src
2922   } = getSrcInfo(cst);
2923   if (!lineStarts || !src || offset > src.length) return null;
2924
2925   for (let i = 0; i < lineStarts.length; ++i) {
2926     const start = lineStarts[i];
2927
2928     if (offset < start) {
2929       return {
2930         line: i,
2931         col: offset - lineStarts[i - 1] + 1
2932       };
2933     }
2934
2935     if (offset === start) return {
2936       line: i + 1,
2937       col: 1
2938     };
2939   }
2940
2941   const line = lineStarts.length;
2942   return {
2943     line,
2944     col: offset - lineStarts[line - 1] + 1
2945   };
2946 }
2947 /**
2948  * Get a specified line from the source.
2949  *
2950  * Accepts a source string or a CST document as the second parameter. With
2951  * the latter, starting indices for lines are cached in the document as
2952  * `lineStarts: number[]`.
2953  *
2954  * Returns the line as a string if found, or `null` otherwise.
2955  *
2956  * @param {number} line One-indexed line number
2957  * @param {string|Document|Document[]} cst
2958  * @returns {?string}
2959  */
2960
2961
2962 function getLine(line, cst) {
2963   const {
2964     lineStarts,
2965     src
2966   } = getSrcInfo(cst);
2967   if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null;
2968   const start = lineStarts[line - 1];
2969   let end = lineStarts[line]; // undefined for last line; that's ok for slice()
2970
2971   while (end && end > start && src[end - 1] === '\n') --end;
2972
2973   return src.slice(start, end);
2974 }
2975 /**
2976  * Pretty-print the starting line from the source indicated by the range `pos`
2977  *
2978  * Trims output to `maxWidth` chars while keeping the starting column visible,
2979  * using `…` at either end to indicate dropped characters.
2980  *
2981  * Returns a two-line string (or `null`) with `\n` as separator; the second line
2982  * will hold appropriately indented `^` marks indicating the column range.
2983  *
2984  * @param {Object} pos
2985  * @param {LinePos} pos.start
2986  * @param {LinePos} [pos.end]
2987  * @param {string|Document|Document[]*} cst
2988  * @param {number} [maxWidth=80]
2989  * @returns {?string}
2990  */
2991
2992
2993 function getPrettyContext({
2994   start,
2995   end
2996 }, cst, maxWidth = 80) {
2997   let src = getLine(start.line, cst);
2998   if (!src) return null;
2999   let {
3000     col
3001   } = start;
3002
3003   if (src.length > maxWidth) {
3004     if (col <= maxWidth - 10) {
3005       src = src.substr(0, maxWidth - 1) + '…';
3006     } else {
3007       const halfWidth = Math.round(maxWidth / 2);
3008       if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…';
3009       col -= src.length - maxWidth;
3010       src = '…' + src.substr(1 - maxWidth);
3011     }
3012   }
3013
3014   let errLen = 1;
3015   let errEnd = '';
3016
3017   if (end) {
3018     if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) {
3019       errLen = end.col - start.col;
3020     } else {
3021       errLen = Math.min(src.length + 1, maxWidth) - col;
3022       errEnd = '…';
3023     }
3024   }
3025
3026   const offset = col > 1 ? ' '.repeat(col - 1) : '';
3027   const err = '^'.repeat(errLen);
3028   return `${src}\n${offset}${err}${errEnd}`;
3029 }
3030
3031 class Range {
3032   static copy(orig) {
3033     return new Range(orig.start, orig.end);
3034   }
3035
3036   constructor(start, end) {
3037     this.start = start;
3038     this.end = end || start;
3039   }
3040
3041   isEmpty() {
3042     return typeof this.start !== 'number' || !this.end || this.end <= this.start;
3043   }
3044   /**
3045    * Set `origStart` and `origEnd` to point to the original source range for
3046    * this node, which may differ due to dropped CR characters.
3047    *
3048    * @param {number[]} cr - Positions of dropped CR characters
3049    * @param {number} offset - Starting index of `cr` from the last call
3050    * @returns {number} - The next offset, matching the one found for `origStart`
3051    */
3052
3053
3054   setOrigRange(cr, offset) {
3055     const {
3056       start,
3057       end
3058     } = this;
3059
3060     if (cr.length === 0 || end <= cr[0]) {
3061       this.origStart = start;
3062       this.origEnd = end;
3063       return offset;
3064     }
3065
3066     let i = offset;
3067
3068     while (i < cr.length) {
3069       if (cr[i] > start) break;else ++i;
3070     }
3071
3072     this.origStart = start + i;
3073     const nextOffset = i;
3074
3075     while (i < cr.length) {
3076       // if end was at \n, it should now be at \r
3077       if (cr[i] >= end) break;else ++i;
3078     }
3079
3080     this.origEnd = end + i;
3081     return nextOffset;
3082   }
3083
3084 }
3085 /** Root class of all nodes */
3086
3087
3088 class Node {
3089   static addStringTerminator(src, offset, str) {
3090     if (str[str.length - 1] === '\n') return str;
3091     const next = Node.endOfWhiteSpace(src, offset);
3092     return next >= src.length || src[next] === '\n' ? str + '\n' : str;
3093   } // ^(---|...)
3094
3095
3096   static atDocumentBoundary(src, offset, sep) {
3097     const ch0 = src[offset];
3098     if (!ch0) return true;
3099     const prev = src[offset - 1];
3100     if (prev && prev !== '\n') return false;
3101
3102     if (sep) {
3103       if (ch0 !== sep) return false;
3104     } else {
3105       if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false;
3106     }
3107
3108     const ch1 = src[offset + 1];
3109     const ch2 = src[offset + 2];
3110     if (ch1 !== ch0 || ch2 !== ch0) return false;
3111     const ch3 = src[offset + 3];
3112     return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' ';
3113   }
3114
3115   static endOfIdentifier(src, offset) {
3116     let ch = src[offset];
3117     const isVerbatim = ch === '<';
3118     const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ','];
3119
3120     while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1];
3121
3122     if (isVerbatim && ch === '>') offset += 1;
3123     return offset;
3124   }
3125
3126   static endOfIndent(src, offset) {
3127     let ch = src[offset];
3128
3129     while (ch === ' ') ch = src[offset += 1];
3130
3131     return offset;
3132   }
3133
3134   static endOfLine(src, offset) {
3135     let ch = src[offset];
3136
3137     while (ch && ch !== '\n') ch = src[offset += 1];
3138
3139     return offset;
3140   }
3141
3142   static endOfWhiteSpace(src, offset) {
3143     let ch = src[offset];
3144
3145     while (ch === '\t' || ch === ' ') ch = src[offset += 1];
3146
3147     return offset;
3148   }
3149
3150   static startOfLine(src, offset) {
3151     let ch = src[offset - 1];
3152     if (ch === '\n') return offset;
3153
3154     while (ch && ch !== '\n') ch = src[offset -= 1];
3155
3156     return offset + 1;
3157   }
3158   /**
3159    * End of indentation, or null if the line's indent level is not more
3160    * than `indent`
3161    *
3162    * @param {string} src
3163    * @param {number} indent
3164    * @param {number} lineStart
3165    * @returns {?number}
3166    */
3167
3168
3169   static endOfBlockIndent(src, indent, lineStart) {
3170     const inEnd = Node.endOfIndent(src, lineStart);
3171
3172     if (inEnd > lineStart + indent) {
3173       return inEnd;
3174     } else {
3175       const wsEnd = Node.endOfWhiteSpace(src, inEnd);
3176       const ch = src[wsEnd];
3177       if (!ch || ch === '\n') return wsEnd;
3178     }
3179
3180     return null;
3181   }
3182
3183   static atBlank(src, offset, endAsBlank) {
3184     const ch = src[offset];
3185     return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch;
3186   }
3187
3188   static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) {
3189     if (!ch || indentDiff < 0) return false;
3190     if (indentDiff > 0) return true;
3191     return indicatorAsIndent && ch === '-';
3192   } // should be at line or string end, or at next non-whitespace char
3193
3194
3195   static normalizeOffset(src, offset) {
3196     const ch = src[offset];
3197     return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node.endOfWhiteSpace(src, offset);
3198   } // fold single newline into space, multiple newlines to N - 1 newlines
3199   // presumes src[offset] === '\n'
3200
3201
3202   static foldNewline(src, offset, indent) {
3203     let inCount = 0;
3204     let error = false;
3205     let fold = '';
3206     let ch = src[offset + 1];
3207
3208     while (ch === ' ' || ch === '\t' || ch === '\n') {
3209       switch (ch) {
3210         case '\n':
3211           inCount = 0;
3212           offset += 1;
3213           fold += '\n';
3214           break;
3215
3216         case '\t':
3217           if (inCount <= indent) error = true;
3218           offset = Node.endOfWhiteSpace(src, offset + 2) - 1;
3219           break;
3220
3221         case ' ':
3222           inCount += 1;
3223           offset += 1;
3224           break;
3225       }
3226
3227       ch = src[offset + 1];
3228     }
3229
3230     if (!fold) fold = ' ';
3231     if (ch && inCount <= indent) error = true;
3232     return {
3233       fold,
3234       offset,
3235       error
3236     };
3237   }
3238
3239   constructor(type, props, context) {
3240     Object.defineProperty(this, 'context', {
3241       value: context || null,
3242       writable: true
3243     });
3244     this.error = null;
3245     this.range = null;
3246     this.valueRange = null;
3247     this.props = props || [];
3248     this.type = type;
3249     this.value = null;
3250   }
3251
3252   getPropValue(idx, key, skipKey) {
3253     if (!this.context) return null;
3254     const {
3255       src
3256     } = this.context;
3257     const prop = this.props[idx];
3258     return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null;
3259   }
3260
3261   get anchor() {
3262     for (let i = 0; i < this.props.length; ++i) {
3263       const anchor = this.getPropValue(i, Char.ANCHOR, true);
3264       if (anchor != null) return anchor;
3265     }
3266
3267     return null;
3268   }
3269
3270   get comment() {
3271     const comments = [];
3272
3273     for (let i = 0; i < this.props.length; ++i) {
3274       const comment = this.getPropValue(i, Char.COMMENT, true);
3275       if (comment != null) comments.push(comment);
3276     }
3277
3278     return comments.length > 0 ? comments.join('\n') : null;
3279   }
3280
3281   commentHasRequiredWhitespace(start) {
3282     const {
3283       src
3284     } = this.context;
3285     if (this.header && start === this.header.end) return false;
3286     if (!this.valueRange) return false;
3287     const {
3288       end
3289     } = this.valueRange;
3290     return start !== end || Node.atBlank(src, end - 1);
3291   }
3292
3293   get hasComment() {
3294     if (this.context) {
3295       const {
3296         src
3297       } = this.context;
3298
3299       for (let i = 0; i < this.props.length; ++i) {
3300         if (src[this.props[i].start] === Char.COMMENT) return true;
3301       }
3302     }
3303
3304     return false;
3305   }
3306
3307   get hasProps() {
3308     if (this.context) {
3309       const {
3310         src
3311       } = this.context;
3312
3313       for (let i = 0; i < this.props.length; ++i) {
3314         if (src[this.props[i].start] !== Char.COMMENT) return true;
3315       }
3316     }
3317
3318     return false;
3319   }
3320
3321   get includesTrailingLines() {
3322     return false;
3323   }
3324
3325   get jsonLike() {
3326     const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE];
3327     return jsonLikeTypes.indexOf(this.type) !== -1;
3328   }
3329
3330   get rangeAsLinePos() {
3331     if (!this.range || !this.context) return undefined;
3332     const start = getLinePos(this.range.start, this.context.root);
3333     if (!start) return undefined;
3334     const end = getLinePos(this.range.end, this.context.root);
3335     return {
3336       start,
3337       end
3338     };
3339   }
3340
3341   get rawValue() {
3342     if (!this.valueRange || !this.context) return null;
3343     const {
3344       start,
3345       end
3346     } = this.valueRange;
3347     return this.context.src.slice(start, end);
3348   }
3349
3350   get tag() {
3351     for (let i = 0; i < this.props.length; ++i) {
3352       const tag = this.getPropValue(i, Char.TAG, false);
3353
3354       if (tag != null) {
3355         if (tag[1] === '<') {
3356           return {
3357             verbatim: tag.slice(2, -1)
3358           };
3359         } else {
3360           // eslint-disable-next-line no-unused-vars
3361           const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/);
3362           return {
3363             handle,
3364             suffix
3365           };
3366         }
3367       }
3368     }
3369
3370     return null;
3371   }
3372
3373   get valueRangeContainsNewline() {
3374     if (!this.valueRange || !this.context) return false;
3375     const {
3376       start,
3377       end
3378     } = this.valueRange;
3379     const {
3380       src
3381     } = this.context;
3382
3383     for (let i = start; i < end; ++i) {
3384       if (src[i] === '\n') return true;
3385     }
3386
3387     return false;
3388   }
3389
3390   parseComment(start) {
3391     const {
3392       src
3393     } = this.context;
3394
3395     if (src[start] === Char.COMMENT) {
3396       const end = Node.endOfLine(src, start + 1);
3397       const commentRange = new Range(start, end);
3398       this.props.push(commentRange);
3399       return end;
3400     }
3401
3402     return start;
3403   }
3404   /**
3405    * Populates the `origStart` and `origEnd` values of all ranges for this
3406    * node. Extended by child classes to handle descendant nodes.
3407    *
3408    * @param {number[]} cr - Positions of dropped CR characters
3409    * @param {number} offset - Starting index of `cr` from the last call
3410    * @returns {number} - The next offset, matching the one found for `origStart`
3411    */
3412
3413
3414   setOrigRanges(cr, offset) {
3415     if (this.range) offset = this.range.setOrigRange(cr, offset);
3416     if (this.valueRange) this.valueRange.setOrigRange(cr, offset);
3417     this.props.forEach(prop => prop.setOrigRange(cr, offset));
3418     return offset;
3419   }
3420
3421   toString() {
3422     const {
3423       context: {
3424         src
3425       },
3426       range,
3427       value
3428     } = this;
3429     if (value != null) return value;
3430     const str = src.slice(range.start, range.end);
3431     return Node.addStringTerminator(src, range.end, str);
3432   }
3433
3434 }
3435
3436 class YAMLError extends Error {
3437   constructor(name, source, message) {
3438     if (!message || !(source instanceof Node)) throw new Error(`Invalid arguments for new ${name}`);
3439     super();
3440     this.name = name;
3441     this.message = message;
3442     this.source = source;
3443   }
3444
3445   makePretty() {
3446     if (!this.source) return;
3447     this.nodeType = this.source.type;
3448     const cst = this.source.context && this.source.context.root;
3449
3450     if (typeof this.offset === 'number') {
3451       this.range = new Range(this.offset, this.offset + 1);
3452       const start = cst && getLinePos(this.offset, cst);
3453
3454       if (start) {
3455         const end = {
3456           line: start.line,
3457           col: start.col + 1
3458         };
3459         this.linePos = {
3460           start,
3461           end
3462         };
3463       }
3464
3465       delete this.offset;
3466     } else {
3467       this.range = this.source.range;
3468       this.linePos = this.source.rangeAsLinePos;
3469     }
3470
3471     if (this.linePos) {
3472       const {
3473         line,
3474         col
3475       } = this.linePos.start;
3476       this.message += ` at line ${line}, column ${col}`;
3477       const ctx = cst && getPrettyContext(this.linePos, cst);
3478       if (ctx) this.message += `:\n\n${ctx}\n`;
3479     }
3480
3481     delete this.source;
3482   }
3483
3484 }
3485
3486 class YAMLReferenceError extends YAMLError {
3487   constructor(source, message) {
3488     super('YAMLReferenceError', source, message);
3489   }
3490
3491 }
3492
3493 class YAMLSemanticError extends YAMLError {
3494   constructor(source, message) {
3495     super('YAMLSemanticError', source, message);
3496   }
3497
3498 }
3499
3500 class YAMLSyntaxError extends YAMLError {
3501   constructor(source, message) {
3502     super('YAMLSyntaxError', source, message);
3503   }
3504
3505 }
3506
3507 class YAMLWarning extends YAMLError {
3508   constructor(source, message) {
3509     super('YAMLWarning', source, message);
3510   }
3511
3512 }
3513
3514 function _defineProperty(obj, key, value) {
3515   if (key in obj) {
3516     Object.defineProperty(obj, key, {
3517       value: value,
3518       enumerable: true,
3519       configurable: true,
3520       writable: true
3521     });
3522   } else {
3523     obj[key] = value;
3524   }
3525
3526   return obj;
3527 }
3528
3529 class PlainValue extends Node {
3530   static endOfLine(src, start, inFlow) {
3531     let ch = src[start];
3532     let offset = start;
3533
3534     while (ch && ch !== '\n') {
3535       if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break;
3536       const next = src[offset + 1];
3537       if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break;
3538       if ((ch === ' ' || ch === '\t') && next === '#') break;
3539       offset += 1;
3540       ch = next;
3541     }
3542
3543     return offset;
3544   }
3545
3546   get strValue() {
3547     if (!this.valueRange || !this.context) return null;
3548     let {
3549       start,
3550       end
3551     } = this.valueRange;
3552     const {
3553       src
3554     } = this.context;
3555     let ch = src[end - 1];
3556
3557     while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1];
3558
3559     let str = '';
3560
3561     for (let i = start; i < end; ++i) {
3562       const ch = src[i];
3563
3564       if (ch === '\n') {
3565         const {
3566           fold,
3567           offset
3568         } = Node.foldNewline(src, i, -1);
3569         str += fold;
3570         i = offset;
3571       } else if (ch === ' ' || ch === '\t') {
3572         // trim trailing whitespace
3573         const wsStart = i;
3574         let next = src[i + 1];
3575
3576         while (i < end && (next === ' ' || next === '\t')) {
3577           i += 1;
3578           next = src[i + 1];
3579         }
3580
3581         if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
3582       } else {
3583         str += ch;
3584       }
3585     }
3586
3587     const ch0 = src[start];
3588
3589     switch (ch0) {
3590       case '\t':
3591         {
3592           const msg = 'Plain value cannot start with a tab character';
3593           const errors = [new YAMLSemanticError(this, msg)];
3594           return {
3595             errors,
3596             str
3597           };
3598         }
3599
3600       case '@':
3601       case '`':
3602         {
3603           const msg = `Plain value cannot start with reserved character ${ch0}`;
3604           const errors = [new YAMLSemanticError(this, msg)];
3605           return {
3606             errors,
3607             str
3608           };
3609         }
3610
3611       default:
3612         return str;
3613     }
3614   }
3615
3616   parseBlockValue(start) {
3617     const {
3618       indent,
3619       inFlow,
3620       src
3621     } = this.context;
3622     let offset = start;
3623     let valueEnd = start;
3624
3625     for (let ch = src[offset]; ch === '\n'; ch = src[offset]) {
3626       if (Node.atDocumentBoundary(src, offset + 1)) break;
3627       const end = Node.endOfBlockIndent(src, indent, offset + 1);
3628       if (end === null || src[end] === '#') break;
3629
3630       if (src[end] === '\n') {
3631         offset = end;
3632       } else {
3633         valueEnd = PlainValue.endOfLine(src, end, inFlow);
3634         offset = valueEnd;
3635       }
3636     }
3637
3638     if (this.valueRange.isEmpty()) this.valueRange.start = start;
3639     this.valueRange.end = valueEnd;
3640     return valueEnd;
3641   }
3642   /**
3643    * Parses a plain value from the source
3644    *
3645    * Accepted forms are:
3646    * ```
3647    * #comment
3648    *
3649    * first line
3650    *
3651    * first line #comment
3652    *
3653    * first line
3654    * block
3655    * lines
3656    *
3657    * #comment
3658    * block
3659    * lines
3660    * ```
3661    * where block lines are empty or have an indent level greater than `indent`.
3662    *
3663    * @param {ParseContext} context
3664    * @param {number} start - Index of first character
3665    * @returns {number} - Index of the character after this scalar, may be `\n`
3666    */
3667
3668
3669   parse(context, start) {
3670     this.context = context;
3671     const {
3672       inFlow,
3673       src
3674     } = context;
3675     let offset = start;
3676     const ch = src[offset];
3677
3678     if (ch && ch !== '#' && ch !== '\n') {
3679       offset = PlainValue.endOfLine(src, start, inFlow);
3680     }
3681
3682     this.valueRange = new Range(start, offset);
3683     offset = Node.endOfWhiteSpace(src, offset);
3684     offset = this.parseComment(offset);
3685
3686     if (!this.hasComment || this.valueRange.isEmpty()) {
3687       offset = this.parseBlockValue(offset);
3688     }
3689
3690     return offset;
3691   }
3692
3693 }
3694
3695 var Char_1 = Char;
3696 var Node_1 = Node;
3697 var PlainValue_1 = PlainValue;
3698 var Range_1 = Range;
3699 var Type_1 = Type;
3700 var YAMLError_1 = YAMLError;
3701 var YAMLReferenceError_1 = YAMLReferenceError;
3702 var YAMLSemanticError_1 = YAMLSemanticError;
3703 var YAMLSyntaxError_1 = YAMLSyntaxError;
3704 var YAMLWarning_1 = YAMLWarning;
3705 var _defineProperty_1 = _defineProperty;
3706 var defaultTagPrefix_1 = defaultTagPrefix;
3707 var defaultTags_1 = defaultTags;
3708 var PlainValueEc8e588e = {
3709   Char: Char_1,
3710   Node: Node_1,
3711   PlainValue: PlainValue_1,
3712   Range: Range_1,
3713   Type: Type_1,
3714   YAMLError: YAMLError_1,
3715   YAMLReferenceError: YAMLReferenceError_1,
3716   YAMLSemanticError: YAMLSemanticError_1,
3717   YAMLSyntaxError: YAMLSyntaxError_1,
3718   YAMLWarning: YAMLWarning_1,
3719   _defineProperty: _defineProperty_1,
3720   defaultTagPrefix: defaultTagPrefix_1,
3721   defaultTags: defaultTags_1
3722 };
3723
3724 class BlankLine extends PlainValueEc8e588e.Node {
3725   constructor() {
3726     super(PlainValueEc8e588e.Type.BLANK_LINE);
3727   }
3728   /* istanbul ignore next */
3729
3730
3731   get includesTrailingLines() {
3732     // This is never called from anywhere, but if it were,
3733     // this is the value it should return.
3734     return true;
3735   }
3736   /**
3737    * Parses a blank line from the source
3738    *
3739    * @param {ParseContext} context
3740    * @param {number} start - Index of first \n character
3741    * @returns {number} - Index of the character after this
3742    */
3743
3744
3745   parse(context, start) {
3746     this.context = context;
3747     this.range = new PlainValueEc8e588e.Range(start, start + 1);
3748     return start + 1;
3749   }
3750
3751 }
3752
3753 class CollectionItem extends PlainValueEc8e588e.Node {
3754   constructor(type, props) {
3755     super(type, props);
3756     this.node = null;
3757   }
3758
3759   get includesTrailingLines() {
3760     return !!this.node && this.node.includesTrailingLines;
3761   }
3762   /**
3763    * @param {ParseContext} context
3764    * @param {number} start - Index of first character
3765    * @returns {number} - Index of the character after this
3766    */
3767
3768
3769   parse(context, start) {
3770     this.context = context;
3771     const {
3772       parseNode,
3773       src
3774     } = context;
3775     let {
3776       atLineStart,
3777       lineStart
3778     } = context;
3779     if (!atLineStart && this.type === PlainValueEc8e588e.Type.SEQ_ITEM) this.error = new PlainValueEc8e588e.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line');
3780     const indent = atLineStart ? start - lineStart : context.indent;
3781     let offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, start + 1);
3782     let ch = src[offset];
3783     const inlineComment = ch === '#';
3784     const comments = [];
3785     let blankLine = null;
3786
3787     while (ch === '\n' || ch === '#') {
3788       if (ch === '#') {
3789         const end = PlainValueEc8e588e.Node.endOfLine(src, offset + 1);
3790         comments.push(new PlainValueEc8e588e.Range(offset, end));
3791         offset = end;
3792       } else {
3793         atLineStart = true;
3794         lineStart = offset + 1;
3795         const wsEnd = PlainValueEc8e588e.Node.endOfWhiteSpace(src, lineStart);
3796
3797         if (src[wsEnd] === '\n' && comments.length === 0) {
3798           blankLine = new BlankLine();
3799           lineStart = blankLine.parse({
3800             src
3801           }, lineStart);
3802         }
3803
3804         offset = PlainValueEc8e588e.Node.endOfIndent(src, lineStart);
3805       }
3806
3807       ch = src[offset];
3808     }
3809
3810     if (PlainValueEc8e588e.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValueEc8e588e.Type.SEQ_ITEM)) {
3811       this.node = parseNode({
3812         atLineStart,
3813         inCollection: false,
3814         indent,
3815         lineStart,
3816         parent: this
3817       }, offset);
3818     } else if (ch && lineStart > start + 1) {
3819       offset = lineStart - 1;
3820     }
3821
3822     if (this.node) {
3823       if (blankLine) {
3824         // Only blank lines preceding non-empty nodes are captured. Note that
3825         // this means that collection item range start indices do not always
3826         // increase monotonically. -- eemeli/yaml#126
3827         const items = context.parent.items || context.parent.contents;
3828         if (items) items.push(blankLine);
3829       }
3830
3831       if (comments.length) Array.prototype.push.apply(this.props, comments);
3832       offset = this.node.range.end;
3833     } else {
3834       if (inlineComment) {
3835         const c = comments[0];
3836         this.props.push(c);
3837         offset = c.end;
3838       } else {
3839         offset = PlainValueEc8e588e.Node.endOfLine(src, start + 1);
3840       }
3841     }
3842
3843     const end = this.node ? this.node.valueRange.end : offset;
3844     this.valueRange = new PlainValueEc8e588e.Range(start, end);
3845     return offset;
3846   }
3847
3848   setOrigRanges(cr, offset) {
3849     offset = super.setOrigRanges(cr, offset);
3850     return this.node ? this.node.setOrigRanges(cr, offset) : offset;
3851   }
3852
3853   toString() {
3854     const {
3855       context: {
3856         src
3857       },
3858       node,
3859       range,
3860       value
3861     } = this;
3862     if (value != null) return value;
3863     const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end);
3864     return PlainValueEc8e588e.Node.addStringTerminator(src, range.end, str);
3865   }
3866
3867 }
3868
3869 class Comment extends PlainValueEc8e588e.Node {
3870   constructor() {
3871     super(PlainValueEc8e588e.Type.COMMENT);
3872   }
3873   /**
3874    * Parses a comment line from the source
3875    *
3876    * @param {ParseContext} context
3877    * @param {number} start - Index of first character
3878    * @returns {number} - Index of the character after this scalar
3879    */
3880
3881
3882   parse(context, start) {
3883     this.context = context;
3884     const offset = this.parseComment(start);
3885     this.range = new PlainValueEc8e588e.Range(start, offset);
3886     return offset;
3887   }
3888
3889 }
3890
3891 function grabCollectionEndComments(node) {
3892   let cnode = node;
3893
3894   while (cnode instanceof CollectionItem) cnode = cnode.node;
3895
3896   if (!(cnode instanceof Collection)) return null;
3897   const len = cnode.items.length;
3898   let ci = -1;
3899
3900   for (let i = len - 1; i >= 0; --i) {
3901     const n = cnode.items[i];
3902
3903     if (n.type === PlainValueEc8e588e.Type.COMMENT) {
3904       // Keep sufficiently indented comments with preceding node
3905       const {
3906         indent,
3907         lineStart
3908       } = n.context;
3909       if (indent > 0 && n.range.start >= lineStart + indent) break;
3910       ci = i;
3911     } else if (n.type === PlainValueEc8e588e.Type.BLANK_LINE) ci = i;else break;
3912   }
3913
3914   if (ci === -1) return null;
3915   const ca = cnode.items.splice(ci, len - ci);
3916   const prevEnd = ca[0].range.start;
3917
3918   while (true) {
3919     cnode.range.end = prevEnd;
3920     if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd;
3921     if (cnode === node) break;
3922     cnode = cnode.context.parent;
3923   }
3924
3925   return ca;
3926 }
3927
3928 class Collection extends PlainValueEc8e588e.Node {
3929   static nextContentHasIndent(src, offset, indent) {
3930     const lineStart = PlainValueEc8e588e.Node.endOfLine(src, offset) + 1;
3931     offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, lineStart);
3932     const ch = src[offset];
3933     if (!ch) return false;
3934     if (offset >= lineStart + indent) return true;
3935     if (ch !== '#' && ch !== '\n') return false;
3936     return Collection.nextContentHasIndent(src, offset, indent);
3937   }
3938
3939   constructor(firstItem) {
3940     super(firstItem.type === PlainValueEc8e588e.Type.SEQ_ITEM ? PlainValueEc8e588e.Type.SEQ : PlainValueEc8e588e.Type.MAP);
3941
3942     for (let i = firstItem.props.length - 1; i >= 0; --i) {
3943       if (firstItem.props[i].start < firstItem.context.lineStart) {
3944         // props on previous line are assumed by the collection
3945         this.props = firstItem.props.slice(0, i + 1);
3946         firstItem.props = firstItem.props.slice(i + 1);
3947         const itemRange = firstItem.props[0] || firstItem.valueRange;
3948         firstItem.range.start = itemRange.start;
3949         break;
3950       }
3951     }
3952
3953     this.items = [firstItem];
3954     const ec = grabCollectionEndComments(firstItem);
3955     if (ec) Array.prototype.push.apply(this.items, ec);
3956   }
3957
3958   get includesTrailingLines() {
3959     return this.items.length > 0;
3960   }
3961   /**
3962    * @param {ParseContext} context
3963    * @param {number} start - Index of first character
3964    * @returns {number} - Index of the character after this
3965    */
3966
3967
3968   parse(context, start) {
3969     this.context = context;
3970     const {
3971       parseNode,
3972       src
3973     } = context; // It's easier to recalculate lineStart here rather than tracking down the
3974     // last context from which to read it -- eemeli/yaml#2
3975
3976     let lineStart = PlainValueEc8e588e.Node.startOfLine(src, start);
3977     const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling
3978     // -- eemeli/yaml#17
3979
3980     firstItem.context.parent = this;
3981     this.valueRange = PlainValueEc8e588e.Range.copy(firstItem.valueRange);
3982     const indent = firstItem.range.start - firstItem.context.lineStart;
3983     let offset = start;
3984     offset = PlainValueEc8e588e.Node.normalizeOffset(src, offset);
3985     let ch = src[offset];
3986     let atLineStart = PlainValueEc8e588e.Node.endOfWhiteSpace(src, lineStart) === offset;
3987     let prevIncludesTrailingLines = false;
3988
3989     while (ch) {
3990       while (ch === '\n' || ch === '#') {
3991         if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) {
3992           const blankLine = new BlankLine();
3993           offset = blankLine.parse({
3994             src
3995           }, offset);
3996           this.valueRange.end = offset;
3997
3998           if (offset >= src.length) {
3999             ch = null;
4000             break;
4001           }
4002
4003           this.items.push(blankLine);
4004           offset -= 1; // blankLine.parse() consumes terminal newline
4005         } else if (ch === '#') {
4006           if (offset < lineStart + indent && !Collection.nextContentHasIndent(src, offset, indent)) {
4007             return offset;
4008           }
4009
4010           const comment = new Comment();
4011           offset = comment.parse({
4012             indent,
4013             lineStart,
4014             src
4015           }, offset);
4016           this.items.push(comment);
4017           this.valueRange.end = offset;
4018
4019           if (offset >= src.length) {
4020             ch = null;
4021             break;
4022           }
4023         }
4024
4025         lineStart = offset + 1;
4026         offset = PlainValueEc8e588e.Node.endOfIndent(src, lineStart);
4027
4028         if (PlainValueEc8e588e.Node.atBlank(src, offset)) {
4029           const wsEnd = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
4030           const next = src[wsEnd];
4031
4032           if (!next || next === '\n' || next === '#') {
4033             offset = wsEnd;
4034           }
4035         }
4036
4037         ch = src[offset];
4038         atLineStart = true;
4039       }
4040
4041       if (!ch) {
4042         break;
4043       }
4044
4045       if (offset !== lineStart + indent && (atLineStart || ch !== ':')) {
4046         if (offset < lineStart + indent) {
4047           if (lineStart > start) offset = lineStart;
4048           break;
4049         } else if (!this.error) {
4050           const msg = 'All collection items must start at the same column';
4051           this.error = new PlainValueEc8e588e.YAMLSyntaxError(this, msg);
4052         }
4053       }
4054
4055       if (firstItem.type === PlainValueEc8e588e.Type.SEQ_ITEM) {
4056         if (ch !== '-') {
4057           if (lineStart > start) offset = lineStart;
4058           break;
4059         }
4060       } else if (ch === '-' && !this.error) {
4061         // map key may start with -, as long as it's followed by a non-whitespace char
4062         const next = src[offset + 1];
4063
4064         if (!next || next === '\n' || next === '\t' || next === ' ') {
4065           const msg = 'A collection cannot be both a mapping and a sequence';
4066           this.error = new PlainValueEc8e588e.YAMLSyntaxError(this, msg);
4067         }
4068       }
4069
4070       const node = parseNode({
4071         atLineStart,
4072         inCollection: true,
4073         indent,
4074         lineStart,
4075         parent: this
4076       }, offset);
4077       if (!node) return offset; // at next document start
4078
4079       this.items.push(node);
4080       this.valueRange.end = node.valueRange.end;
4081       offset = PlainValueEc8e588e.Node.normalizeOffset(src, node.range.end);
4082       ch = src[offset];
4083       atLineStart = false;
4084       prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range
4085       // has advanced to check the current line's indentation level
4086       // -- eemeli/yaml#10 & eemeli/yaml#38
4087
4088       if (ch) {
4089         let ls = offset - 1;
4090         let prev = src[ls];
4091
4092         while (prev === ' ' || prev === '\t') prev = src[--ls];
4093
4094         if (prev === '\n') {
4095           lineStart = ls + 1;
4096           atLineStart = true;
4097         }
4098       }
4099
4100       const ec = grabCollectionEndComments(node);
4101       if (ec) Array.prototype.push.apply(this.items, ec);
4102     }
4103
4104     return offset;
4105   }
4106
4107   setOrigRanges(cr, offset) {
4108     offset = super.setOrigRanges(cr, offset);
4109     this.items.forEach(node => {
4110       offset = node.setOrigRanges(cr, offset);
4111     });
4112     return offset;
4113   }
4114
4115   toString() {
4116     const {
4117       context: {
4118         src
4119       },
4120       items,
4121       range,
4122       value
4123     } = this;
4124     if (value != null) return value;
4125     let str = src.slice(range.start, items[0].range.start) + String(items[0]);
4126
4127     for (let i = 1; i < items.length; ++i) {
4128       const item = items[i];
4129       const {
4130         atLineStart,
4131         indent
4132       } = item.context;
4133       if (atLineStart) for (let i = 0; i < indent; ++i) str += ' ';
4134       str += String(item);
4135     }
4136
4137     return PlainValueEc8e588e.Node.addStringTerminator(src, range.end, str);
4138   }
4139
4140 }
4141
4142 class Directive extends PlainValueEc8e588e.Node {
4143   constructor() {
4144     super(PlainValueEc8e588e.Type.DIRECTIVE);
4145     this.name = null;
4146   }
4147
4148   get parameters() {
4149     const raw = this.rawValue;
4150     return raw ? raw.trim().split(/[ \t]+/) : [];
4151   }
4152
4153   parseName(start) {
4154     const {
4155       src
4156     } = this.context;
4157     let offset = start;
4158     let ch = src[offset];
4159
4160     while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1];
4161
4162     this.name = src.slice(start, offset);
4163     return offset;
4164   }
4165
4166   parseParameters(start) {
4167     const {
4168       src
4169     } = this.context;
4170     let offset = start;
4171     let ch = src[offset];
4172
4173     while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1];
4174
4175     this.valueRange = new PlainValueEc8e588e.Range(start, offset);
4176     return offset;
4177   }
4178
4179   parse(context, start) {
4180     this.context = context;
4181     let offset = this.parseName(start + 1);
4182     offset = this.parseParameters(offset);
4183     offset = this.parseComment(offset);
4184     this.range = new PlainValueEc8e588e.Range(start, offset);
4185     return offset;
4186   }
4187
4188 }
4189
4190 class Document extends PlainValueEc8e588e.Node {
4191   static startCommentOrEndBlankLine(src, start) {
4192     const offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, start);
4193     const ch = src[offset];
4194     return ch === '#' || ch === '\n' ? offset : start;
4195   }
4196
4197   constructor() {
4198     super(PlainValueEc8e588e.Type.DOCUMENT);
4199     this.directives = null;
4200     this.contents = null;
4201     this.directivesEndMarker = null;
4202     this.documentEndMarker = null;
4203   }
4204
4205   parseDirectives(start) {
4206     const {
4207       src
4208     } = this.context;
4209     this.directives = [];
4210     let atLineStart = true;
4211     let hasDirectives = false;
4212     let offset = start;
4213
4214     while (!PlainValueEc8e588e.Node.atDocumentBoundary(src, offset, PlainValueEc8e588e.Char.DIRECTIVES_END)) {
4215       offset = Document.startCommentOrEndBlankLine(src, offset);
4216
4217       switch (src[offset]) {
4218         case '\n':
4219           if (atLineStart) {
4220             const blankLine = new BlankLine();
4221             offset = blankLine.parse({
4222               src
4223             }, offset);
4224
4225             if (offset < src.length) {
4226               this.directives.push(blankLine);
4227             }
4228           } else {
4229             offset += 1;
4230             atLineStart = true;
4231           }
4232
4233           break;
4234
4235         case '#':
4236           {
4237             const comment = new Comment();
4238             offset = comment.parse({
4239               src
4240             }, offset);
4241             this.directives.push(comment);
4242             atLineStart = false;
4243           }
4244           break;
4245
4246         case '%':
4247           {
4248             const directive = new Directive();
4249             offset = directive.parse({
4250               parent: this,
4251               src
4252             }, offset);
4253             this.directives.push(directive);
4254             hasDirectives = true;
4255             atLineStart = false;
4256           }
4257           break;
4258
4259         default:
4260           if (hasDirectives) {
4261             this.error = new PlainValueEc8e588e.YAMLSemanticError(this, 'Missing directives-end indicator line');
4262           } else if (this.directives.length > 0) {
4263             this.contents = this.directives;
4264             this.directives = [];
4265           }
4266
4267           return offset;
4268       }
4269     }
4270
4271     if (src[offset]) {
4272       this.directivesEndMarker = new PlainValueEc8e588e.Range(offset, offset + 3);
4273       return offset + 3;
4274     }
4275
4276     if (hasDirectives) {
4277       this.error = new PlainValueEc8e588e.YAMLSemanticError(this, 'Missing directives-end indicator line');
4278     } else if (this.directives.length > 0) {
4279       this.contents = this.directives;
4280       this.directives = [];
4281     }
4282
4283     return offset;
4284   }
4285
4286   parseContents(start) {
4287     const {
4288       parseNode,
4289       src
4290     } = this.context;
4291     if (!this.contents) this.contents = [];
4292     let lineStart = start;
4293
4294     while (src[lineStart - 1] === '-') lineStart -= 1;
4295
4296     let offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, start);
4297     let atLineStart = lineStart === start;
4298     this.valueRange = new PlainValueEc8e588e.Range(offset);
4299
4300     while (!PlainValueEc8e588e.Node.atDocumentBoundary(src, offset, PlainValueEc8e588e.Char.DOCUMENT_END)) {
4301       switch (src[offset]) {
4302         case '\n':
4303           if (atLineStart) {
4304             const blankLine = new BlankLine();
4305             offset = blankLine.parse({
4306               src
4307             }, offset);
4308
4309             if (offset < src.length) {
4310               this.contents.push(blankLine);
4311             }
4312           } else {
4313             offset += 1;
4314             atLineStart = true;
4315           }
4316
4317           lineStart = offset;
4318           break;
4319
4320         case '#':
4321           {
4322             const comment = new Comment();
4323             offset = comment.parse({
4324               src
4325             }, offset);
4326             this.contents.push(comment);
4327             atLineStart = false;
4328           }
4329           break;
4330
4331         default:
4332           {
4333             const iEnd = PlainValueEc8e588e.Node.endOfIndent(src, offset);
4334             const context = {
4335               atLineStart,
4336               indent: -1,
4337               inFlow: false,
4338               inCollection: false,
4339               lineStart,
4340               parent: this
4341             };
4342             const node = parseNode(context, iEnd);
4343             if (!node) return this.valueRange.end = iEnd; // at next document start
4344
4345             this.contents.push(node);
4346             offset = node.range.end;
4347             atLineStart = false;
4348             const ec = grabCollectionEndComments(node);
4349             if (ec) Array.prototype.push.apply(this.contents, ec);
4350           }
4351       }
4352
4353       offset = Document.startCommentOrEndBlankLine(src, offset);
4354     }
4355
4356     this.valueRange.end = offset;
4357
4358     if (src[offset]) {
4359       this.documentEndMarker = new PlainValueEc8e588e.Range(offset, offset + 3);
4360       offset += 3;
4361
4362       if (src[offset]) {
4363         offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
4364
4365         if (src[offset] === '#') {
4366           const comment = new Comment();
4367           offset = comment.parse({
4368             src
4369           }, offset);
4370           this.contents.push(comment);
4371         }
4372
4373         switch (src[offset]) {
4374           case '\n':
4375             offset += 1;
4376             break;
4377
4378           case undefined:
4379             break;
4380
4381           default:
4382             this.error = new PlainValueEc8e588e.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix');
4383         }
4384       }
4385     }
4386
4387     return offset;
4388   }
4389   /**
4390    * @param {ParseContext} context
4391    * @param {number} start - Index of first character
4392    * @returns {number} - Index of the character after this
4393    */
4394
4395
4396   parse(context, start) {
4397     context.root = this;
4398     this.context = context;
4399     const {
4400       src
4401     } = context;
4402     let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM
4403
4404     offset = this.parseDirectives(offset);
4405     offset = this.parseContents(offset);
4406     return offset;
4407   }
4408
4409   setOrigRanges(cr, offset) {
4410     offset = super.setOrigRanges(cr, offset);
4411     this.directives.forEach(node => {
4412       offset = node.setOrigRanges(cr, offset);
4413     });
4414     if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset);
4415     this.contents.forEach(node => {
4416       offset = node.setOrigRanges(cr, offset);
4417     });
4418     if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset);
4419     return offset;
4420   }
4421
4422   toString() {
4423     const {
4424       contents,
4425       directives,
4426       value
4427     } = this;
4428     if (value != null) return value;
4429     let str = directives.join('');
4430
4431     if (contents.length > 0) {
4432       if (directives.length > 0 || contents[0].type === PlainValueEc8e588e.Type.COMMENT) str += '---\n';
4433       str += contents.join('');
4434     }
4435
4436     if (str[str.length - 1] !== '\n') str += '\n';
4437     return str;
4438   }
4439
4440 }
4441
4442 class Alias extends PlainValueEc8e588e.Node {
4443   /**
4444    * Parses an *alias from the source
4445    *
4446    * @param {ParseContext} context
4447    * @param {number} start - Index of first character
4448    * @returns {number} - Index of the character after this scalar
4449    */
4450   parse(context, start) {
4451     this.context = context;
4452     const {
4453       src
4454     } = context;
4455     let offset = PlainValueEc8e588e.Node.endOfIdentifier(src, start + 1);
4456     this.valueRange = new PlainValueEc8e588e.Range(start + 1, offset);
4457     offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
4458     offset = this.parseComment(offset);
4459     return offset;
4460   }
4461
4462 }
4463
4464 const Chomp = {
4465   CLIP: 'CLIP',
4466   KEEP: 'KEEP',
4467   STRIP: 'STRIP'
4468 };
4469
4470 class BlockValue extends PlainValueEc8e588e.Node {
4471   constructor(type, props) {
4472     super(type, props);
4473     this.blockIndent = null;
4474     this.chomping = Chomp.CLIP;
4475     this.header = null;
4476   }
4477
4478   get includesTrailingLines() {
4479     return this.chomping === Chomp.KEEP;
4480   }
4481
4482   get strValue() {
4483     if (!this.valueRange || !this.context) return null;
4484     let {
4485       start,
4486       end
4487     } = this.valueRange;
4488     const {
4489       indent,
4490       src
4491     } = this.context;
4492     if (this.valueRange.isEmpty()) return '';
4493     let lastNewLine = null;
4494     let ch = src[end - 1];
4495
4496     while (ch === '\n' || ch === '\t' || ch === ' ') {
4497       end -= 1;
4498
4499       if (end <= start) {
4500         if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens
4501       }
4502
4503       if (ch === '\n') lastNewLine = end;
4504       ch = src[end - 1];
4505     }
4506
4507     let keepStart = end + 1;
4508
4509     if (lastNewLine) {
4510       if (this.chomping === Chomp.KEEP) {
4511         keepStart = lastNewLine;
4512         end = this.valueRange.end;
4513       } else {
4514         end = lastNewLine;
4515       }
4516     }
4517
4518     const bi = indent + this.blockIndent;
4519     const folded = this.type === PlainValueEc8e588e.Type.BLOCK_FOLDED;
4520     let atStart = true;
4521     let str = '';
4522     let sep = '';
4523     let prevMoreIndented = false;
4524
4525     for (let i = start; i < end; ++i) {
4526       for (let j = 0; j < bi; ++j) {
4527         if (src[i] !== ' ') break;
4528         i += 1;
4529       }
4530
4531       const ch = src[i];
4532
4533       if (ch === '\n') {
4534         if (sep === '\n') str += '\n';else sep = '\n';
4535       } else {
4536         const lineEnd = PlainValueEc8e588e.Node.endOfLine(src, i);
4537         const line = src.slice(i, lineEnd);
4538         i = lineEnd;
4539
4540         if (folded && (ch === ' ' || ch === '\t') && i < keepStart) {
4541           if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n';
4542           str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '')
4543
4544           sep = lineEnd < end && src[lineEnd] || '';
4545           prevMoreIndented = true;
4546         } else {
4547           str += sep + line;
4548           sep = folded && i < keepStart ? ' ' : '\n';
4549           prevMoreIndented = false;
4550         }
4551
4552         if (atStart && line !== '') atStart = false;
4553       }
4554     }
4555
4556     return this.chomping === Chomp.STRIP ? str : str + '\n';
4557   }
4558
4559   parseBlockHeader(start) {
4560     const {
4561       src
4562     } = this.context;
4563     let offset = start + 1;
4564     let bi = '';
4565
4566     while (true) {
4567       const ch = src[offset];
4568
4569       switch (ch) {
4570         case '-':
4571           this.chomping = Chomp.STRIP;
4572           break;
4573
4574         case '+':
4575           this.chomping = Chomp.KEEP;
4576           break;
4577
4578         case '0':
4579         case '1':
4580         case '2':
4581         case '3':
4582         case '4':
4583         case '5':
4584         case '6':
4585         case '7':
4586         case '8':
4587         case '9':
4588           bi += ch;
4589           break;
4590
4591         default:
4592           this.blockIndent = Number(bi) || null;
4593           this.header = new PlainValueEc8e588e.Range(start, offset);
4594           return offset;
4595       }
4596
4597       offset += 1;
4598     }
4599   }
4600
4601   parseBlockValue(start) {
4602     const {
4603       indent,
4604       src
4605     } = this.context;
4606     const explicit = !!this.blockIndent;
4607     let offset = start;
4608     let valueEnd = start;
4609     let minBlockIndent = 1;
4610
4611     for (let ch = src[offset]; ch === '\n'; ch = src[offset]) {
4612       offset += 1;
4613       if (PlainValueEc8e588e.Node.atDocumentBoundary(src, offset)) break;
4614       const end = PlainValueEc8e588e.Node.endOfBlockIndent(src, indent, offset); // should not include tab?
4615
4616       if (end === null) break;
4617       const ch = src[end];
4618       const lineIndent = end - (offset + indent);
4619
4620       if (!this.blockIndent) {
4621         // no explicit block indent, none yet detected
4622         if (src[end] !== '\n') {
4623           // first line with non-whitespace content
4624           if (lineIndent < minBlockIndent) {
4625             const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
4626             this.error = new PlainValueEc8e588e.YAMLSemanticError(this, msg);
4627           }
4628
4629           this.blockIndent = lineIndent;
4630         } else if (lineIndent > minBlockIndent) {
4631           // empty line with more whitespace
4632           minBlockIndent = lineIndent;
4633         }
4634       } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) {
4635         if (src[end] === '#') break;
4636
4637         if (!this.error) {
4638           const src = explicit ? 'explicit indentation indicator' : 'first line';
4639           const msg = `Block scalars must not be less indented than their ${src}`;
4640           this.error = new PlainValueEc8e588e.YAMLSemanticError(this, msg);
4641         }
4642       }
4643
4644       if (src[end] === '\n') {
4645         offset = end;
4646       } else {
4647         offset = valueEnd = PlainValueEc8e588e.Node.endOfLine(src, end);
4648       }
4649     }
4650
4651     if (this.chomping !== Chomp.KEEP) {
4652       offset = src[valueEnd] ? valueEnd + 1 : valueEnd;
4653     }
4654
4655     this.valueRange = new PlainValueEc8e588e.Range(start + 1, offset);
4656     return offset;
4657   }
4658   /**
4659    * Parses a block value from the source
4660    *
4661    * Accepted forms are:
4662    * ```
4663    * BS
4664    * block
4665    * lines
4666    *
4667    * BS #comment
4668    * block
4669    * lines
4670    * ```
4671    * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines
4672    * are empty or have an indent level greater than `indent`.
4673    *
4674    * @param {ParseContext} context
4675    * @param {number} start - Index of first character
4676    * @returns {number} - Index of the character after this block
4677    */
4678
4679
4680   parse(context, start) {
4681     this.context = context;
4682     const {
4683       src
4684     } = context;
4685     let offset = this.parseBlockHeader(start);
4686     offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
4687     offset = this.parseComment(offset);
4688     offset = this.parseBlockValue(offset);
4689     return offset;
4690   }
4691
4692   setOrigRanges(cr, offset) {
4693     offset = super.setOrigRanges(cr, offset);
4694     return this.header ? this.header.setOrigRange(cr, offset) : offset;
4695   }
4696
4697 }
4698
4699 class FlowCollection extends PlainValueEc8e588e.Node {
4700   constructor(type, props) {
4701     super(type, props);
4702     this.items = null;
4703   }
4704
4705   prevNodeIsJsonLike(idx = this.items.length) {
4706     const node = this.items[idx - 1];
4707     return !!node && (node.jsonLike || node.type === PlainValueEc8e588e.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1));
4708   }
4709   /**
4710    * @param {ParseContext} context
4711    * @param {number} start - Index of first character
4712    * @returns {number} - Index of the character after this
4713    */
4714
4715
4716   parse(context, start) {
4717     this.context = context;
4718     const {
4719       parseNode,
4720       src
4721     } = context;
4722     let {
4723       indent,
4724       lineStart
4725     } = context;
4726     let char = src[start]; // { or [
4727
4728     this.items = [{
4729       char,
4730       offset: start
4731     }];
4732     let offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, start + 1);
4733     char = src[offset];
4734
4735     while (char && char !== ']' && char !== '}') {
4736       switch (char) {
4737         case '\n':
4738           {
4739             lineStart = offset + 1;
4740             const wsEnd = PlainValueEc8e588e.Node.endOfWhiteSpace(src, lineStart);
4741
4742             if (src[wsEnd] === '\n') {
4743               const blankLine = new BlankLine();
4744               lineStart = blankLine.parse({
4745                 src
4746               }, lineStart);
4747               this.items.push(blankLine);
4748             }
4749
4750             offset = PlainValueEc8e588e.Node.endOfIndent(src, lineStart);
4751
4752             if (offset <= lineStart + indent) {
4753               char = src[offset];
4754
4755               if (offset < lineStart + indent || char !== ']' && char !== '}') {
4756                 const msg = 'Insufficient indentation in flow collection';
4757                 this.error = new PlainValueEc8e588e.YAMLSemanticError(this, msg);
4758               }
4759             }
4760           }
4761           break;
4762
4763         case ',':
4764           {
4765             this.items.push({
4766               char,
4767               offset
4768             });
4769             offset += 1;
4770           }
4771           break;
4772
4773         case '#':
4774           {
4775             const comment = new Comment();
4776             offset = comment.parse({
4777               src
4778             }, offset);
4779             this.items.push(comment);
4780           }
4781           break;
4782
4783         case '?':
4784         case ':':
4785           {
4786             const next = src[offset + 1];
4787
4788             if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace
4789             char === ':' && this.prevNodeIsJsonLike()) {
4790               this.items.push({
4791                 char,
4792                 offset
4793               });
4794               offset += 1;
4795               break;
4796             }
4797           }
4798         // fallthrough
4799
4800         default:
4801           {
4802             const node = parseNode({
4803               atLineStart: false,
4804               inCollection: false,
4805               inFlow: true,
4806               indent: -1,
4807               lineStart,
4808               parent: this
4809             }, offset);
4810
4811             if (!node) {
4812               // at next document start
4813               this.valueRange = new PlainValueEc8e588e.Range(start, offset);
4814               return offset;
4815             }
4816
4817             this.items.push(node);
4818             offset = PlainValueEc8e588e.Node.normalizeOffset(src, node.range.end);
4819           }
4820       }
4821
4822       offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
4823       char = src[offset];
4824     }
4825
4826     this.valueRange = new PlainValueEc8e588e.Range(start, offset + 1);
4827
4828     if (char) {
4829       this.items.push({
4830         char,
4831         offset
4832       });
4833       offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset + 1);
4834       offset = this.parseComment(offset);
4835     }
4836
4837     return offset;
4838   }
4839
4840   setOrigRanges(cr, offset) {
4841     offset = super.setOrigRanges(cr, offset);
4842     this.items.forEach(node => {
4843       if (node instanceof PlainValueEc8e588e.Node) {
4844         offset = node.setOrigRanges(cr, offset);
4845       } else if (cr.length === 0) {
4846         node.origOffset = node.offset;
4847       } else {
4848         let i = offset;
4849
4850         while (i < cr.length) {
4851           if (cr[i] > node.offset) break;else ++i;
4852         }
4853
4854         node.origOffset = node.offset + i;
4855         offset = i;
4856       }
4857     });
4858     return offset;
4859   }
4860
4861   toString() {
4862     const {
4863       context: {
4864         src
4865       },
4866       items,
4867       range,
4868       value
4869     } = this;
4870     if (value != null) return value;
4871     const nodes = items.filter(item => item instanceof PlainValueEc8e588e.Node);
4872     let str = '';
4873     let prevEnd = range.start;
4874     nodes.forEach(node => {
4875       const prefix = src.slice(prevEnd, node.range.start);
4876       prevEnd = node.range.end;
4877       str += prefix + String(node);
4878
4879       if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') {
4880         // Comment range does not include the terminal newline, but its
4881         // stringified value does. Without this fix, newlines at comment ends
4882         // get duplicated.
4883         prevEnd += 1;
4884       }
4885     });
4886     str += src.slice(prevEnd, range.end);
4887     return PlainValueEc8e588e.Node.addStringTerminator(src, range.end, str);
4888   }
4889
4890 }
4891
4892 class QuoteDouble extends PlainValueEc8e588e.Node {
4893   static endOfQuote(src, offset) {
4894     let ch = src[offset];
4895
4896     while (ch && ch !== '"') {
4897       offset += ch === '\\' ? 2 : 1;
4898       ch = src[offset];
4899     }
4900
4901     return offset + 1;
4902   }
4903   /**
4904    * @returns {string | { str: string, errors: YAMLSyntaxError[] }}
4905    */
4906
4907
4908   get strValue() {
4909     if (!this.valueRange || !this.context) return null;
4910     const errors = [];
4911     const {
4912       start,
4913       end
4914     } = this.valueRange;
4915     const {
4916       indent,
4917       src
4918     } = this.context;
4919     if (src[end - 1] !== '"') errors.push(new PlainValueEc8e588e.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by
4920     // escaped backslashes; also, this should be faster.
4921
4922     let str = '';
4923
4924     for (let i = start + 1; i < end - 1; ++i) {
4925       const ch = src[i];
4926
4927       if (ch === '\n') {
4928         if (PlainValueEc8e588e.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValueEc8e588e.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
4929         const {
4930           fold,
4931           offset,
4932           error
4933         } = PlainValueEc8e588e.Node.foldNewline(src, i, indent);
4934         str += fold;
4935         i = offset;
4936         if (error) errors.push(new PlainValueEc8e588e.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented'));
4937       } else if (ch === '\\') {
4938         i += 1;
4939
4940         switch (src[i]) {
4941           case '0':
4942             str += '\0';
4943             break;
4944           // null character
4945
4946           case 'a':
4947             str += '\x07';
4948             break;
4949           // bell character
4950
4951           case 'b':
4952             str += '\b';
4953             break;
4954           // backspace
4955
4956           case 'e':
4957             str += '\x1b';
4958             break;
4959           // escape character
4960
4961           case 'f':
4962             str += '\f';
4963             break;
4964           // form feed
4965
4966           case 'n':
4967             str += '\n';
4968             break;
4969           // line feed
4970
4971           case 'r':
4972             str += '\r';
4973             break;
4974           // carriage return
4975
4976           case 't':
4977             str += '\t';
4978             break;
4979           // horizontal tab
4980
4981           case 'v':
4982             str += '\v';
4983             break;
4984           // vertical tab
4985
4986           case 'N':
4987             str += '\u0085';
4988             break;
4989           // Unicode next line
4990
4991           case '_':
4992             str += '\u00a0';
4993             break;
4994           // Unicode non-breaking space
4995
4996           case 'L':
4997             str += '\u2028';
4998             break;
4999           // Unicode line separator
5000
5001           case 'P':
5002             str += '\u2029';
5003             break;
5004           // Unicode paragraph separator
5005
5006           case ' ':
5007             str += ' ';
5008             break;
5009
5010           case '"':
5011             str += '"';
5012             break;
5013
5014           case '/':
5015             str += '/';
5016             break;
5017
5018           case '\\':
5019             str += '\\';
5020             break;
5021
5022           case '\t':
5023             str += '\t';
5024             break;
5025
5026           case 'x':
5027             str += this.parseCharCode(i + 1, 2, errors);
5028             i += 2;
5029             break;
5030
5031           case 'u':
5032             str += this.parseCharCode(i + 1, 4, errors);
5033             i += 4;
5034             break;
5035
5036           case 'U':
5037             str += this.parseCharCode(i + 1, 8, errors);
5038             i += 8;
5039             break;
5040
5041           case '\n':
5042             // skip escaped newlines, but still trim the following line
5043             while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1;
5044
5045             break;
5046
5047           default:
5048             errors.push(new PlainValueEc8e588e.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`));
5049             str += '\\' + src[i];
5050         }
5051       } else if (ch === ' ' || ch === '\t') {
5052         // trim trailing whitespace
5053         const wsStart = i;
5054         let next = src[i + 1];
5055
5056         while (next === ' ' || next === '\t') {
5057           i += 1;
5058           next = src[i + 1];
5059         }
5060
5061         if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
5062       } else {
5063         str += ch;
5064       }
5065     }
5066
5067     return errors.length > 0 ? {
5068       errors,
5069       str
5070     } : str;
5071   }
5072
5073   parseCharCode(offset, length, errors) {
5074     const {
5075       src
5076     } = this.context;
5077     const cc = src.substr(offset, length);
5078     const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
5079     const code = ok ? parseInt(cc, 16) : NaN;
5080
5081     if (isNaN(code)) {
5082       errors.push(new PlainValueEc8e588e.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`));
5083       return src.substr(offset - 2, length + 2);
5084     }
5085
5086     return String.fromCodePoint(code);
5087   }
5088   /**
5089    * Parses a "double quoted" value from the source
5090    *
5091    * @param {ParseContext} context
5092    * @param {number} start - Index of first character
5093    * @returns {number} - Index of the character after this scalar
5094    */
5095
5096
5097   parse(context, start) {
5098     this.context = context;
5099     const {
5100       src
5101     } = context;
5102     let offset = QuoteDouble.endOfQuote(src, start + 1);
5103     this.valueRange = new PlainValueEc8e588e.Range(start, offset);
5104     offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
5105     offset = this.parseComment(offset);
5106     return offset;
5107   }
5108
5109 }
5110
5111 class QuoteSingle extends PlainValueEc8e588e.Node {
5112   static endOfQuote(src, offset) {
5113     let ch = src[offset];
5114
5115     while (ch) {
5116       if (ch === "'") {
5117         if (src[offset + 1] !== "'") break;
5118         ch = src[offset += 2];
5119       } else {
5120         ch = src[offset += 1];
5121       }
5122     }
5123
5124     return offset + 1;
5125   }
5126   /**
5127    * @returns {string | { str: string, errors: YAMLSyntaxError[] }}
5128    */
5129
5130
5131   get strValue() {
5132     if (!this.valueRange || !this.context) return null;
5133     const errors = [];
5134     const {
5135       start,
5136       end
5137     } = this.valueRange;
5138     const {
5139       indent,
5140       src
5141     } = this.context;
5142     if (src[end - 1] !== "'") errors.push(new PlainValueEc8e588e.YAMLSyntaxError(this, "Missing closing 'quote"));
5143     let str = '';
5144
5145     for (let i = start + 1; i < end - 1; ++i) {
5146       const ch = src[i];
5147
5148       if (ch === '\n') {
5149         if (PlainValueEc8e588e.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValueEc8e588e.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
5150         const {
5151           fold,
5152           offset,
5153           error
5154         } = PlainValueEc8e588e.Node.foldNewline(src, i, indent);
5155         str += fold;
5156         i = offset;
5157         if (error) errors.push(new PlainValueEc8e588e.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented'));
5158       } else if (ch === "'") {
5159         str += ch;
5160         i += 1;
5161         if (src[i] !== "'") errors.push(new PlainValueEc8e588e.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.'));
5162       } else if (ch === ' ' || ch === '\t') {
5163         // trim trailing whitespace
5164         const wsStart = i;
5165         let next = src[i + 1];
5166
5167         while (next === ' ' || next === '\t') {
5168           i += 1;
5169           next = src[i + 1];
5170         }
5171
5172         if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
5173       } else {
5174         str += ch;
5175       }
5176     }
5177
5178     return errors.length > 0 ? {
5179       errors,
5180       str
5181     } : str;
5182   }
5183   /**
5184    * Parses a 'single quoted' value from the source
5185    *
5186    * @param {ParseContext} context
5187    * @param {number} start - Index of first character
5188    * @returns {number} - Index of the character after this scalar
5189    */
5190
5191
5192   parse(context, start) {
5193     this.context = context;
5194     const {
5195       src
5196     } = context;
5197     let offset = QuoteSingle.endOfQuote(src, start + 1);
5198     this.valueRange = new PlainValueEc8e588e.Range(start, offset);
5199     offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
5200     offset = this.parseComment(offset);
5201     return offset;
5202   }
5203
5204 }
5205
5206 function createNewNode(type, props) {
5207   switch (type) {
5208     case PlainValueEc8e588e.Type.ALIAS:
5209       return new Alias(type, props);
5210
5211     case PlainValueEc8e588e.Type.BLOCK_FOLDED:
5212     case PlainValueEc8e588e.Type.BLOCK_LITERAL:
5213       return new BlockValue(type, props);
5214
5215     case PlainValueEc8e588e.Type.FLOW_MAP:
5216     case PlainValueEc8e588e.Type.FLOW_SEQ:
5217       return new FlowCollection(type, props);
5218
5219     case PlainValueEc8e588e.Type.MAP_KEY:
5220     case PlainValueEc8e588e.Type.MAP_VALUE:
5221     case PlainValueEc8e588e.Type.SEQ_ITEM:
5222       return new CollectionItem(type, props);
5223
5224     case PlainValueEc8e588e.Type.COMMENT:
5225     case PlainValueEc8e588e.Type.PLAIN:
5226       return new PlainValueEc8e588e.PlainValue(type, props);
5227
5228     case PlainValueEc8e588e.Type.QUOTE_DOUBLE:
5229       return new QuoteDouble(type, props);
5230
5231     case PlainValueEc8e588e.Type.QUOTE_SINGLE:
5232       return new QuoteSingle(type, props);
5233
5234     /* istanbul ignore next */
5235
5236     default:
5237       return null;
5238     // should never happen
5239   }
5240 }
5241 /**
5242  * @param {boolean} atLineStart - Node starts at beginning of line
5243  * @param {boolean} inFlow - true if currently in a flow context
5244  * @param {boolean} inCollection - true if currently in a collection context
5245  * @param {number} indent - Current level of indentation
5246  * @param {number} lineStart - Start of the current line
5247  * @param {Node} parent - The parent of the node
5248  * @param {string} src - Source of the YAML document
5249  */
5250
5251
5252 class ParseContext {
5253   static parseType(src, offset, inFlow) {
5254     switch (src[offset]) {
5255       case '*':
5256         return PlainValueEc8e588e.Type.ALIAS;
5257
5258       case '>':
5259         return PlainValueEc8e588e.Type.BLOCK_FOLDED;
5260
5261       case '|':
5262         return PlainValueEc8e588e.Type.BLOCK_LITERAL;
5263
5264       case '{':
5265         return PlainValueEc8e588e.Type.FLOW_MAP;
5266
5267       case '[':
5268         return PlainValueEc8e588e.Type.FLOW_SEQ;
5269
5270       case '?':
5271         return !inFlow && PlainValueEc8e588e.Node.atBlank(src, offset + 1, true) ? PlainValueEc8e588e.Type.MAP_KEY : PlainValueEc8e588e.Type.PLAIN;
5272
5273       case ':':
5274         return !inFlow && PlainValueEc8e588e.Node.atBlank(src, offset + 1, true) ? PlainValueEc8e588e.Type.MAP_VALUE : PlainValueEc8e588e.Type.PLAIN;
5275
5276       case '-':
5277         return !inFlow && PlainValueEc8e588e.Node.atBlank(src, offset + 1, true) ? PlainValueEc8e588e.Type.SEQ_ITEM : PlainValueEc8e588e.Type.PLAIN;
5278
5279       case '"':
5280         return PlainValueEc8e588e.Type.QUOTE_DOUBLE;
5281
5282       case "'":
5283         return PlainValueEc8e588e.Type.QUOTE_SINGLE;
5284
5285       default:
5286         return PlainValueEc8e588e.Type.PLAIN;
5287     }
5288   }
5289
5290   constructor(orig = {}, {
5291     atLineStart,
5292     inCollection,
5293     inFlow,
5294     indent,
5295     lineStart,
5296     parent
5297   } = {}) {
5298     PlainValueEc8e588e._defineProperty(this, "parseNode", (overlay, start) => {
5299       if (PlainValueEc8e588e.Node.atDocumentBoundary(this.src, start)) return null;
5300       const context = new ParseContext(this, overlay);
5301       const {
5302         props,
5303         type,
5304         valueStart
5305       } = context.parseProps(start);
5306       const node = createNewNode(type, props);
5307       let offset = node.parse(context, valueStart);
5308       node.range = new PlainValueEc8e588e.Range(start, offset);
5309       /* istanbul ignore if */
5310
5311       if (offset <= start) {
5312         // This should never happen, but if it does, let's make sure to at least
5313         // step one character forward to avoid a busy loop.
5314         node.error = new Error(`Node#parse consumed no characters`);
5315         node.error.parseEnd = offset;
5316         node.error.source = node;
5317         node.range.end = start + 1;
5318       }
5319
5320       if (context.nodeStartsCollection(node)) {
5321         if (!node.error && !context.atLineStart && context.parent.type === PlainValueEc8e588e.Type.DOCUMENT) {
5322           node.error = new PlainValueEc8e588e.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)');
5323         }
5324
5325         const collection = new Collection(node);
5326         offset = collection.parse(new ParseContext(context), offset);
5327         collection.range = new PlainValueEc8e588e.Range(start, offset);
5328         return collection;
5329       }
5330
5331       return node;
5332     });
5333
5334     this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false;
5335     this.inCollection = inCollection != null ? inCollection : orig.inCollection || false;
5336     this.inFlow = inFlow != null ? inFlow : orig.inFlow || false;
5337     this.indent = indent != null ? indent : orig.indent;
5338     this.lineStart = lineStart != null ? lineStart : orig.lineStart;
5339     this.parent = parent != null ? parent : orig.parent || {};
5340     this.root = orig.root;
5341     this.src = orig.src;
5342   }
5343
5344   nodeStartsCollection(node) {
5345     const {
5346       inCollection,
5347       inFlow,
5348       src
5349     } = this;
5350     if (inCollection || inFlow) return false;
5351     if (node instanceof CollectionItem) return true; // check for implicit key
5352
5353     let offset = node.range.end;
5354     if (src[offset] === '\n' || src[offset - 1] === '\n') return false;
5355     offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
5356     return src[offset] === ':';
5357   } // Anchor and tag are before type, which determines the node implementation
5358   // class; hence this intermediate step.
5359
5360
5361   parseProps(offset) {
5362     const {
5363       inFlow,
5364       parent,
5365       src
5366     } = this;
5367     const props = [];
5368     let lineHasProps = false;
5369     offset = this.atLineStart ? PlainValueEc8e588e.Node.endOfIndent(src, offset) : PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
5370     let ch = src[offset];
5371
5372     while (ch === PlainValueEc8e588e.Char.ANCHOR || ch === PlainValueEc8e588e.Char.COMMENT || ch === PlainValueEc8e588e.Char.TAG || ch === '\n') {
5373       if (ch === '\n') {
5374         const lineStart = offset + 1;
5375         const inEnd = PlainValueEc8e588e.Node.endOfIndent(src, lineStart);
5376         const indentDiff = inEnd - (lineStart + this.indent);
5377         const noIndicatorAsIndent = parent.type === PlainValueEc8e588e.Type.SEQ_ITEM && parent.context.atLineStart;
5378         if (!PlainValueEc8e588e.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break;
5379         this.atLineStart = true;
5380         this.lineStart = lineStart;
5381         lineHasProps = false;
5382         offset = inEnd;
5383       } else if (ch === PlainValueEc8e588e.Char.COMMENT) {
5384         const end = PlainValueEc8e588e.Node.endOfLine(src, offset + 1);
5385         props.push(new PlainValueEc8e588e.Range(offset, end));
5386         offset = end;
5387       } else {
5388         let end = PlainValueEc8e588e.Node.endOfIdentifier(src, offset + 1);
5389
5390         if (ch === PlainValueEc8e588e.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) {
5391           // Let's presume we're dealing with a YAML 1.0 domain tag here, rather
5392           // than an empty but 'foo.bar' private-tagged node in a flow collection
5393           // followed without whitespace by a plain string starting with a year
5394           // or date divided by something.
5395           end = PlainValueEc8e588e.Node.endOfIdentifier(src, end + 5);
5396         }
5397
5398         props.push(new PlainValueEc8e588e.Range(offset, end));
5399         lineHasProps = true;
5400         offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, end);
5401       }
5402
5403       ch = src[offset];
5404     } // '- &a : b' has an anchor on an empty node
5405
5406
5407     if (lineHasProps && ch === ':' && PlainValueEc8e588e.Node.atBlank(src, offset + 1, true)) offset -= 1;
5408     const type = ParseContext.parseType(src, offset, inFlow);
5409     return {
5410       props,
5411       type,
5412       valueStart: offset
5413     };
5414   }
5415   /**
5416    * Parses a node from the source
5417    * @param {ParseContext} overlay
5418    * @param {number} start - Index of first non-whitespace character for the node
5419    * @returns {?Node} - null if at a document boundary
5420    */
5421
5422
5423 } // Published as 'yaml/parse-cst'
5424
5425
5426 function parse(src) {
5427   const cr = [];
5428
5429   if (src.indexOf('\r') !== -1) {
5430     src = src.replace(/\r\n?/g, (match, offset) => {
5431       if (match.length > 1) cr.push(offset);
5432       return '\n';
5433     });
5434   }
5435
5436   const documents = [];
5437   let offset = 0;
5438
5439   do {
5440     const doc = new Document();
5441     const context = new ParseContext({
5442       src
5443     });
5444     offset = doc.parse(context, offset);
5445     documents.push(doc);
5446   } while (offset < src.length);
5447
5448   documents.setOrigRanges = () => {
5449     if (cr.length === 0) return false;
5450
5451     for (let i = 1; i < cr.length; ++i) cr[i] -= i;
5452
5453     let crOffset = 0;
5454
5455     for (let i = 0; i < documents.length; ++i) {
5456       crOffset = documents[i].setOrigRanges(cr, crOffset);
5457     }
5458
5459     cr.splice(0, cr.length);
5460     return true;
5461   };
5462
5463   documents.toString = () => documents.join('...\n');
5464
5465   return documents;
5466 }
5467
5468 var parse_1 = parse;
5469 var parseCst = {
5470   parse: parse_1
5471 };
5472
5473 function addCommentBefore(str, indent, comment) {
5474   if (!comment) return str;
5475   const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`);
5476   return `#${cc}\n${indent}${str}`;
5477 }
5478
5479 function addComment(str, indent, comment) {
5480   return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`);
5481 }
5482
5483 class Node$1 {}
5484
5485 function toJSON(value, arg, ctx) {
5486   if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx));
5487
5488   if (value && typeof value.toJSON === 'function') {
5489     const anchor = ctx && ctx.anchors && ctx.anchors.get(value);
5490     if (anchor) ctx.onCreate = res => {
5491       anchor.res = res;
5492       delete ctx.onCreate;
5493     };
5494     const res = value.toJSON(arg, ctx);
5495     if (anchor && ctx.onCreate) ctx.onCreate(res);
5496     return res;
5497   }
5498
5499   if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value);
5500   return value;
5501 }
5502
5503 class Scalar extends Node$1 {
5504   constructor(value) {
5505     super();
5506     this.value = value;
5507   }
5508
5509   toJSON(arg, ctx) {
5510     return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx);
5511   }
5512
5513   toString() {
5514     return String(this.value);
5515   }
5516
5517 }
5518
5519 function collectionFromPath(schema, path, value) {
5520   let v = value;
5521
5522   for (let i = path.length - 1; i >= 0; --i) {
5523     const k = path[i];
5524     const o = Number.isInteger(k) && k >= 0 ? [] : {};
5525     o[k] = v;
5526     v = o;
5527   }
5528
5529   return schema.createNode(v, false);
5530 } // null, undefined, or an empty non-string iterable (e.g. [])
5531
5532
5533 const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done;
5534
5535 class Collection$1 extends Node$1 {
5536   constructor(schema) {
5537     super();
5538
5539     PlainValueEc8e588e._defineProperty(this, "items", []);
5540
5541     this.schema = schema;
5542   }
5543
5544   addIn(path, value) {
5545     if (isEmptyPath(path)) this.add(value);else {
5546       const [key, ...rest] = path;
5547       const node = this.get(key, true);
5548       if (node instanceof Collection$1) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
5549     }
5550   }
5551
5552   deleteIn([key, ...rest]) {
5553     if (rest.length === 0) return this.delete(key);
5554     const node = this.get(key, true);
5555     if (node instanceof Collection$1) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
5556   }
5557
5558   getIn([key, ...rest], keepScalar) {
5559     const node = this.get(key, true);
5560     if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection$1 ? node.getIn(rest, keepScalar) : undefined;
5561   }
5562
5563   hasAllNullValues() {
5564     return this.items.every(node => {
5565       if (!node || node.type !== 'PAIR') return false;
5566       const n = node.value;
5567       return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag;
5568     });
5569   }
5570
5571   hasIn([key, ...rest]) {
5572     if (rest.length === 0) return this.has(key);
5573     const node = this.get(key, true);
5574     return node instanceof Collection$1 ? node.hasIn(rest) : false;
5575   }
5576
5577   setIn([key, ...rest], value) {
5578     if (rest.length === 0) {
5579       this.set(key, value);
5580     } else {
5581       const node = this.get(key, true);
5582       if (node instanceof Collection$1) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
5583     }
5584   } // overridden in implementations
5585
5586   /* istanbul ignore next */
5587
5588
5589   toJSON() {
5590     return null;
5591   }
5592
5593   toString(ctx, {
5594     blockItem,
5595     flowChars,
5596     isMap,
5597     itemIndent
5598   }, onComment, onChompKeep) {
5599     const {
5600       indent,
5601       indentStep,
5602       stringify
5603     } = ctx;
5604     const inFlow = this.type === PlainValueEc8e588e.Type.FLOW_MAP || this.type === PlainValueEc8e588e.Type.FLOW_SEQ || ctx.inFlow;
5605     if (inFlow) itemIndent += indentStep;
5606     const allNullValues = isMap && this.hasAllNullValues();
5607     ctx = Object.assign({}, ctx, {
5608       allNullValues,
5609       indent: itemIndent,
5610       inFlow,
5611       type: null
5612     });
5613     let chompKeep = false;
5614     let hasItemWithNewLine = false;
5615     const nodes = this.items.reduce((nodes, item, i) => {
5616       let comment;
5617
5618       if (item) {
5619         if (!chompKeep && item.spaceBefore) nodes.push({
5620           type: 'comment',
5621           str: ''
5622         });
5623         if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => {
5624           nodes.push({
5625             type: 'comment',
5626             str: `#${line}`
5627           });
5628         });
5629         if (item.comment) comment = item.comment;
5630         if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true;
5631       }
5632
5633       chompKeep = false;
5634       let str = stringify(item, ctx, () => comment = null, () => chompKeep = true);
5635       if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true;
5636       if (inFlow && i < this.items.length - 1) str += ',';
5637       str = addComment(str, itemIndent, comment);
5638       if (chompKeep && (comment || inFlow)) chompKeep = false;
5639       nodes.push({
5640         type: 'item',
5641         str
5642       });
5643       return nodes;
5644     }, []);
5645     let str;
5646
5647     if (nodes.length === 0) {
5648       str = flowChars.start + flowChars.end;
5649     } else if (inFlow) {
5650       const {
5651         start,
5652         end
5653       } = flowChars;
5654       const strings = nodes.map(n => n.str);
5655
5656       if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection$1.maxFlowStringSingleLineLength) {
5657         str = start;
5658
5659         for (const s of strings) {
5660           str += s ? `\n${indentStep}${indent}${s}` : '\n';
5661         }
5662
5663         str += `\n${indent}${end}`;
5664       } else {
5665         str = `${start} ${strings.join(' ')} ${end}`;
5666       }
5667     } else {
5668       const strings = nodes.map(blockItem);
5669       str = strings.shift();
5670
5671       for (const s of strings) str += s ? `\n${indent}${s}` : '\n';
5672     }
5673
5674     if (this.comment) {
5675       str += '\n' + this.comment.replace(/^/gm, `${indent}#`);
5676       if (onComment) onComment();
5677     } else if (chompKeep && onChompKeep) onChompKeep();
5678
5679     return str;
5680   }
5681
5682 }
5683
5684 PlainValueEc8e588e._defineProperty(Collection$1, "maxFlowStringSingleLineLength", 60);
5685
5686 function asItemIndex(key) {
5687   let idx = key instanceof Scalar ? key.value : key;
5688   if (idx && typeof idx === 'string') idx = Number(idx);
5689   return Number.isInteger(idx) && idx >= 0 ? idx : null;
5690 }
5691
5692 class YAMLSeq extends Collection$1 {
5693   add(value) {
5694     this.items.push(value);
5695   }
5696
5697   delete(key) {
5698     const idx = asItemIndex(key);
5699     if (typeof idx !== 'number') return false;
5700     const del = this.items.splice(idx, 1);
5701     return del.length > 0;
5702   }
5703
5704   get(key, keepScalar) {
5705     const idx = asItemIndex(key);
5706     if (typeof idx !== 'number') return undefined;
5707     const it = this.items[idx];
5708     return !keepScalar && it instanceof Scalar ? it.value : it;
5709   }
5710
5711   has(key) {
5712     const idx = asItemIndex(key);
5713     return typeof idx === 'number' && idx < this.items.length;
5714   }
5715
5716   set(key, value) {
5717     const idx = asItemIndex(key);
5718     if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`);
5719     this.items[idx] = value;
5720   }
5721
5722   toJSON(_, ctx) {
5723     const seq = [];
5724     if (ctx && ctx.onCreate) ctx.onCreate(seq);
5725     let i = 0;
5726
5727     for (const item of this.items) seq.push(toJSON(item, String(i++), ctx));
5728
5729     return seq;
5730   }
5731
5732   toString(ctx, onComment, onChompKeep) {
5733     if (!ctx) return JSON.stringify(this);
5734     return super.toString(ctx, {
5735       blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`,
5736       flowChars: {
5737         start: '[',
5738         end: ']'
5739       },
5740       isMap: false,
5741       itemIndent: (ctx.indent || '') + '  '
5742     }, onComment, onChompKeep);
5743   }
5744
5745 }
5746
5747 const stringifyKey = (key, jsKey, ctx) => {
5748   if (jsKey === null) return '';
5749   if (typeof jsKey !== 'object') return String(jsKey);
5750   if (key instanceof Node$1 && ctx && ctx.doc) return key.toString({
5751     anchors: {},
5752     doc: ctx.doc,
5753     indent: '',
5754     indentStep: ctx.indentStep,
5755     inFlow: true,
5756     inStringifyKey: true,
5757     stringify: ctx.stringify
5758   });
5759   return JSON.stringify(jsKey);
5760 };
5761
5762 class Pair extends Node$1 {
5763   constructor(key, value = null) {
5764     super();
5765     this.key = key;
5766     this.value = value;
5767     this.type = Pair.Type.PAIR;
5768   }
5769
5770   get commentBefore() {
5771     return this.key instanceof Node$1 ? this.key.commentBefore : undefined;
5772   }
5773
5774   set commentBefore(cb) {
5775     if (this.key == null) this.key = new Scalar(null);
5776     if (this.key instanceof Node$1) this.key.commentBefore = cb;else {
5777       const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.';
5778       throw new Error(msg);
5779     }
5780   }
5781
5782   addToJSMap(ctx, map) {
5783     const key = toJSON(this.key, '', ctx);
5784
5785     if (map instanceof Map) {
5786       const value = toJSON(this.value, key, ctx);
5787       map.set(key, value);
5788     } else if (map instanceof Set) {
5789       map.add(key);
5790     } else {
5791       const stringKey = stringifyKey(this.key, key, ctx);
5792       map[stringKey] = toJSON(this.value, stringKey, ctx);
5793     }
5794
5795     return map;
5796   }
5797
5798   toJSON(_, ctx) {
5799     const pair = ctx && ctx.mapAsMap ? new Map() : {};
5800     return this.addToJSMap(ctx, pair);
5801   }
5802
5803   toString(ctx, onComment, onChompKeep) {
5804     if (!ctx || !ctx.doc) return JSON.stringify(this);
5805     const {
5806       indent: indentSize,
5807       indentSeq,
5808       simpleKeys
5809     } = ctx.doc.options;
5810     let {
5811       key,
5812       value
5813     } = this;
5814     let keyComment = key instanceof Node$1 && key.comment;
5815
5816     if (simpleKeys) {
5817       if (keyComment) {
5818         throw new Error('With simple keys, key nodes cannot have comments');
5819       }
5820
5821       if (key instanceof Collection$1) {
5822         const msg = 'With simple keys, collection cannot be used as a key value';
5823         throw new Error(msg);
5824       }
5825     }
5826
5827     const explicitKey = !simpleKeys && (!key || keyComment || key instanceof Collection$1 || key.type === PlainValueEc8e588e.Type.BLOCK_FOLDED || key.type === PlainValueEc8e588e.Type.BLOCK_LITERAL);
5828     const {
5829       doc,
5830       indent,
5831       indentStep,
5832       stringify
5833     } = ctx;
5834     ctx = Object.assign({}, ctx, {
5835       implicitKey: !explicitKey,
5836       indent: indent + indentStep
5837     });
5838     let chompKeep = false;
5839     let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true);
5840     str = addComment(str, ctx.indent, keyComment);
5841
5842     if (ctx.allNullValues && !simpleKeys) {
5843       if (this.comment) {
5844         str = addComment(str, ctx.indent, this.comment);
5845         if (onComment) onComment();
5846       } else if (chompKeep && !keyComment && onChompKeep) onChompKeep();
5847
5848       return ctx.inFlow ? str : `? ${str}`;
5849     }
5850
5851     str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`;
5852
5853     if (this.comment) {
5854       // expected (but not strictly required) to be a single-line comment
5855       str = addComment(str, ctx.indent, this.comment);
5856       if (onComment) onComment();
5857     }
5858
5859     let vcb = '';
5860     let valueComment = null;
5861
5862     if (value instanceof Node$1) {
5863       if (value.spaceBefore) vcb = '\n';
5864
5865       if (value.commentBefore) {
5866         const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`);
5867         vcb += `\n${cs}`;
5868       }
5869
5870       valueComment = value.comment;
5871     } else if (value && typeof value === 'object') {
5872       value = doc.schema.createNode(value, true);
5873     }
5874
5875     ctx.implicitKey = false;
5876     if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1;
5877     chompKeep = false;
5878
5879     if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValueEc8e588e.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) {
5880       // If indentSeq === false, consider '- ' as part of indentation where possible
5881       ctx.indent = ctx.indent.substr(2);
5882     }
5883
5884     const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true);
5885     let ws = ' ';
5886
5887     if (vcb || this.comment) {
5888       ws = `${vcb}\n${ctx.indent}`;
5889     } else if (!explicitKey && value instanceof Collection$1) {
5890       const flow = valueStr[0] === '[' || valueStr[0] === '{';
5891       if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`;
5892     }
5893
5894     if (chompKeep && !valueComment && onChompKeep) onChompKeep();
5895     return addComment(str + ws + valueStr, ctx.indent, valueComment);
5896   }
5897
5898 }
5899
5900 PlainValueEc8e588e._defineProperty(Pair, "Type", {
5901   PAIR: 'PAIR',
5902   MERGE_PAIR: 'MERGE_PAIR'
5903 });
5904
5905 const getAliasCount = (node, anchors) => {
5906   if (node instanceof Alias$1) {
5907     const anchor = anchors.get(node.source);
5908     return anchor.count * anchor.aliasCount;
5909   } else if (node instanceof Collection$1) {
5910     let count = 0;
5911
5912     for (const item of node.items) {
5913       const c = getAliasCount(item, anchors);
5914       if (c > count) count = c;
5915     }
5916
5917     return count;
5918   } else if (node instanceof Pair) {
5919     const kc = getAliasCount(node.key, anchors);
5920     const vc = getAliasCount(node.value, anchors);
5921     return Math.max(kc, vc);
5922   }
5923
5924   return 1;
5925 };
5926
5927 class Alias$1 extends Node$1 {
5928   static stringify({
5929     range,
5930     source
5931   }, {
5932     anchors,
5933     doc,
5934     implicitKey,
5935     inStringifyKey
5936   }) {
5937     let anchor = Object.keys(anchors).find(a => anchors[a] === source);
5938     if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName();
5939     if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`;
5940     const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node';
5941     throw new Error(`${msg} [${range}]`);
5942   }
5943
5944   constructor(source) {
5945     super();
5946     this.source = source;
5947     this.type = PlainValueEc8e588e.Type.ALIAS;
5948   }
5949
5950   set tag(t) {
5951     throw new Error('Alias nodes cannot have tags');
5952   }
5953
5954   toJSON(arg, ctx) {
5955     if (!ctx) return toJSON(this.source, arg, ctx);
5956     const {
5957       anchors,
5958       maxAliasCount
5959     } = ctx;
5960     const anchor = anchors.get(this.source);
5961     /* istanbul ignore if */
5962
5963     if (!anchor || anchor.res === undefined) {
5964       const msg = 'This should not happen: Alias anchor was not resolved?';
5965       if (this.cstNode) throw new PlainValueEc8e588e.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
5966     }
5967
5968     if (maxAliasCount >= 0) {
5969       anchor.count += 1;
5970       if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors);
5971
5972       if (anchor.count * anchor.aliasCount > maxAliasCount) {
5973         const msg = 'Excessive alias count indicates a resource exhaustion attack';
5974         if (this.cstNode) throw new PlainValueEc8e588e.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
5975       }
5976     }
5977
5978     return anchor.res;
5979   } // Only called when stringifying an alias mapping key while constructing
5980   // Object output.
5981
5982
5983   toString(ctx) {
5984     return Alias$1.stringify(this, ctx);
5985   }
5986
5987 }
5988
5989 PlainValueEc8e588e._defineProperty(Alias$1, "default", true);
5990
5991 function findPair(items, key) {
5992   const k = key instanceof Scalar ? key.value : key;
5993
5994   for (const it of items) {
5995     if (it instanceof Pair) {
5996       if (it.key === key || it.key === k) return it;
5997       if (it.key && it.key.value === k) return it;
5998     }
5999   }
6000
6001   return undefined;
6002 }
6003
6004 class YAMLMap extends Collection$1 {
6005   add(pair, overwrite) {
6006     if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value);
6007     const prev = findPair(this.items, pair.key);
6008     const sortEntries = this.schema && this.schema.sortMapEntries;
6009
6010     if (prev) {
6011       if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`);
6012     } else if (sortEntries) {
6013       const i = this.items.findIndex(item => sortEntries(pair, item) < 0);
6014       if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair);
6015     } else {
6016       this.items.push(pair);
6017     }
6018   }
6019
6020   delete(key) {
6021     const it = findPair(this.items, key);
6022     if (!it) return false;
6023     const del = this.items.splice(this.items.indexOf(it), 1);
6024     return del.length > 0;
6025   }
6026
6027   get(key, keepScalar) {
6028     const it = findPair(this.items, key);
6029     const node = it && it.value;
6030     return !keepScalar && node instanceof Scalar ? node.value : node;
6031   }
6032
6033   has(key) {
6034     return !!findPair(this.items, key);
6035   }
6036
6037   set(key, value) {
6038     this.add(new Pair(key, value), true);
6039   }
6040   /**
6041    * @param {*} arg ignored
6042    * @param {*} ctx Conversion context, originally set in Document#toJSON()
6043    * @param {Class} Type If set, forces the returned collection type
6044    * @returns {*} Instance of Type, Map, or Object
6045    */
6046
6047
6048   toJSON(_, ctx, Type) {
6049     const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {};
6050     if (ctx && ctx.onCreate) ctx.onCreate(map);
6051
6052     for (const item of this.items) item.addToJSMap(ctx, map);
6053
6054     return map;
6055   }
6056
6057   toString(ctx, onComment, onChompKeep) {
6058     if (!ctx) return JSON.stringify(this);
6059
6060     for (const item of this.items) {
6061       if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
6062     }
6063
6064     return super.toString(ctx, {
6065       blockItem: n => n.str,
6066       flowChars: {
6067         start: '{',
6068         end: '}'
6069       },
6070       isMap: true,
6071       itemIndent: ctx.indent || ''
6072     }, onComment, onChompKeep);
6073   }
6074
6075 }
6076
6077 const MERGE_KEY = '<<';
6078
6079 class Merge extends Pair {
6080   constructor(pair) {
6081     if (pair instanceof Pair) {
6082       let seq = pair.value;
6083
6084       if (!(seq instanceof YAMLSeq)) {
6085         seq = new YAMLSeq();
6086         seq.items.push(pair.value);
6087         seq.range = pair.value.range;
6088       }
6089
6090       super(pair.key, seq);
6091       this.range = pair.range;
6092     } else {
6093       super(new Scalar(MERGE_KEY), new YAMLSeq());
6094     }
6095
6096     this.type = Pair.Type.MERGE_PAIR;
6097   } // If the value associated with a merge key is a single mapping node, each of
6098   // its key/value pairs is inserted into the current mapping, unless the key
6099   // already exists in it. If the value associated with the merge key is a
6100   // sequence, then this sequence is expected to contain mapping nodes and each
6101   // of these nodes is merged in turn according to its order in the sequence.
6102   // Keys in mapping nodes earlier in the sequence override keys specified in
6103   // later mapping nodes. -- http://yaml.org/type/merge.html
6104
6105
6106   addToJSMap(ctx, map) {
6107     for (const {
6108       source
6109     } of this.value.items) {
6110       if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps');
6111       const srcMap = source.toJSON(null, ctx, Map);
6112
6113       for (const [key, value] of srcMap) {
6114         if (map instanceof Map) {
6115           if (!map.has(key)) map.set(key, value);
6116         } else if (map instanceof Set) {
6117           map.add(key);
6118         } else {
6119           if (!Object.prototype.hasOwnProperty.call(map, key)) map[key] = value;
6120         }
6121       }
6122     }
6123
6124     return map;
6125   }
6126
6127   toString(ctx, onComment) {
6128     const seq = this.value;
6129     if (seq.items.length > 1) return super.toString(ctx, onComment);
6130     this.value = seq.items[0];
6131     const str = super.toString(ctx, onComment);
6132     this.value = seq;
6133     return str;
6134   }
6135
6136 }
6137
6138 const binaryOptions = {
6139   defaultType: PlainValueEc8e588e.Type.BLOCK_LITERAL,
6140   lineWidth: 76
6141 };
6142 const boolOptions = {
6143   trueStr: 'true',
6144   falseStr: 'false'
6145 };
6146 const intOptions = {
6147   asBigInt: false
6148 };
6149 const nullOptions = {
6150   nullStr: 'null'
6151 };
6152 const strOptions = {
6153   defaultType: PlainValueEc8e588e.Type.PLAIN,
6154   doubleQuoted: {
6155     jsonEncoding: false,
6156     minMultiLineLength: 40
6157   },
6158   fold: {
6159     lineWidth: 80,
6160     minContentWidth: 20
6161   }
6162 };
6163
6164 function resolveScalar(str, tags, scalarFallback) {
6165   for (const {
6166     format,
6167     test,
6168     resolve
6169   } of tags) {
6170     if (test) {
6171       const match = str.match(test);
6172
6173       if (match) {
6174         let res = resolve.apply(null, match);
6175         if (!(res instanceof Scalar)) res = new Scalar(res);
6176         if (format) res.format = format;
6177         return res;
6178       }
6179     }
6180   }
6181
6182   if (scalarFallback) str = scalarFallback(str);
6183   return new Scalar(str);
6184 }
6185
6186 const FOLD_FLOW = 'flow';
6187 const FOLD_BLOCK = 'block';
6188 const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line
6189 // returns index of last newline in more-indented block
6190
6191 const consumeMoreIndentedLines = (text, i) => {
6192   let ch = text[i + 1];
6193
6194   while (ch === ' ' || ch === '\t') {
6195     do {
6196       ch = text[i += 1];
6197     } while (ch && ch !== '\n');
6198
6199     ch = text[i + 1];
6200   }
6201
6202   return i;
6203 };
6204 /**
6205  * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
6206  * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
6207  * terminated with `\n` and started with `indent`.
6208  *
6209  * @param {string} text
6210  * @param {string} indent
6211  * @param {string} [mode='flow'] `'block'` prevents more-indented lines
6212  *   from being folded; `'quoted'` allows for `\` escapes, including escaped
6213  *   newlines
6214  * @param {Object} options
6215  * @param {number} [options.indentAtStart] Accounts for leading contents on
6216  *   the first line, defaulting to `indent.length`
6217  * @param {number} [options.lineWidth=80]
6218  * @param {number} [options.minContentWidth=20] Allow highly indented lines to
6219  *   stretch the line width
6220  * @param {function} options.onFold Called once if the text is folded
6221  * @param {function} options.onFold Called once if any line of text exceeds
6222  *   lineWidth characters
6223  */
6224
6225
6226 function foldFlowLines(text, indent, mode, {
6227   indentAtStart,
6228   lineWidth = 80,
6229   minContentWidth = 20,
6230   onFold,
6231   onOverflow
6232 }) {
6233   if (!lineWidth || lineWidth < 0) return text;
6234   const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
6235   if (text.length <= endStep) return text;
6236   const folds = [];
6237   const escapedFolds = {};
6238   let end = lineWidth - (typeof indentAtStart === 'number' ? indentAtStart : indent.length);
6239   let split = undefined;
6240   let prev = undefined;
6241   let overflow = false;
6242   let i = -1;
6243
6244   if (mode === FOLD_BLOCK) {
6245     i = consumeMoreIndentedLines(text, i);
6246     if (i !== -1) end = i + endStep;
6247   }
6248
6249   for (let ch; ch = text[i += 1];) {
6250     if (mode === FOLD_QUOTED && ch === '\\') {
6251       switch (text[i + 1]) {
6252         case 'x':
6253           i += 3;
6254           break;
6255
6256         case 'u':
6257           i += 5;
6258           break;
6259
6260         case 'U':
6261           i += 9;
6262           break;
6263
6264         default:
6265           i += 1;
6266       }
6267     }
6268
6269     if (ch === '\n') {
6270       if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i);
6271       end = i + endStep;
6272       split = undefined;
6273     } else {
6274       if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') {
6275         // space surrounded by non-space can be replaced with newline + indent
6276         const next = text[i + 1];
6277         if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i;
6278       }
6279
6280       if (i >= end) {
6281         if (split) {
6282           folds.push(split);
6283           end = split + endStep;
6284           split = undefined;
6285         } else if (mode === FOLD_QUOTED) {
6286           // white-space collected at end may stretch past lineWidth
6287           while (prev === ' ' || prev === '\t') {
6288             prev = ch;
6289             ch = text[i += 1];
6290             overflow = true;
6291           } // i - 2 accounts for not-dropped last char + newline-escaping \
6292
6293
6294           folds.push(i - 2);
6295           escapedFolds[i - 2] = true;
6296           end = i - 2 + endStep;
6297           split = undefined;
6298         } else {
6299           overflow = true;
6300         }
6301       }
6302     }
6303
6304     prev = ch;
6305   }
6306
6307   if (overflow && onOverflow) onOverflow();
6308   if (folds.length === 0) return text;
6309   if (onFold) onFold();
6310   let res = text.slice(0, folds[0]);
6311
6312   for (let i = 0; i < folds.length; ++i) {
6313     const fold = folds[i];
6314     const end = folds[i + 1] || text.length;
6315     if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`;
6316     res += `\n${indent}${text.slice(fold + 1, end)}`;
6317   }
6318
6319   return res;
6320 }
6321
6322 const getFoldOptions = ({
6323   indentAtStart
6324 }) => indentAtStart ? Object.assign({
6325   indentAtStart
6326 }, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will
6327 // presume that's starting a new document.
6328
6329
6330 const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str);
6331
6332 function lineLengthOverLimit(str, limit) {
6333   const strLen = str.length;
6334   if (strLen <= limit) return false;
6335
6336   for (let i = 0, start = 0; i < strLen; ++i) {
6337     if (str[i] === '\n') {
6338       if (i - start > limit) return true;
6339       start = i + 1;
6340       if (strLen - start <= limit) return false;
6341     }
6342   }
6343
6344   return true;
6345 }
6346
6347 function doubleQuotedString(value, ctx) {
6348   const {
6349     implicitKey
6350   } = ctx;
6351   const {
6352     jsonEncoding,
6353     minMultiLineLength
6354   } = strOptions.doubleQuoted;
6355   const json = JSON.stringify(value);
6356   if (jsonEncoding) return json;
6357   const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');
6358   let str = '';
6359   let start = 0;
6360
6361   for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
6362     if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
6363       // space before newline needs to be escaped to not be folded
6364       str += json.slice(start, i) + '\\ ';
6365       i += 1;
6366       start = i;
6367       ch = '\\';
6368     }
6369
6370     if (ch === '\\') switch (json[i + 1]) {
6371       case 'u':
6372         {
6373           str += json.slice(start, i);
6374           const code = json.substr(i + 2, 4);
6375
6376           switch (code) {
6377             case '0000':
6378               str += '\\0';
6379               break;
6380
6381             case '0007':
6382               str += '\\a';
6383               break;
6384
6385             case '000b':
6386               str += '\\v';
6387               break;
6388
6389             case '001b':
6390               str += '\\e';
6391               break;
6392
6393             case '0085':
6394               str += '\\N';
6395               break;
6396
6397             case '00a0':
6398               str += '\\_';
6399               break;
6400
6401             case '2028':
6402               str += '\\L';
6403               break;
6404
6405             case '2029':
6406               str += '\\P';
6407               break;
6408
6409             default:
6410               if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6);
6411           }
6412
6413           i += 5;
6414           start = i + 1;
6415         }
6416         break;
6417
6418       case 'n':
6419         if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
6420           i += 1;
6421         } else {
6422           // folding will eat first newline
6423           str += json.slice(start, i) + '\n\n';
6424
6425           while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') {
6426             str += '\n';
6427             i += 2;
6428           }
6429
6430           str += indent; // space after newline needs to be escaped to not be folded
6431
6432           if (json[i + 2] === ' ') str += '\\';
6433           i += 1;
6434           start = i + 1;
6435         }
6436
6437         break;
6438
6439       default:
6440         i += 1;
6441     }
6442   }
6443
6444   str = start ? str + json.slice(start) : json;
6445   return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx));
6446 }
6447
6448 function singleQuotedString(value, ctx) {
6449   if (ctx.implicitKey) {
6450     if (/\n/.test(value)) return doubleQuotedString(value, ctx);
6451   } else {
6452     // single quoted string can't have leading or trailing whitespace around newline
6453     if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx);
6454   }
6455
6456   const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');
6457   const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
6458   return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx));
6459 }
6460
6461 function blockString({
6462   comment,
6463   type,
6464   value
6465 }, ctx, onComment, onChompKeep) {
6466   // 1. Block can't end in whitespace unless the last line is non-empty.
6467   // 2. Strings consisting of only whitespace are best rendered explicitly.
6468   if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
6469     return doubleQuotedString(value, ctx);
6470   }
6471
6472   const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? '  ' : '');
6473   const indentSize = indent ? '2' : '1'; // root is at -1
6474
6475   const literal = type === PlainValueEc8e588e.Type.BLOCK_FOLDED ? false : type === PlainValueEc8e588e.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth - indent.length);
6476   let header = literal ? '|' : '>';
6477   if (!value) return header + '\n';
6478   let wsStart = '';
6479   let wsEnd = '';
6480   value = value.replace(/[\n\t ]*$/, ws => {
6481     const n = ws.indexOf('\n');
6482
6483     if (n === -1) {
6484       header += '-'; // strip
6485     } else if (value === ws || n !== ws.length - 1) {
6486       header += '+'; // keep
6487
6488       if (onChompKeep) onChompKeep();
6489     }
6490
6491     wsEnd = ws.replace(/\n$/, '');
6492     return '';
6493   }).replace(/^[\n ]*/, ws => {
6494     if (ws.indexOf(' ') !== -1) header += indentSize;
6495     const m = ws.match(/ +$/);
6496
6497     if (m) {
6498       wsStart = ws.slice(0, -m[0].length);
6499       return m[0];
6500     } else {
6501       wsStart = ws;
6502       return '';
6503     }
6504   });
6505   if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`);
6506   if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`);
6507
6508   if (comment) {
6509     header += ' #' + comment.replace(/ ?[\r\n]+/g, ' ');
6510     if (onComment) onComment();
6511   }
6512
6513   if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`;
6514
6515   if (literal) {
6516     value = value.replace(/\n+/g, `$&${indent}`);
6517     return `${header}\n${indent}${wsStart}${value}${wsEnd}`;
6518   }
6519
6520   value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
6521   //         ^ ind.line  ^ empty     ^ capture next empty lines only at end of indent
6522   .replace(/\n+/g, `$&${indent}`);
6523   const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold);
6524   return `${header}\n${indent}${body}`;
6525 }
6526
6527 function plainString(item, ctx, onComment, onChompKeep) {
6528   const {
6529     comment,
6530     type,
6531     value
6532   } = item;
6533   const {
6534     actualString,
6535     implicitKey,
6536     indent,
6537     inFlow
6538   } = ctx;
6539
6540   if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) {
6541     return doubleQuotedString(value, ctx);
6542   }
6543
6544   if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
6545     // not allowed:
6546     // - empty string, '-' or '?'
6547     // - start with an indicator character (except [?:-]) or /[?-] /
6548     // - '\n ', ': ' or ' \n' anywhere
6549     // - '#' not preceded by a non-space char
6550     // - end with ' ' or ':'
6551     return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
6552   }
6553
6554   if (!implicitKey && !inFlow && type !== PlainValueEc8e588e.Type.PLAIN && value.indexOf('\n') !== -1) {
6555     // Where allowed & type not set explicitly, prefer block style for multiline strings
6556     return blockString(item, ctx, onComment, onChompKeep);
6557   }
6558
6559   if (indent === '' && containsDocumentMarker(value)) {
6560     ctx.forceBlockIndent = true;
6561     return blockString(item, ctx, onComment, onChompKeep);
6562   }
6563
6564   const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and
6565   // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
6566   // and others in v1.1.
6567
6568   if (actualString) {
6569     const {
6570       tags
6571     } = ctx.doc.schema;
6572     const resolved = resolveScalar(str, tags, tags.scalarFallback).value;
6573     if (typeof resolved !== 'string') return doubleQuotedString(value, ctx);
6574   }
6575
6576   const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx));
6577
6578   if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) {
6579     if (onComment) onComment();
6580     return addCommentBefore(body, indent, comment);
6581   }
6582
6583   return body;
6584 }
6585
6586 function stringifyString(item, ctx, onComment, onChompKeep) {
6587   const {
6588     defaultType
6589   } = strOptions;
6590   const {
6591     implicitKey,
6592     inFlow
6593   } = ctx;
6594   let {
6595     type,
6596     value
6597   } = item;
6598
6599   if (typeof value !== 'string') {
6600     value = String(value);
6601     item = Object.assign({}, item, {
6602       value
6603     });
6604   }
6605
6606   const _stringify = _type => {
6607     switch (_type) {
6608       case PlainValueEc8e588e.Type.BLOCK_FOLDED:
6609       case PlainValueEc8e588e.Type.BLOCK_LITERAL:
6610         return blockString(item, ctx, onComment, onChompKeep);
6611
6612       case PlainValueEc8e588e.Type.QUOTE_DOUBLE:
6613         return doubleQuotedString(value, ctx);
6614
6615       case PlainValueEc8e588e.Type.QUOTE_SINGLE:
6616         return singleQuotedString(value, ctx);
6617
6618       case PlainValueEc8e588e.Type.PLAIN:
6619         return plainString(item, ctx, onComment, onChompKeep);
6620
6621       default:
6622         return null;
6623     }
6624   };
6625
6626   if (type !== PlainValueEc8e588e.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) {
6627     // force double quotes on control characters
6628     type = PlainValueEc8e588e.Type.QUOTE_DOUBLE;
6629   } else if ((implicitKey || inFlow) && (type === PlainValueEc8e588e.Type.BLOCK_FOLDED || type === PlainValueEc8e588e.Type.BLOCK_LITERAL)) {
6630     // should not happen; blocks are not valid inside flow containers
6631     type = PlainValueEc8e588e.Type.QUOTE_DOUBLE;
6632   }
6633
6634   let res = _stringify(type);
6635
6636   if (res === null) {
6637     res = _stringify(defaultType);
6638     if (res === null) throw new Error(`Unsupported default string type ${defaultType}`);
6639   }
6640
6641   return res;
6642 }
6643
6644 function stringifyNumber({
6645   format,
6646   minFractionDigits,
6647   tag,
6648   value
6649 }) {
6650   if (typeof value === 'bigint') return String(value);
6651   if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf';
6652   let n = JSON.stringify(value);
6653
6654   if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) {
6655     let i = n.indexOf('.');
6656
6657     if (i < 0) {
6658       i = n.length;
6659       n += '.';
6660     }
6661
6662     let d = minFractionDigits - (n.length - i - 1);
6663
6664     while (d-- > 0) n += '0';
6665   }
6666
6667   return n;
6668 }
6669
6670 function checkFlowCollectionEnd(errors, cst) {
6671   let char, name;
6672
6673   switch (cst.type) {
6674     case PlainValueEc8e588e.Type.FLOW_MAP:
6675       char = '}';
6676       name = 'flow map';
6677       break;
6678
6679     case PlainValueEc8e588e.Type.FLOW_SEQ:
6680       char = ']';
6681       name = 'flow sequence';
6682       break;
6683
6684     default:
6685       errors.push(new PlainValueEc8e588e.YAMLSemanticError(cst, 'Not a flow collection!?'));
6686       return;
6687   }
6688
6689   let lastItem;
6690
6691   for (let i = cst.items.length - 1; i >= 0; --i) {
6692     const item = cst.items[i];
6693
6694     if (!item || item.type !== PlainValueEc8e588e.Type.COMMENT) {
6695       lastItem = item;
6696       break;
6697     }
6698   }
6699
6700   if (lastItem && lastItem.char !== char) {
6701     const msg = `Expected ${name} to end with ${char}`;
6702     let err;
6703
6704     if (typeof lastItem.offset === 'number') {
6705       err = new PlainValueEc8e588e.YAMLSemanticError(cst, msg);
6706       err.offset = lastItem.offset + 1;
6707     } else {
6708       err = new PlainValueEc8e588e.YAMLSemanticError(lastItem, msg);
6709       if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start;
6710     }
6711
6712     errors.push(err);
6713   }
6714 }
6715
6716 function checkFlowCommentSpace(errors, comment) {
6717   const prev = comment.context.src[comment.range.start - 1];
6718
6719   if (prev !== '\n' && prev !== '\t' && prev !== ' ') {
6720     const msg = 'Comments must be separated from other tokens by white space characters';
6721     errors.push(new PlainValueEc8e588e.YAMLSemanticError(comment, msg));
6722   }
6723 }
6724
6725 function getLongKeyError(source, key) {
6726   const sk = String(key);
6727   const k = sk.substr(0, 8) + '...' + sk.substr(-8);
6728   return new PlainValueEc8e588e.YAMLSemanticError(source, `The "${k}" key is too long`);
6729 }
6730
6731 function resolveComments(collection, comments) {
6732   for (const {
6733     afterKey,
6734     before,
6735     comment
6736   } of comments) {
6737     let item = collection.items[before];
6738
6739     if (!item) {
6740       if (comment !== undefined) {
6741         if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment;
6742       }
6743     } else {
6744       if (afterKey && item.value) item = item.value;
6745
6746       if (comment === undefined) {
6747         if (afterKey || !item.commentBefore) item.spaceBefore = true;
6748       } else {
6749         if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment;
6750       }
6751     }
6752   }
6753 } // on error, will return { str: string, errors: Error[] }
6754
6755
6756 function resolveString(doc, node) {
6757   const res = node.strValue;
6758   if (!res) return '';
6759   if (typeof res === 'string') return res;
6760   res.errors.forEach(error => {
6761     if (!error.source) error.source = node;
6762     doc.errors.push(error);
6763   });
6764   return res.str;
6765 }
6766
6767 function resolveTagHandle(doc, node) {
6768   const {
6769     handle,
6770     suffix
6771   } = node.tag;
6772   let prefix = doc.tagPrefixes.find(p => p.handle === handle);
6773
6774   if (!prefix) {
6775     const dtp = doc.getDefaults().tagPrefixes;
6776     if (dtp) prefix = dtp.find(p => p.handle === handle);
6777     if (!prefix) throw new PlainValueEc8e588e.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`);
6778   }
6779
6780   if (!suffix) throw new PlainValueEc8e588e.YAMLSemanticError(node, `The ${handle} tag has no suffix.`);
6781
6782   if (handle === '!' && (doc.version || doc.options.version) === '1.0') {
6783     if (suffix[0] === '^') {
6784       doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported'));
6785       return suffix;
6786     }
6787
6788     if (/[:/]/.test(suffix)) {
6789       // word/foo -> tag:word.yaml.org,2002:foo
6790       const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i);
6791       return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`;
6792     }
6793   }
6794
6795   return prefix.prefix + decodeURIComponent(suffix);
6796 }
6797
6798 function resolveTagName(doc, node) {
6799   const {
6800     tag,
6801     type
6802   } = node;
6803   let nonSpecific = false;
6804
6805   if (tag) {
6806     const {
6807       handle,
6808       suffix,
6809       verbatim
6810     } = tag;
6811
6812     if (verbatim) {
6813       if (verbatim !== '!' && verbatim !== '!!') return verbatim;
6814       const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`;
6815       doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(node, msg));
6816     } else if (handle === '!' && !suffix) {
6817       nonSpecific = true;
6818     } else {
6819       try {
6820         return resolveTagHandle(doc, node);
6821       } catch (error) {
6822         doc.errors.push(error);
6823       }
6824     }
6825   }
6826
6827   switch (type) {
6828     case PlainValueEc8e588e.Type.BLOCK_FOLDED:
6829     case PlainValueEc8e588e.Type.BLOCK_LITERAL:
6830     case PlainValueEc8e588e.Type.QUOTE_DOUBLE:
6831     case PlainValueEc8e588e.Type.QUOTE_SINGLE:
6832       return PlainValueEc8e588e.defaultTags.STR;
6833
6834     case PlainValueEc8e588e.Type.FLOW_MAP:
6835     case PlainValueEc8e588e.Type.MAP:
6836       return PlainValueEc8e588e.defaultTags.MAP;
6837
6838     case PlainValueEc8e588e.Type.FLOW_SEQ:
6839     case PlainValueEc8e588e.Type.SEQ:
6840       return PlainValueEc8e588e.defaultTags.SEQ;
6841
6842     case PlainValueEc8e588e.Type.PLAIN:
6843       return nonSpecific ? PlainValueEc8e588e.defaultTags.STR : null;
6844
6845     default:
6846       return null;
6847   }
6848 }
6849
6850 function resolveByTagName(doc, node, tagName) {
6851   const {
6852     tags
6853   } = doc.schema;
6854   const matchWithTest = [];
6855
6856   for (const tag of tags) {
6857     if (tag.tag === tagName) {
6858       if (tag.test) matchWithTest.push(tag);else {
6859         const res = tag.resolve(doc, node);
6860         return res instanceof Collection$1 ? res : new Scalar(res);
6861       }
6862     }
6863   }
6864
6865   const str = resolveString(doc, node);
6866   if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback);
6867   return null;
6868 }
6869
6870 function getFallbackTagName({
6871   type
6872 }) {
6873   switch (type) {
6874     case PlainValueEc8e588e.Type.FLOW_MAP:
6875     case PlainValueEc8e588e.Type.MAP:
6876       return PlainValueEc8e588e.defaultTags.MAP;
6877
6878     case PlainValueEc8e588e.Type.FLOW_SEQ:
6879     case PlainValueEc8e588e.Type.SEQ:
6880       return PlainValueEc8e588e.defaultTags.SEQ;
6881
6882     default:
6883       return PlainValueEc8e588e.defaultTags.STR;
6884   }
6885 }
6886
6887 function resolveTag(doc, node, tagName) {
6888   try {
6889     const res = resolveByTagName(doc, node, tagName);
6890
6891     if (res) {
6892       if (tagName && node.tag) res.tag = tagName;
6893       return res;
6894     }
6895   } catch (error) {
6896     /* istanbul ignore if */
6897     if (!error.source) error.source = node;
6898     doc.errors.push(error);
6899     return null;
6900   }
6901
6902   try {
6903     const fallback = getFallbackTagName(node);
6904     if (!fallback) throw new Error(`The tag ${tagName} is unavailable`);
6905     const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`;
6906     doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(node, msg));
6907     const res = resolveByTagName(doc, node, fallback);
6908     res.tag = tagName;
6909     return res;
6910   } catch (error) {
6911     const refError = new PlainValueEc8e588e.YAMLReferenceError(node, error.message);
6912     refError.stack = error.stack;
6913     doc.errors.push(refError);
6914     return null;
6915   }
6916 }
6917
6918 const isCollectionItem = node => {
6919   if (!node) return false;
6920   const {
6921     type
6922   } = node;
6923   return type === PlainValueEc8e588e.Type.MAP_KEY || type === PlainValueEc8e588e.Type.MAP_VALUE || type === PlainValueEc8e588e.Type.SEQ_ITEM;
6924 };
6925
6926 function resolveNodeProps(errors, node) {
6927   const comments = {
6928     before: [],
6929     after: []
6930   };
6931   let hasAnchor = false;
6932   let hasTag = false;
6933   const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props;
6934
6935   for (const {
6936     start,
6937     end
6938   } of props) {
6939     switch (node.context.src[start]) {
6940       case PlainValueEc8e588e.Char.COMMENT:
6941         {
6942           if (!node.commentHasRequiredWhitespace(start)) {
6943             const msg = 'Comments must be separated from other tokens by white space characters';
6944             errors.push(new PlainValueEc8e588e.YAMLSemanticError(node, msg));
6945           }
6946
6947           const {
6948             header,
6949             valueRange
6950           } = node;
6951           const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before;
6952           cc.push(node.context.src.slice(start + 1, end));
6953           break;
6954         }
6955       // Actual anchor & tag resolution is handled by schema, here we just complain
6956
6957       case PlainValueEc8e588e.Char.ANCHOR:
6958         if (hasAnchor) {
6959           const msg = 'A node can have at most one anchor';
6960           errors.push(new PlainValueEc8e588e.YAMLSemanticError(node, msg));
6961         }
6962
6963         hasAnchor = true;
6964         break;
6965
6966       case PlainValueEc8e588e.Char.TAG:
6967         if (hasTag) {
6968           const msg = 'A node can have at most one tag';
6969           errors.push(new PlainValueEc8e588e.YAMLSemanticError(node, msg));
6970         }
6971
6972         hasTag = true;
6973         break;
6974     }
6975   }
6976
6977   return {
6978     comments,
6979     hasAnchor,
6980     hasTag
6981   };
6982 }
6983
6984 function resolveNodeValue(doc, node) {
6985   const {
6986     anchors,
6987     errors,
6988     schema
6989   } = doc;
6990
6991   if (node.type === PlainValueEc8e588e.Type.ALIAS) {
6992     const name = node.rawValue;
6993     const src = anchors.getNode(name);
6994
6995     if (!src) {
6996       const msg = `Aliased anchor not found: ${name}`;
6997       errors.push(new PlainValueEc8e588e.YAMLReferenceError(node, msg));
6998       return null;
6999     } // Lazy resolution for circular references
7000
7001
7002     const res = new Alias$1(src);
7003
7004     anchors._cstAliases.push(res);
7005
7006     return res;
7007   }
7008
7009   const tagName = resolveTagName(doc, node);
7010   if (tagName) return resolveTag(doc, node, tagName);
7011
7012   if (node.type !== PlainValueEc8e588e.Type.PLAIN) {
7013     const msg = `Failed to resolve ${node.type} node here`;
7014     errors.push(new PlainValueEc8e588e.YAMLSyntaxError(node, msg));
7015     return null;
7016   }
7017
7018   try {
7019     const str = resolveString(doc, node);
7020     return resolveScalar(str, schema.tags, schema.tags.scalarFallback);
7021   } catch (error) {
7022     if (!error.source) error.source = node;
7023     errors.push(error);
7024     return null;
7025   }
7026 } // sets node.resolved on success
7027
7028
7029 function resolveNode(doc, node) {
7030   if (!node) return null;
7031   if (node.error) doc.errors.push(node.error);
7032   const {
7033     comments,
7034     hasAnchor,
7035     hasTag
7036   } = resolveNodeProps(doc.errors, node);
7037
7038   if (hasAnchor) {
7039     const {
7040       anchors
7041     } = doc;
7042     const name = node.anchor;
7043     const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor
7044     // name have already been resolved, so it may safely be renamed.
7045
7046     if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as
7047     // anchors need to be available during resolution to allow for
7048     // circular references.
7049
7050     anchors.map[name] = node;
7051   }
7052
7053   if (node.type === PlainValueEc8e588e.Type.ALIAS && (hasAnchor || hasTag)) {
7054     const msg = 'An alias node must not specify any properties';
7055     doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(node, msg));
7056   }
7057
7058   const res = resolveNodeValue(doc, node);
7059
7060   if (res) {
7061     res.range = [node.range.start, node.range.end];
7062     if (doc.options.keepCstNodes) res.cstNode = node;
7063     if (doc.options.keepNodeTypes) res.type = node.type;
7064     const cb = comments.before.join('\n');
7065
7066     if (cb) {
7067       res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb;
7068     }
7069
7070     const ca = comments.after.join('\n');
7071     if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca;
7072   }
7073
7074   return node.resolved = res;
7075 }
7076
7077 function resolveMap(doc, cst) {
7078   if (cst.type !== PlainValueEc8e588e.Type.MAP && cst.type !== PlainValueEc8e588e.Type.FLOW_MAP) {
7079     const msg = `A ${cst.type} node cannot be resolved as a mapping`;
7080     doc.errors.push(new PlainValueEc8e588e.YAMLSyntaxError(cst, msg));
7081     return null;
7082   }
7083
7084   const {
7085     comments,
7086     items
7087   } = cst.type === PlainValueEc8e588e.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst);
7088   const map = new YAMLMap();
7089   map.items = items;
7090   resolveComments(map, comments);
7091   let hasCollectionKey = false;
7092
7093   for (let i = 0; i < items.length; ++i) {
7094     const {
7095       key: iKey
7096     } = items[i];
7097     if (iKey instanceof Collection$1) hasCollectionKey = true;
7098
7099     if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) {
7100       items[i] = new Merge(items[i]);
7101       const sources = items[i].value.items;
7102       let error = null;
7103       sources.some(node => {
7104         if (node instanceof Alias$1) {
7105           // During parsing, alias sources are CST nodes; to account for
7106           // circular references their resolved values can't be used here.
7107           const {
7108             type
7109           } = node.source;
7110           if (type === PlainValueEc8e588e.Type.MAP || type === PlainValueEc8e588e.Type.FLOW_MAP) return false;
7111           return error = 'Merge nodes aliases can only point to maps';
7112         }
7113
7114         return error = 'Merge nodes can only have Alias nodes as values';
7115       });
7116       if (error) doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(cst, error));
7117     } else {
7118       for (let j = i + 1; j < items.length; ++j) {
7119         const {
7120           key: jKey
7121         } = items[j];
7122
7123         if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) {
7124           const msg = `Map keys must be unique; "${iKey}" is repeated`;
7125           doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(cst, msg));
7126           break;
7127         }
7128       }
7129     }
7130   }
7131
7132   if (hasCollectionKey && !doc.options.mapAsMap) {
7133     const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
7134     doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(cst, warn));
7135   }
7136
7137   cst.resolved = map;
7138   return map;
7139 }
7140
7141 const valueHasPairComment = ({
7142   context: {
7143     lineStart,
7144     node,
7145     src
7146   },
7147   props
7148 }) => {
7149   if (props.length === 0) return false;
7150   const {
7151     start
7152   } = props[0];
7153   if (node && start > node.valueRange.start) return false;
7154   if (src[start] !== PlainValueEc8e588e.Char.COMMENT) return false;
7155
7156   for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false;
7157
7158   return true;
7159 };
7160
7161 function resolvePairComment(item, pair) {
7162   if (!valueHasPairComment(item)) return;
7163   const comment = item.getPropValue(0, PlainValueEc8e588e.Char.COMMENT, true);
7164   let found = false;
7165   const cb = pair.value.commentBefore;
7166
7167   if (cb && cb.startsWith(comment)) {
7168     pair.value.commentBefore = cb.substr(comment.length + 1);
7169     found = true;
7170   } else {
7171     const cc = pair.value.comment;
7172
7173     if (!item.node && cc && cc.startsWith(comment)) {
7174       pair.value.comment = cc.substr(comment.length + 1);
7175       found = true;
7176     }
7177   }
7178
7179   if (found) pair.comment = comment;
7180 }
7181
7182 function resolveBlockMapItems(doc, cst) {
7183   const comments = [];
7184   const items = [];
7185   let key = undefined;
7186   let keyStart = null;
7187
7188   for (let i = 0; i < cst.items.length; ++i) {
7189     const item = cst.items[i];
7190
7191     switch (item.type) {
7192       case PlainValueEc8e588e.Type.BLANK_LINE:
7193         comments.push({
7194           afterKey: !!key,
7195           before: items.length
7196         });
7197         break;
7198
7199       case PlainValueEc8e588e.Type.COMMENT:
7200         comments.push({
7201           afterKey: !!key,
7202           before: items.length,
7203           comment: item.comment
7204         });
7205         break;
7206
7207       case PlainValueEc8e588e.Type.MAP_KEY:
7208         if (key !== undefined) items.push(new Pair(key));
7209         if (item.error) doc.errors.push(item.error);
7210         key = resolveNode(doc, item.node);
7211         keyStart = null;
7212         break;
7213
7214       case PlainValueEc8e588e.Type.MAP_VALUE:
7215         {
7216           if (key === undefined) key = null;
7217           if (item.error) doc.errors.push(item.error);
7218
7219           if (!item.context.atLineStart && item.node && item.node.type === PlainValueEc8e588e.Type.MAP && !item.node.context.atLineStart) {
7220             const msg = 'Nested mappings are not allowed in compact mappings';
7221             doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item.node, msg));
7222           }
7223
7224           let valueNode = item.node;
7225
7226           if (!valueNode && item.props.length > 0) {
7227             // Comments on an empty mapping value need to be preserved, so we
7228             // need to construct a minimal empty node here to use instead of the
7229             // missing `item.node`. -- eemeli/yaml#19
7230             valueNode = new PlainValueEc8e588e.PlainValue(PlainValueEc8e588e.Type.PLAIN, []);
7231             valueNode.context = {
7232               parent: item,
7233               src: item.context.src
7234             };
7235             const pos = item.range.start + 1;
7236             valueNode.range = {
7237               start: pos,
7238               end: pos
7239             };
7240             valueNode.valueRange = {
7241               start: pos,
7242               end: pos
7243             };
7244
7245             if (typeof item.range.origStart === 'number') {
7246               const origPos = item.range.origStart + 1;
7247               valueNode.range.origStart = valueNode.range.origEnd = origPos;
7248               valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos;
7249             }
7250           }
7251
7252           const pair = new Pair(key, resolveNode(doc, valueNode));
7253           resolvePairComment(item, pair);
7254           items.push(pair);
7255
7256           if (key && typeof keyStart === 'number') {
7257             if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
7258           }
7259
7260           key = undefined;
7261           keyStart = null;
7262         }
7263         break;
7264
7265       default:
7266         if (key !== undefined) items.push(new Pair(key));
7267         key = resolveNode(doc, item);
7268         keyStart = item.range.start;
7269         if (item.error) doc.errors.push(item.error);
7270
7271         next: for (let j = i + 1;; ++j) {
7272           const nextItem = cst.items[j];
7273
7274           switch (nextItem && nextItem.type) {
7275             case PlainValueEc8e588e.Type.BLANK_LINE:
7276             case PlainValueEc8e588e.Type.COMMENT:
7277               continue next;
7278
7279             case PlainValueEc8e588e.Type.MAP_VALUE:
7280               break next;
7281
7282             default:
7283               {
7284                 const msg = 'Implicit map keys need to be followed by map values';
7285                 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, msg));
7286                 break next;
7287               }
7288           }
7289         }
7290
7291         if (item.valueRangeContainsNewline) {
7292           const msg = 'Implicit map keys need to be on a single line';
7293           doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, msg));
7294         }
7295
7296     }
7297   }
7298
7299   if (key !== undefined) items.push(new Pair(key));
7300   return {
7301     comments,
7302     items
7303   };
7304 }
7305
7306 function resolveFlowMapItems(doc, cst) {
7307   const comments = [];
7308   const items = [];
7309   let key = undefined;
7310   let explicitKey = false;
7311   let next = '{';
7312
7313   for (let i = 0; i < cst.items.length; ++i) {
7314     const item = cst.items[i];
7315
7316     if (typeof item.char === 'string') {
7317       const {
7318         char,
7319         offset
7320       } = item;
7321
7322       if (char === '?' && key === undefined && !explicitKey) {
7323         explicitKey = true;
7324         next = ':';
7325         continue;
7326       }
7327
7328       if (char === ':') {
7329         if (key === undefined) key = null;
7330
7331         if (next === ':') {
7332           next = ',';
7333           continue;
7334         }
7335       } else {
7336         if (explicitKey) {
7337           if (key === undefined && char !== ',') key = null;
7338           explicitKey = false;
7339         }
7340
7341         if (key !== undefined) {
7342           items.push(new Pair(key));
7343           key = undefined;
7344
7345           if (char === ',') {
7346             next = ':';
7347             continue;
7348           }
7349         }
7350       }
7351
7352       if (char === '}') {
7353         if (i === cst.items.length - 1) continue;
7354       } else if (char === next) {
7355         next = ':';
7356         continue;
7357       }
7358
7359       const msg = `Flow map contains an unexpected ${char}`;
7360       const err = new PlainValueEc8e588e.YAMLSyntaxError(cst, msg);
7361       err.offset = offset;
7362       doc.errors.push(err);
7363     } else if (item.type === PlainValueEc8e588e.Type.BLANK_LINE) {
7364       comments.push({
7365         afterKey: !!key,
7366         before: items.length
7367       });
7368     } else if (item.type === PlainValueEc8e588e.Type.COMMENT) {
7369       checkFlowCommentSpace(doc.errors, item);
7370       comments.push({
7371         afterKey: !!key,
7372         before: items.length,
7373         comment: item.comment
7374       });
7375     } else if (key === undefined) {
7376       if (next === ',') doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, 'Separator , missing in flow map'));
7377       key = resolveNode(doc, item);
7378     } else {
7379       if (next !== ',') doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, 'Indicator : missing in flow map entry'));
7380       items.push(new Pair(key, resolveNode(doc, item)));
7381       key = undefined;
7382       explicitKey = false;
7383     }
7384   }
7385
7386   checkFlowCollectionEnd(doc.errors, cst);
7387   if (key !== undefined) items.push(new Pair(key));
7388   return {
7389     comments,
7390     items
7391   };
7392 }
7393
7394 function resolveSeq(doc, cst) {
7395   if (cst.type !== PlainValueEc8e588e.Type.SEQ && cst.type !== PlainValueEc8e588e.Type.FLOW_SEQ) {
7396     const msg = `A ${cst.type} node cannot be resolved as a sequence`;
7397     doc.errors.push(new PlainValueEc8e588e.YAMLSyntaxError(cst, msg));
7398     return null;
7399   }
7400
7401   const {
7402     comments,
7403     items
7404   } = cst.type === PlainValueEc8e588e.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst);
7405   const seq = new YAMLSeq();
7406   seq.items = items;
7407   resolveComments(seq, comments);
7408
7409   if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection$1)) {
7410     const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
7411     doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(cst, warn));
7412   }
7413
7414   cst.resolved = seq;
7415   return seq;
7416 }
7417
7418 function resolveBlockSeqItems(doc, cst) {
7419   const comments = [];
7420   const items = [];
7421
7422   for (let i = 0; i < cst.items.length; ++i) {
7423     const item = cst.items[i];
7424
7425     switch (item.type) {
7426       case PlainValueEc8e588e.Type.BLANK_LINE:
7427         comments.push({
7428           before: items.length
7429         });
7430         break;
7431
7432       case PlainValueEc8e588e.Type.COMMENT:
7433         comments.push({
7434           comment: item.comment,
7435           before: items.length
7436         });
7437         break;
7438
7439       case PlainValueEc8e588e.Type.SEQ_ITEM:
7440         if (item.error) doc.errors.push(item.error);
7441         items.push(resolveNode(doc, item.node));
7442
7443         if (item.hasProps) {
7444           const msg = 'Sequence items cannot have tags or anchors before the - indicator';
7445           doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, msg));
7446         }
7447
7448         break;
7449
7450       default:
7451         if (item.error) doc.errors.push(item.error);
7452         doc.errors.push(new PlainValueEc8e588e.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`));
7453     }
7454   }
7455
7456   return {
7457     comments,
7458     items
7459   };
7460 }
7461
7462 function resolveFlowSeqItems(doc, cst) {
7463   const comments = [];
7464   const items = [];
7465   let explicitKey = false;
7466   let key = undefined;
7467   let keyStart = null;
7468   let next = '[';
7469   let prevItem = null;
7470
7471   for (let i = 0; i < cst.items.length; ++i) {
7472     const item = cst.items[i];
7473
7474     if (typeof item.char === 'string') {
7475       const {
7476         char,
7477         offset
7478       } = item;
7479
7480       if (char !== ':' && (explicitKey || key !== undefined)) {
7481         if (explicitKey && key === undefined) key = next ? items.pop() : null;
7482         items.push(new Pair(key));
7483         explicitKey = false;
7484         key = undefined;
7485         keyStart = null;
7486       }
7487
7488       if (char === next) {
7489         next = null;
7490       } else if (!next && char === '?') {
7491         explicitKey = true;
7492       } else if (next !== '[' && char === ':' && key === undefined) {
7493         if (next === ',') {
7494           key = items.pop();
7495
7496           if (key instanceof Pair) {
7497             const msg = 'Chaining flow sequence pairs is invalid';
7498             const err = new PlainValueEc8e588e.YAMLSemanticError(cst, msg);
7499             err.offset = offset;
7500             doc.errors.push(err);
7501           }
7502
7503           if (!explicitKey && typeof keyStart === 'number') {
7504             const keyEnd = item.range ? item.range.start : item.offset;
7505             if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
7506             const {
7507               src
7508             } = prevItem.context;
7509
7510             for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') {
7511               const msg = 'Implicit keys of flow sequence pairs need to be on a single line';
7512               doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(prevItem, msg));
7513               break;
7514             }
7515           }
7516         } else {
7517           key = null;
7518         }
7519
7520         keyStart = null;
7521         explicitKey = false;
7522         next = null;
7523       } else if (next === '[' || char !== ']' || i < cst.items.length - 1) {
7524         const msg = `Flow sequence contains an unexpected ${char}`;
7525         const err = new PlainValueEc8e588e.YAMLSyntaxError(cst, msg);
7526         err.offset = offset;
7527         doc.errors.push(err);
7528       }
7529     } else if (item.type === PlainValueEc8e588e.Type.BLANK_LINE) {
7530       comments.push({
7531         before: items.length
7532       });
7533     } else if (item.type === PlainValueEc8e588e.Type.COMMENT) {
7534       checkFlowCommentSpace(doc.errors, item);
7535       comments.push({
7536         comment: item.comment,
7537         before: items.length
7538       });
7539     } else {
7540       if (next) {
7541         const msg = `Expected a ${next} in flow sequence`;
7542         doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, msg));
7543       }
7544
7545       const value = resolveNode(doc, item);
7546
7547       if (key === undefined) {
7548         items.push(value);
7549         prevItem = item;
7550       } else {
7551         items.push(new Pair(key, value));
7552         key = undefined;
7553       }
7554
7555       keyStart = item.range.start;
7556       next = ',';
7557     }
7558   }
7559
7560   checkFlowCollectionEnd(doc.errors, cst);
7561   if (key !== undefined) items.push(new Pair(key));
7562   return {
7563     comments,
7564     items
7565   };
7566 }
7567
7568 var Alias_1 = Alias$1;
7569 var Collection_1 = Collection$1;
7570 var Merge_1 = Merge;
7571 var Node_1$1 = Node$1;
7572 var Pair_1 = Pair;
7573 var Scalar_1 = Scalar;
7574 var YAMLMap_1 = YAMLMap;
7575 var YAMLSeq_1 = YAMLSeq;
7576 var addComment_1 = addComment;
7577 var binaryOptions_1 = binaryOptions;
7578 var boolOptions_1 = boolOptions;
7579 var findPair_1 = findPair;
7580 var intOptions_1 = intOptions;
7581 var isEmptyPath_1 = isEmptyPath;
7582 var nullOptions_1 = nullOptions;
7583 var resolveMap_1 = resolveMap;
7584 var resolveNode_1 = resolveNode;
7585 var resolveSeq_1 = resolveSeq;
7586 var resolveString_1 = resolveString;
7587 var strOptions_1 = strOptions;
7588 var stringifyNumber_1 = stringifyNumber;
7589 var stringifyString_1 = stringifyString;
7590 var toJSON_1 = toJSON;
7591 var resolveSeq4a68b39b = {
7592   Alias: Alias_1,
7593   Collection: Collection_1,
7594   Merge: Merge_1,
7595   Node: Node_1$1,
7596   Pair: Pair_1,
7597   Scalar: Scalar_1,
7598   YAMLMap: YAMLMap_1,
7599   YAMLSeq: YAMLSeq_1,
7600   addComment: addComment_1,
7601   binaryOptions: binaryOptions_1,
7602   boolOptions: boolOptions_1,
7603   findPair: findPair_1,
7604   intOptions: intOptions_1,
7605   isEmptyPath: isEmptyPath_1,
7606   nullOptions: nullOptions_1,
7607   resolveMap: resolveMap_1,
7608   resolveNode: resolveNode_1,
7609   resolveSeq: resolveSeq_1,
7610   resolveString: resolveString_1,
7611   strOptions: strOptions_1,
7612   stringifyNumber: stringifyNumber_1,
7613   stringifyString: stringifyString_1,
7614   toJSON: toJSON_1
7615 };
7616
7617 /* global atob, btoa, Buffer */
7618
7619
7620 const binary = {
7621   identify: value => value instanceof Uint8Array,
7622   // Buffer inherits from Uint8Array
7623   default: false,
7624   tag: 'tag:yaml.org,2002:binary',
7625
7626   /**
7627    * Returns a Buffer in node and an Uint8Array in browsers
7628    *
7629    * To use the resulting buffer as an image, you'll want to do something like:
7630    *
7631    *   const blob = new Blob([buffer], { type: 'image/jpeg' })
7632    *   document.querySelector('#photo').src = URL.createObjectURL(blob)
7633    */
7634   resolve: (doc, node) => {
7635     const src = resolveSeq4a68b39b.resolveString(doc, node);
7636
7637     if (typeof Buffer === 'function') {
7638       return Buffer.from(src, 'base64');
7639     } else if (typeof atob === 'function') {
7640       // On IE 11, atob() can't handle newlines
7641       const str = atob(src.replace(/[\n\r]/g, ''));
7642       const buffer = new Uint8Array(str.length);
7643
7644       for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i);
7645
7646       return buffer;
7647     } else {
7648       const msg = 'This environment does not support reading binary tags; either Buffer or atob is required';
7649       doc.errors.push(new PlainValueEc8e588e.YAMLReferenceError(node, msg));
7650       return null;
7651     }
7652   },
7653   options: resolveSeq4a68b39b.binaryOptions,
7654   stringify: ({
7655     comment,
7656     type,
7657     value
7658   }, ctx, onComment, onChompKeep) => {
7659     let src;
7660
7661     if (typeof Buffer === 'function') {
7662       src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64');
7663     } else if (typeof btoa === 'function') {
7664       let s = '';
7665
7666       for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]);
7667
7668       src = btoa(s);
7669     } else {
7670       throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
7671     }
7672
7673     if (!type) type = resolveSeq4a68b39b.binaryOptions.defaultType;
7674
7675     if (type === PlainValueEc8e588e.Type.QUOTE_DOUBLE) {
7676       value = src;
7677     } else {
7678       const {
7679         lineWidth
7680       } = resolveSeq4a68b39b.binaryOptions;
7681       const n = Math.ceil(src.length / lineWidth);
7682       const lines = new Array(n);
7683
7684       for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
7685         lines[i] = src.substr(o, lineWidth);
7686       }
7687
7688       value = lines.join(type === PlainValueEc8e588e.Type.BLOCK_LITERAL ? '\n' : ' ');
7689     }
7690
7691     return resolveSeq4a68b39b.stringifyString({
7692       comment,
7693       type,
7694       value
7695     }, ctx, onComment, onChompKeep);
7696   }
7697 };
7698
7699 function parsePairs(doc, cst) {
7700   const seq = resolveSeq4a68b39b.resolveSeq(doc, cst);
7701
7702   for (let i = 0; i < seq.items.length; ++i) {
7703     let item = seq.items[i];
7704     if (item instanceof resolveSeq4a68b39b.Pair) continue;else if (item instanceof resolveSeq4a68b39b.YAMLMap) {
7705       if (item.items.length > 1) {
7706         const msg = 'Each pair must have its own sequence indicator';
7707         throw new PlainValueEc8e588e.YAMLSemanticError(cst, msg);
7708       }
7709
7710       const pair = item.items[0] || new resolveSeq4a68b39b.Pair();
7711       if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore;
7712       if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment;
7713       item = pair;
7714     }
7715     seq.items[i] = item instanceof resolveSeq4a68b39b.Pair ? item : new resolveSeq4a68b39b.Pair(item);
7716   }
7717
7718   return seq;
7719 }
7720
7721 function createPairs(schema, iterable, ctx) {
7722   const pairs = new resolveSeq4a68b39b.YAMLSeq(schema);
7723   pairs.tag = 'tag:yaml.org,2002:pairs';
7724
7725   for (const it of iterable) {
7726     let key, value;
7727
7728     if (Array.isArray(it)) {
7729       if (it.length === 2) {
7730         key = it[0];
7731         value = it[1];
7732       } else throw new TypeError(`Expected [key, value] tuple: ${it}`);
7733     } else if (it && it instanceof Object) {
7734       const keys = Object.keys(it);
7735
7736       if (keys.length === 1) {
7737         key = keys[0];
7738         value = it[key];
7739       } else throw new TypeError(`Expected { key: value } tuple: ${it}`);
7740     } else {
7741       key = it;
7742     }
7743
7744     const pair = schema.createPair(key, value, ctx);
7745     pairs.items.push(pair);
7746   }
7747
7748   return pairs;
7749 }
7750
7751 const pairs = {
7752   default: false,
7753   tag: 'tag:yaml.org,2002:pairs',
7754   resolve: parsePairs,
7755   createNode: createPairs
7756 };
7757
7758 class YAMLOMap extends resolveSeq4a68b39b.YAMLSeq {
7759   constructor() {
7760     super();
7761
7762     PlainValueEc8e588e._defineProperty(this, "add", resolveSeq4a68b39b.YAMLMap.prototype.add.bind(this));
7763
7764     PlainValueEc8e588e._defineProperty(this, "delete", resolveSeq4a68b39b.YAMLMap.prototype.delete.bind(this));
7765
7766     PlainValueEc8e588e._defineProperty(this, "get", resolveSeq4a68b39b.YAMLMap.prototype.get.bind(this));
7767
7768     PlainValueEc8e588e._defineProperty(this, "has", resolveSeq4a68b39b.YAMLMap.prototype.has.bind(this));
7769
7770     PlainValueEc8e588e._defineProperty(this, "set", resolveSeq4a68b39b.YAMLMap.prototype.set.bind(this));
7771
7772     this.tag = YAMLOMap.tag;
7773   }
7774
7775   toJSON(_, ctx) {
7776     const map = new Map();
7777     if (ctx && ctx.onCreate) ctx.onCreate(map);
7778
7779     for (const pair of this.items) {
7780       let key, value;
7781
7782       if (pair instanceof resolveSeq4a68b39b.Pair) {
7783         key = resolveSeq4a68b39b.toJSON(pair.key, '', ctx);
7784         value = resolveSeq4a68b39b.toJSON(pair.value, key, ctx);
7785       } else {
7786         key = resolveSeq4a68b39b.toJSON(pair, '', ctx);
7787       }
7788
7789       if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys');
7790       map.set(key, value);
7791     }
7792
7793     return map;
7794   }
7795
7796 }
7797
7798 PlainValueEc8e588e._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap');
7799
7800 function parseOMap(doc, cst) {
7801   const pairs = parsePairs(doc, cst);
7802   const seenKeys = [];
7803
7804   for (const {
7805     key
7806   } of pairs.items) {
7807     if (key instanceof resolveSeq4a68b39b.Scalar) {
7808       if (seenKeys.includes(key.value)) {
7809         const msg = 'Ordered maps must not include duplicate keys';
7810         throw new PlainValueEc8e588e.YAMLSemanticError(cst, msg);
7811       } else {
7812         seenKeys.push(key.value);
7813       }
7814     }
7815   }
7816
7817   return Object.assign(new YAMLOMap(), pairs);
7818 }
7819
7820 function createOMap(schema, iterable, ctx) {
7821   const pairs = createPairs(schema, iterable, ctx);
7822   const omap = new YAMLOMap();
7823   omap.items = pairs.items;
7824   return omap;
7825 }
7826
7827 const omap = {
7828   identify: value => value instanceof Map,
7829   nodeClass: YAMLOMap,
7830   default: false,
7831   tag: 'tag:yaml.org,2002:omap',
7832   resolve: parseOMap,
7833   createNode: createOMap
7834 };
7835
7836 class YAMLSet extends resolveSeq4a68b39b.YAMLMap {
7837   constructor() {
7838     super();
7839     this.tag = YAMLSet.tag;
7840   }
7841
7842   add(key) {
7843     const pair = key instanceof resolveSeq4a68b39b.Pair ? key : new resolveSeq4a68b39b.Pair(key);
7844     const prev = resolveSeq4a68b39b.findPair(this.items, pair.key);
7845     if (!prev) this.items.push(pair);
7846   }
7847
7848   get(key, keepPair) {
7849     const pair = resolveSeq4a68b39b.findPair(this.items, key);
7850     return !keepPair && pair instanceof resolveSeq4a68b39b.Pair ? pair.key instanceof resolveSeq4a68b39b.Scalar ? pair.key.value : pair.key : pair;
7851   }
7852
7853   set(key, value) {
7854     if (typeof value !== 'boolean') throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
7855     const prev = resolveSeq4a68b39b.findPair(this.items, key);
7856
7857     if (prev && !value) {
7858       this.items.splice(this.items.indexOf(prev), 1);
7859     } else if (!prev && value) {
7860       this.items.push(new resolveSeq4a68b39b.Pair(key));
7861     }
7862   }
7863
7864   toJSON(_, ctx) {
7865     return super.toJSON(_, ctx, Set);
7866   }
7867
7868   toString(ctx, onComment, onChompKeep) {
7869     if (!ctx) return JSON.stringify(this);
7870     if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values');
7871   }
7872
7873 }
7874
7875 PlainValueEc8e588e._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set');
7876
7877 function parseSet(doc, cst) {
7878   const map = resolveSeq4a68b39b.resolveMap(doc, cst);
7879   if (!map.hasAllNullValues()) throw new PlainValueEc8e588e.YAMLSemanticError(cst, 'Set items must all have null values');
7880   return Object.assign(new YAMLSet(), map);
7881 }
7882
7883 function createSet(schema, iterable, ctx) {
7884   const set = new YAMLSet();
7885
7886   for (const value of iterable) set.items.push(schema.createPair(value, null, ctx));
7887
7888   return set;
7889 }
7890
7891 const set = {
7892   identify: value => value instanceof Set,
7893   nodeClass: YAMLSet,
7894   default: false,
7895   tag: 'tag:yaml.org,2002:set',
7896   resolve: parseSet,
7897   createNode: createSet
7898 };
7899
7900 const parseSexagesimal = (sign, parts) => {
7901   const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0);
7902   return sign === '-' ? -n : n;
7903 }; // hhhh:mm:ss.sss
7904
7905
7906 const stringifySexagesimal = ({
7907   value
7908 }) => {
7909   if (isNaN(value) || !isFinite(value)) return resolveSeq4a68b39b.stringifyNumber(value);
7910   let sign = '';
7911
7912   if (value < 0) {
7913     sign = '-';
7914     value = Math.abs(value);
7915   }
7916
7917   const parts = [value % 60]; // seconds, including ms
7918
7919   if (value < 60) {
7920     parts.unshift(0); // at least one : is required
7921   } else {
7922     value = Math.round((value - parts[0]) / 60);
7923     parts.unshift(value % 60); // minutes
7924
7925     if (value >= 60) {
7926       value = Math.round((value - parts[0]) / 60);
7927       parts.unshift(value); // hours
7928     }
7929   }
7930
7931   return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error
7932   ;
7933 };
7934
7935 const intTime = {
7936   identify: value => typeof value === 'number',
7937   default: true,
7938   tag: 'tag:yaml.org,2002:int',
7939   format: 'TIME',
7940   test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,
7941   resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')),
7942   stringify: stringifySexagesimal
7943 };
7944 const floatTime = {
7945   identify: value => typeof value === 'number',
7946   default: true,
7947   tag: 'tag:yaml.org,2002:float',
7948   format: 'TIME',
7949   test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,
7950   resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')),
7951   stringify: stringifySexagesimal
7952 };
7953 const timestamp = {
7954   identify: value => value instanceof Date,
7955   default: true,
7956   tag: 'tag:yaml.org,2002:timestamp',
7957   // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
7958   // may be omitted altogether, resulting in a date format. In such a case, the time part is
7959   // assumed to be 00:00:00Z (start of day, UTC).
7960   test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
7961   '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace
7962   '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
7963   '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
7964   ')?' + ')$'),
7965   resolve: (str, year, month, day, hour, minute, second, millisec, tz) => {
7966     if (millisec) millisec = (millisec + '00').substr(1, 3);
7967     let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0);
7968
7969     if (tz && tz !== 'Z') {
7970       let d = parseSexagesimal(tz[0], tz.slice(1));
7971       if (Math.abs(d) < 30) d *= 60;
7972       date -= 60000 * d;
7973     }
7974
7975     return new Date(date);
7976   },
7977   stringify: ({
7978     value
7979   }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '')
7980 };
7981 /* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */
7982
7983 function shouldWarn(deprecation) {
7984   const env = typeof process !== 'undefined' && process.env || {};
7985
7986   if (deprecation) {
7987     if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS;
7988     return !env.YAML_SILENCE_DEPRECATION_WARNINGS;
7989   }
7990
7991   if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS;
7992   return !env.YAML_SILENCE_WARNINGS;
7993 }
7994
7995 function warn(warning, type) {
7996   if (shouldWarn(false)) {
7997     const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to
7998     // https://github.com/facebook/jest/issues/2549
7999
8000     if (emit) emit(warning, type);else {
8001       // eslint-disable-next-line no-console
8002       console.warn(type ? `${type}: ${warning}` : warning);
8003     }
8004   }
8005 }
8006
8007 function warnFileDeprecation(filename) {
8008   if (shouldWarn(true)) {
8009     const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/');
8010     warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning');
8011   }
8012 }
8013
8014 const warned = {};
8015
8016 function warnOptionDeprecation(name, alternative) {
8017   if (!warned[name] && shouldWarn(true)) {
8018     warned[name] = true;
8019     let msg = `The option '${name}' will be removed in a future release`;
8020     msg += alternative ? `, use '${alternative}' instead.` : '.';
8021     warn(msg, 'DeprecationWarning');
8022   }
8023 }
8024
8025 var binary_1 = binary;
8026 var floatTime_1 = floatTime;
8027 var intTime_1 = intTime;
8028 var omap_1 = omap;
8029 var pairs_1 = pairs;
8030 var set_1 = set;
8031 var timestamp_1 = timestamp;
8032 var warn_1 = warn;
8033 var warnFileDeprecation_1 = warnFileDeprecation;
8034 var warnOptionDeprecation_1 = warnOptionDeprecation;
8035 var warnings39684f17 = {
8036   binary: binary_1,
8037   floatTime: floatTime_1,
8038   intTime: intTime_1,
8039   omap: omap_1,
8040   pairs: pairs_1,
8041   set: set_1,
8042   timestamp: timestamp_1,
8043   warn: warn_1,
8044   warnFileDeprecation: warnFileDeprecation_1,
8045   warnOptionDeprecation: warnOptionDeprecation_1
8046 };
8047
8048 function createMap(schema, obj, ctx) {
8049   const map = new resolveSeq4a68b39b.YAMLMap(schema);
8050
8051   if (obj instanceof Map) {
8052     for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx));
8053   } else if (obj && typeof obj === 'object') {
8054     for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx));
8055   }
8056
8057   if (typeof schema.sortMapEntries === 'function') {
8058     map.items.sort(schema.sortMapEntries);
8059   }
8060
8061   return map;
8062 }
8063
8064 const map = {
8065   createNode: createMap,
8066   default: true,
8067   nodeClass: resolveSeq4a68b39b.YAMLMap,
8068   tag: 'tag:yaml.org,2002:map',
8069   resolve: resolveSeq4a68b39b.resolveMap
8070 };
8071
8072 function createSeq(schema, obj, ctx) {
8073   const seq = new resolveSeq4a68b39b.YAMLSeq(schema);
8074
8075   if (obj && obj[Symbol.iterator]) {
8076     for (const it of obj) {
8077       const v = schema.createNode(it, ctx.wrapScalars, null, ctx);
8078       seq.items.push(v);
8079     }
8080   }
8081
8082   return seq;
8083 }
8084
8085 const seq = {
8086   createNode: createSeq,
8087   default: true,
8088   nodeClass: resolveSeq4a68b39b.YAMLSeq,
8089   tag: 'tag:yaml.org,2002:seq',
8090   resolve: resolveSeq4a68b39b.resolveSeq
8091 };
8092 const string = {
8093   identify: value => typeof value === 'string',
8094   default: true,
8095   tag: 'tag:yaml.org,2002:str',
8096   resolve: resolveSeq4a68b39b.resolveString,
8097
8098   stringify(item, ctx, onComment, onChompKeep) {
8099     ctx = Object.assign({
8100       actualString: true
8101     }, ctx);
8102     return resolveSeq4a68b39b.stringifyString(item, ctx, onComment, onChompKeep);
8103   },
8104
8105   options: resolveSeq4a68b39b.strOptions
8106 };
8107 const failsafe = [map, seq, string];
8108 /* global BigInt */
8109
8110 const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value);
8111
8112 const intResolve = (src, part, radix) => resolveSeq4a68b39b.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix);
8113
8114 function intStringify(node, radix, prefix) {
8115   const {
8116     value
8117   } = node;
8118   if (intIdentify(value) && value >= 0) return prefix + value.toString(radix);
8119   return resolveSeq4a68b39b.stringifyNumber(node);
8120 }
8121
8122 const nullObj = {
8123   identify: value => value == null,
8124   createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq4a68b39b.Scalar(null) : null,
8125   default: true,
8126   tag: 'tag:yaml.org,2002:null',
8127   test: /^(?:~|[Nn]ull|NULL)?$/,
8128   resolve: () => null,
8129   options: resolveSeq4a68b39b.nullOptions,
8130   stringify: () => resolveSeq4a68b39b.nullOptions.nullStr
8131 };
8132 const boolObj = {
8133   identify: value => typeof value === 'boolean',
8134   default: true,
8135   tag: 'tag:yaml.org,2002:bool',
8136   test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
8137   resolve: str => str[0] === 't' || str[0] === 'T',
8138   options: resolveSeq4a68b39b.boolOptions,
8139   stringify: ({
8140     value
8141   }) => value ? resolveSeq4a68b39b.boolOptions.trueStr : resolveSeq4a68b39b.boolOptions.falseStr
8142 };
8143 const octObj = {
8144   identify: value => intIdentify(value) && value >= 0,
8145   default: true,
8146   tag: 'tag:yaml.org,2002:int',
8147   format: 'OCT',
8148   test: /^0o([0-7]+)$/,
8149   resolve: (str, oct) => intResolve(str, oct, 8),
8150   options: resolveSeq4a68b39b.intOptions,
8151   stringify: node => intStringify(node, 8, '0o')
8152 };
8153 const intObj = {
8154   identify: intIdentify,
8155   default: true,
8156   tag: 'tag:yaml.org,2002:int',
8157   test: /^[-+]?[0-9]+$/,
8158   resolve: str => intResolve(str, str, 10),
8159   options: resolveSeq4a68b39b.intOptions,
8160   stringify: resolveSeq4a68b39b.stringifyNumber
8161 };
8162 const hexObj = {
8163   identify: value => intIdentify(value) && value >= 0,
8164   default: true,
8165   tag: 'tag:yaml.org,2002:int',
8166   format: 'HEX',
8167   test: /^0x([0-9a-fA-F]+)$/,
8168   resolve: (str, hex) => intResolve(str, hex, 16),
8169   options: resolveSeq4a68b39b.intOptions,
8170   stringify: node => intStringify(node, 16, '0x')
8171 };
8172 const nanObj = {
8173   identify: value => typeof value === 'number',
8174   default: true,
8175   tag: 'tag:yaml.org,2002:float',
8176   test: /^(?:[-+]?\.inf|(\.nan))$/i,
8177   resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
8178   stringify: resolveSeq4a68b39b.stringifyNumber
8179 };
8180 const expObj = {
8181   identify: value => typeof value === 'number',
8182   default: true,
8183   tag: 'tag:yaml.org,2002:float',
8184   format: 'EXP',
8185   test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
8186   resolve: str => parseFloat(str),
8187   stringify: ({
8188     value
8189   }) => Number(value).toExponential()
8190 };
8191 const floatObj = {
8192   identify: value => typeof value === 'number',
8193   default: true,
8194   tag: 'tag:yaml.org,2002:float',
8195   test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,
8196
8197   resolve(str, frac1, frac2) {
8198     const frac = frac1 || frac2;
8199     const node = new resolveSeq4a68b39b.Scalar(parseFloat(str));
8200     if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length;
8201     return node;
8202   },
8203
8204   stringify: resolveSeq4a68b39b.stringifyNumber
8205 };
8206 const core = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]);
8207 /* global BigInt */
8208
8209 const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value);
8210
8211 const stringifyJSON = ({
8212   value
8213 }) => JSON.stringify(value);
8214
8215 const json = [map, seq, {
8216   identify: value => typeof value === 'string',
8217   default: true,
8218   tag: 'tag:yaml.org,2002:str',
8219   resolve: resolveSeq4a68b39b.resolveString,
8220   stringify: stringifyJSON
8221 }, {
8222   identify: value => value == null,
8223   createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq4a68b39b.Scalar(null) : null,
8224   default: true,
8225   tag: 'tag:yaml.org,2002:null',
8226   test: /^null$/,
8227   resolve: () => null,
8228   stringify: stringifyJSON
8229 }, {
8230   identify: value => typeof value === 'boolean',
8231   default: true,
8232   tag: 'tag:yaml.org,2002:bool',
8233   test: /^true|false$/,
8234   resolve: str => str === 'true',
8235   stringify: stringifyJSON
8236 }, {
8237   identify: intIdentify$1,
8238   default: true,
8239   tag: 'tag:yaml.org,2002:int',
8240   test: /^-?(?:0|[1-9][0-9]*)$/,
8241   resolve: str => resolveSeq4a68b39b.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10),
8242   stringify: ({
8243     value
8244   }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value)
8245 }, {
8246   identify: value => typeof value === 'number',
8247   default: true,
8248   tag: 'tag:yaml.org,2002:float',
8249   test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
8250   resolve: str => parseFloat(str),
8251   stringify: stringifyJSON
8252 }];
8253
8254 json.scalarFallback = str => {
8255   throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`);
8256 };
8257 /* global BigInt */
8258
8259
8260 const boolStringify = ({
8261   value
8262 }) => value ? resolveSeq4a68b39b.boolOptions.trueStr : resolveSeq4a68b39b.boolOptions.falseStr;
8263
8264 const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value);
8265
8266 function intResolve$1(sign, src, radix) {
8267   let str = src.replace(/_/g, '');
8268
8269   if (resolveSeq4a68b39b.intOptions.asBigInt) {
8270     switch (radix) {
8271       case 2:
8272         str = `0b${str}`;
8273         break;
8274
8275       case 8:
8276         str = `0o${str}`;
8277         break;
8278
8279       case 16:
8280         str = `0x${str}`;
8281         break;
8282     }
8283
8284     const n = BigInt(str);
8285     return sign === '-' ? BigInt(-1) * n : n;
8286   }
8287
8288   const n = parseInt(str, radix);
8289   return sign === '-' ? -1 * n : n;
8290 }
8291
8292 function intStringify$1(node, radix, prefix) {
8293   const {
8294     value
8295   } = node;
8296
8297   if (intIdentify$2(value)) {
8298     const str = value.toString(radix);
8299     return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
8300   }
8301
8302   return resolveSeq4a68b39b.stringifyNumber(node);
8303 }
8304
8305 const yaml11 = failsafe.concat([{
8306   identify: value => value == null,
8307   createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq4a68b39b.Scalar(null) : null,
8308   default: true,
8309   tag: 'tag:yaml.org,2002:null',
8310   test: /^(?:~|[Nn]ull|NULL)?$/,
8311   resolve: () => null,
8312   options: resolveSeq4a68b39b.nullOptions,
8313   stringify: () => resolveSeq4a68b39b.nullOptions.nullStr
8314 }, {
8315   identify: value => typeof value === 'boolean',
8316   default: true,
8317   tag: 'tag:yaml.org,2002:bool',
8318   test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
8319   resolve: () => true,
8320   options: resolveSeq4a68b39b.boolOptions,
8321   stringify: boolStringify
8322 }, {
8323   identify: value => typeof value === 'boolean',
8324   default: true,
8325   tag: 'tag:yaml.org,2002:bool',
8326   test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,
8327   resolve: () => false,
8328   options: resolveSeq4a68b39b.boolOptions,
8329   stringify: boolStringify
8330 }, {
8331   identify: intIdentify$2,
8332   default: true,
8333   tag: 'tag:yaml.org,2002:int',
8334   format: 'BIN',
8335   test: /^([-+]?)0b([0-1_]+)$/,
8336   resolve: (str, sign, bin) => intResolve$1(sign, bin, 2),
8337   stringify: node => intStringify$1(node, 2, '0b')
8338 }, {
8339   identify: intIdentify$2,
8340   default: true,
8341   tag: 'tag:yaml.org,2002:int',
8342   format: 'OCT',
8343   test: /^([-+]?)0([0-7_]+)$/,
8344   resolve: (str, sign, oct) => intResolve$1(sign, oct, 8),
8345   stringify: node => intStringify$1(node, 8, '0')
8346 }, {
8347   identify: intIdentify$2,
8348   default: true,
8349   tag: 'tag:yaml.org,2002:int',
8350   test: /^([-+]?)([0-9][0-9_]*)$/,
8351   resolve: (str, sign, abs) => intResolve$1(sign, abs, 10),
8352   stringify: resolveSeq4a68b39b.stringifyNumber
8353 }, {
8354   identify: intIdentify$2,
8355   default: true,
8356   tag: 'tag:yaml.org,2002:int',
8357   format: 'HEX',
8358   test: /^([-+]?)0x([0-9a-fA-F_]+)$/,
8359   resolve: (str, sign, hex) => intResolve$1(sign, hex, 16),
8360   stringify: node => intStringify$1(node, 16, '0x')
8361 }, {
8362   identify: value => typeof value === 'number',
8363   default: true,
8364   tag: 'tag:yaml.org,2002:float',
8365   test: /^(?:[-+]?\.inf|(\.nan))$/i,
8366   resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
8367   stringify: resolveSeq4a68b39b.stringifyNumber
8368 }, {
8369   identify: value => typeof value === 'number',
8370   default: true,
8371   tag: 'tag:yaml.org,2002:float',
8372   format: 'EXP',
8373   test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,
8374   resolve: str => parseFloat(str.replace(/_/g, '')),
8375   stringify: ({
8376     value
8377   }) => Number(value).toExponential()
8378 }, {
8379   identify: value => typeof value === 'number',
8380   default: true,
8381   tag: 'tag:yaml.org,2002:float',
8382   test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,
8383
8384   resolve(str, frac) {
8385     const node = new resolveSeq4a68b39b.Scalar(parseFloat(str.replace(/_/g, '')));
8386
8387     if (frac) {
8388       const f = frac.replace(/_/g, '');
8389       if (f[f.length - 1] === '0') node.minFractionDigits = f.length;
8390     }
8391
8392     return node;
8393   },
8394
8395   stringify: resolveSeq4a68b39b.stringifyNumber
8396 }], warnings39684f17.binary, warnings39684f17.omap, warnings39684f17.pairs, warnings39684f17.set, warnings39684f17.intTime, warnings39684f17.floatTime, warnings39684f17.timestamp);
8397 const schemas = {
8398   core,
8399   failsafe,
8400   json,
8401   yaml11
8402 };
8403 const tags = {
8404   binary: warnings39684f17.binary,
8405   bool: boolObj,
8406   float: floatObj,
8407   floatExp: expObj,
8408   floatNaN: nanObj,
8409   floatTime: warnings39684f17.floatTime,
8410   int: intObj,
8411   intHex: hexObj,
8412   intOct: octObj,
8413   intTime: warnings39684f17.intTime,
8414   map,
8415   null: nullObj,
8416   omap: warnings39684f17.omap,
8417   pairs: warnings39684f17.pairs,
8418   seq,
8419   set: warnings39684f17.set,
8420   timestamp: warnings39684f17.timestamp
8421 };
8422
8423 function findTagObject(value, tagName, tags) {
8424   if (tagName) {
8425     const match = tags.filter(t => t.tag === tagName);
8426     const tagObj = match.find(t => !t.format) || match[0];
8427     if (!tagObj) throw new Error(`Tag ${tagName} not found`);
8428     return tagObj;
8429   } // TODO: deprecate/remove class check
8430
8431
8432   return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format);
8433 }
8434
8435 function createNode(value, tagName, ctx) {
8436   if (value instanceof resolveSeq4a68b39b.Node) return value;
8437   const {
8438     defaultPrefix,
8439     onTagObj,
8440     prevObjects,
8441     schema,
8442     wrapScalars
8443   } = ctx;
8444   if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2);
8445   let tagObj = findTagObject(value, tagName, schema.tags);
8446
8447   if (!tagObj) {
8448     if (typeof value.toJSON === 'function') value = value.toJSON();
8449     if (typeof value !== 'object') return wrapScalars ? new resolveSeq4a68b39b.Scalar(value) : value;
8450     tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map;
8451   }
8452
8453   if (onTagObj) {
8454     onTagObj(tagObj);
8455     delete ctx.onTagObj;
8456   } // Detect duplicate references to the same object & use Alias nodes for all
8457   // after first. The `obj` wrapper allows for circular references to resolve.
8458
8459
8460   const obj = {};
8461
8462   if (value && typeof value === 'object' && prevObjects) {
8463     const prev = prevObjects.get(value);
8464
8465     if (prev) {
8466       const alias = new resolveSeq4a68b39b.Alias(prev); // leaves source dirty; must be cleaned by caller
8467
8468       ctx.aliasNodes.push(alias); // defined along with prevObjects
8469
8470       return alias;
8471     }
8472
8473     obj.value = value;
8474     prevObjects.set(value, obj);
8475   }
8476
8477   obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq4a68b39b.Scalar(value) : value;
8478   if (tagName && obj.node instanceof resolveSeq4a68b39b.Node) obj.node.tag = tagName;
8479   return obj.node;
8480 }
8481
8482 function getSchemaTags(schemas, knownTags, customTags, schemaId) {
8483   let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11'
8484
8485   if (!tags) {
8486     const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', ');
8487     throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`);
8488   }
8489
8490   if (Array.isArray(customTags)) {
8491     for (const tag of customTags) tags = tags.concat(tag);
8492   } else if (typeof customTags === 'function') {
8493     tags = customTags(tags.slice());
8494   }
8495
8496   for (let i = 0; i < tags.length; ++i) {
8497     const tag = tags[i];
8498
8499     if (typeof tag === 'string') {
8500       const tagObj = knownTags[tag];
8501
8502       if (!tagObj) {
8503         const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', ');
8504         throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
8505       }
8506
8507       tags[i] = tagObj;
8508     }
8509   }
8510
8511   return tags;
8512 }
8513
8514 const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
8515
8516 class Schema {
8517   // TODO: remove in v2
8518   // TODO: remove in v2
8519   constructor({
8520     customTags,
8521     merge,
8522     schema,
8523     sortMapEntries,
8524     tags: deprecatedCustomTags
8525   }) {
8526     this.merge = !!merge;
8527     this.name = schema;
8528     this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null;
8529     if (!customTags && deprecatedCustomTags) warnings39684f17.warnOptionDeprecation('tags', 'customTags');
8530     this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema);
8531   }
8532
8533   createNode(value, wrapScalars, tagName, ctx) {
8534     const baseCtx = {
8535       defaultPrefix: Schema.defaultPrefix,
8536       schema: this,
8537       wrapScalars
8538     };
8539     const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx;
8540     return createNode(value, tagName, createCtx);
8541   }
8542
8543   createPair(key, value, ctx) {
8544     if (!ctx) ctx = {
8545       wrapScalars: true
8546     };
8547     const k = this.createNode(key, ctx.wrapScalars, null, ctx);
8548     const v = this.createNode(value, ctx.wrapScalars, null, ctx);
8549     return new resolveSeq4a68b39b.Pair(k, v);
8550   }
8551
8552 }
8553
8554 PlainValueEc8e588e._defineProperty(Schema, "defaultPrefix", PlainValueEc8e588e.defaultTagPrefix);
8555
8556 PlainValueEc8e588e._defineProperty(Schema, "defaultTags", PlainValueEc8e588e.defaultTags);
8557
8558 var Schema_1 = Schema;
8559 var Schema42e9705c = {
8560   Schema: Schema_1
8561 };
8562
8563 const defaultOptions = {
8564   anchorPrefix: 'a',
8565   customTags: null,
8566   indent: 2,
8567   indentSeq: true,
8568   keepCstNodes: false,
8569   keepNodeTypes: true,
8570   keepBlobsInJSON: true,
8571   mapAsMap: false,
8572   maxAliasCount: 100,
8573   prettyErrors: false,
8574   // TODO Set true in v2
8575   simpleKeys: false,
8576   version: '1.2'
8577 };
8578 const scalarOptions = {
8579   get binary() {
8580     return resolveSeq4a68b39b.binaryOptions;
8581   },
8582
8583   set binary(opt) {
8584     Object.assign(resolveSeq4a68b39b.binaryOptions, opt);
8585   },
8586
8587   get bool() {
8588     return resolveSeq4a68b39b.boolOptions;
8589   },
8590
8591   set bool(opt) {
8592     Object.assign(resolveSeq4a68b39b.boolOptions, opt);
8593   },
8594
8595   get int() {
8596     return resolveSeq4a68b39b.intOptions;
8597   },
8598
8599   set int(opt) {
8600     Object.assign(resolveSeq4a68b39b.intOptions, opt);
8601   },
8602
8603   get null() {
8604     return resolveSeq4a68b39b.nullOptions;
8605   },
8606
8607   set null(opt) {
8608     Object.assign(resolveSeq4a68b39b.nullOptions, opt);
8609   },
8610
8611   get str() {
8612     return resolveSeq4a68b39b.strOptions;
8613   },
8614
8615   set str(opt) {
8616     Object.assign(resolveSeq4a68b39b.strOptions, opt);
8617   }
8618
8619 };
8620 const documentOptions = {
8621   '1.0': {
8622     schema: 'yaml-1.1',
8623     merge: true,
8624     tagPrefixes: [{
8625       handle: '!',
8626       prefix: PlainValueEc8e588e.defaultTagPrefix
8627     }, {
8628       handle: '!!',
8629       prefix: 'tag:private.yaml.org,2002:'
8630     }]
8631   },
8632   '1.1': {
8633     schema: 'yaml-1.1',
8634     merge: true,
8635     tagPrefixes: [{
8636       handle: '!',
8637       prefix: '!'
8638     }, {
8639       handle: '!!',
8640       prefix: PlainValueEc8e588e.defaultTagPrefix
8641     }]
8642   },
8643   '1.2': {
8644     schema: 'core',
8645     merge: false,
8646     tagPrefixes: [{
8647       handle: '!',
8648       prefix: '!'
8649     }, {
8650       handle: '!!',
8651       prefix: PlainValueEc8e588e.defaultTagPrefix
8652     }]
8653   }
8654 };
8655
8656 function stringifyTag(doc, tag) {
8657   if ((doc.version || doc.options.version) === '1.0') {
8658     const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);
8659     if (priv) return '!' + priv[1];
8660     const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);
8661     return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`;
8662   }
8663
8664   let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0);
8665
8666   if (!p) {
8667     const dtp = doc.getDefaults().tagPrefixes;
8668     p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0);
8669   }
8670
8671   if (!p) return tag[0] === '!' ? tag : `!<${tag}>`;
8672   const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({
8673     '!': '%21',
8674     ',': '%2C',
8675     '[': '%5B',
8676     ']': '%5D',
8677     '{': '%7B',
8678     '}': '%7D'
8679   })[ch]);
8680   return p.handle + suffix;
8681 }
8682
8683 function getTagObject(tags, item) {
8684   if (item instanceof resolveSeq4a68b39b.Alias) return resolveSeq4a68b39b.Alias;
8685
8686   if (item.tag) {
8687     const match = tags.filter(t => t.tag === item.tag);
8688     if (match.length > 0) return match.find(t => t.format === item.format) || match[0];
8689   }
8690
8691   let tagObj, obj;
8692
8693   if (item instanceof resolveSeq4a68b39b.Scalar) {
8694     obj = item.value; // TODO: deprecate/remove class check
8695
8696     const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class);
8697     tagObj = match.find(t => t.format === item.format) || match.find(t => !t.format);
8698   } else {
8699     obj = item;
8700     tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
8701   }
8702
8703   if (!tagObj) {
8704     const name = obj && obj.constructor ? obj.constructor.name : typeof obj;
8705     throw new Error(`Tag not resolved for ${name} value`);
8706   }
8707
8708   return tagObj;
8709 } // needs to be called before value stringifier to allow for circular anchor refs
8710
8711
8712 function stringifyProps(node, tagObj, {
8713   anchors,
8714   doc
8715 }) {
8716   const props = [];
8717   const anchor = doc.anchors.getName(node);
8718
8719   if (anchor) {
8720     anchors[anchor] = node;
8721     props.push(`&${anchor}`);
8722   }
8723
8724   if (node.tag) {
8725     props.push(stringifyTag(doc, node.tag));
8726   } else if (!tagObj.default) {
8727     props.push(stringifyTag(doc, tagObj.tag));
8728   }
8729
8730   return props.join(' ');
8731 }
8732
8733 function stringify(item, ctx, onComment, onChompKeep) {
8734   const {
8735     anchors,
8736     schema
8737   } = ctx.doc;
8738   let tagObj;
8739
8740   if (!(item instanceof resolveSeq4a68b39b.Node)) {
8741     const createCtx = {
8742       aliasNodes: [],
8743       onTagObj: o => tagObj = o,
8744       prevObjects: new Map()
8745     };
8746     item = schema.createNode(item, true, null, createCtx);
8747
8748     for (const alias of createCtx.aliasNodes) {
8749       alias.source = alias.source.node;
8750       let name = anchors.getName(alias.source);
8751
8752       if (!name) {
8753         name = anchors.newName();
8754         anchors.map[name] = alias.source;
8755       }
8756     }
8757   }
8758
8759   if (item instanceof resolveSeq4a68b39b.Pair) return item.toString(ctx, onComment, onChompKeep);
8760   if (!tagObj) tagObj = getTagObject(schema.tags, item);
8761   const props = stringifyProps(item, tagObj, ctx);
8762   if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1;
8763   const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq4a68b39b.Scalar ? resolveSeq4a68b39b.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep);
8764   if (!props) return str;
8765   return item instanceof resolveSeq4a68b39b.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`;
8766 }
8767
8768 class Anchors {
8769   static validAnchorNode(node) {
8770     return node instanceof resolveSeq4a68b39b.Scalar || node instanceof resolveSeq4a68b39b.YAMLSeq || node instanceof resolveSeq4a68b39b.YAMLMap;
8771   }
8772
8773   constructor(prefix) {
8774     PlainValueEc8e588e._defineProperty(this, "map", {});
8775
8776     this.prefix = prefix;
8777   }
8778
8779   createAlias(node, name) {
8780     this.setAnchor(node, name);
8781     return new resolveSeq4a68b39b.Alias(node);
8782   }
8783
8784   createMergePair(...sources) {
8785     const merge = new resolveSeq4a68b39b.Merge();
8786     merge.value.items = sources.map(s => {
8787       if (s instanceof resolveSeq4a68b39b.Alias) {
8788         if (s.source instanceof resolveSeq4a68b39b.YAMLMap) return s;
8789       } else if (s instanceof resolveSeq4a68b39b.YAMLMap) {
8790         return this.createAlias(s);
8791       }
8792
8793       throw new Error('Merge sources must be Map nodes or their Aliases');
8794     });
8795     return merge;
8796   }
8797
8798   getName(node) {
8799     const {
8800       map
8801     } = this;
8802     return Object.keys(map).find(a => map[a] === node);
8803   }
8804
8805   getNames() {
8806     return Object.keys(this.map);
8807   }
8808
8809   getNode(name) {
8810     return this.map[name];
8811   }
8812
8813   newName(prefix) {
8814     if (!prefix) prefix = this.prefix;
8815     const names = Object.keys(this.map);
8816
8817     for (let i = 1; true; ++i) {
8818       const name = `${prefix}${i}`;
8819       if (!names.includes(name)) return name;
8820     }
8821   } // During parsing, map & aliases contain CST nodes
8822
8823
8824   resolveNodes() {
8825     const {
8826       map,
8827       _cstAliases
8828     } = this;
8829     Object.keys(map).forEach(a => {
8830       map[a] = map[a].resolved;
8831     });
8832
8833     _cstAliases.forEach(a => {
8834       a.source = a.source.resolved;
8835     });
8836
8837     delete this._cstAliases;
8838   }
8839
8840   setAnchor(node, name) {
8841     if (node != null && !Anchors.validAnchorNode(node)) {
8842       throw new Error('Anchors may only be set for Scalar, Seq and Map nodes');
8843     }
8844
8845     if (name && /[\x00-\x19\s,[\]{}]/.test(name)) {
8846       throw new Error('Anchor names must not contain whitespace or control characters');
8847     }
8848
8849     const {
8850       map
8851     } = this;
8852     const prev = node && Object.keys(map).find(a => map[a] === node);
8853
8854     if (prev) {
8855       if (!name) {
8856         return prev;
8857       } else if (prev !== name) {
8858         delete map[prev];
8859         map[name] = node;
8860       }
8861     } else {
8862       if (!name) {
8863         if (!node) return null;
8864         name = this.newName();
8865       }
8866
8867       map[name] = node;
8868     }
8869
8870     return name;
8871   }
8872
8873 }
8874
8875 const visit = (node, tags) => {
8876   if (node && typeof node === 'object') {
8877     const {
8878       tag
8879     } = node;
8880
8881     if (node instanceof resolveSeq4a68b39b.Collection) {
8882       if (tag) tags[tag] = true;
8883       node.items.forEach(n => visit(n, tags));
8884     } else if (node instanceof resolveSeq4a68b39b.Pair) {
8885       visit(node.key, tags);
8886       visit(node.value, tags);
8887     } else if (node instanceof resolveSeq4a68b39b.Scalar) {
8888       if (tag) tags[tag] = true;
8889     }
8890   }
8891
8892   return tags;
8893 };
8894
8895 const listTagNames = node => Object.keys(visit(node, {}));
8896
8897 function parseContents(doc, contents) {
8898   const comments = {
8899     before: [],
8900     after: []
8901   };
8902   let body = undefined;
8903   let spaceBefore = false;
8904
8905   for (const node of contents) {
8906     if (node.valueRange) {
8907       if (body !== undefined) {
8908         const msg = 'Document contains trailing content not separated by a ... or --- line';
8909         doc.errors.push(new PlainValueEc8e588e.YAMLSyntaxError(node, msg));
8910         break;
8911       }
8912
8913       const res = resolveSeq4a68b39b.resolveNode(doc, node);
8914
8915       if (spaceBefore) {
8916         res.spaceBefore = true;
8917         spaceBefore = false;
8918       }
8919
8920       body = res;
8921     } else if (node.comment !== null) {
8922       const cc = body === undefined ? comments.before : comments.after;
8923       cc.push(node.comment);
8924     } else if (node.type === PlainValueEc8e588e.Type.BLANK_LINE) {
8925       spaceBefore = true;
8926
8927       if (body === undefined && comments.before.length > 0 && !doc.commentBefore) {
8928         // space-separated comments at start are parsed as document comments
8929         doc.commentBefore = comments.before.join('\n');
8930         comments.before = [];
8931       }
8932     }
8933   }
8934
8935   doc.contents = body || null;
8936
8937   if (!body) {
8938     doc.comment = comments.before.concat(comments.after).join('\n') || null;
8939   } else {
8940     const cb = comments.before.join('\n');
8941
8942     if (cb) {
8943       const cbNode = body instanceof resolveSeq4a68b39b.Collection && body.items[0] ? body.items[0] : body;
8944       cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb;
8945     }
8946
8947     doc.comment = comments.after.join('\n') || null;
8948   }
8949 }
8950
8951 function resolveTagDirective({
8952   tagPrefixes
8953 }, directive) {
8954   const [handle, prefix] = directive.parameters;
8955
8956   if (!handle || !prefix) {
8957     const msg = 'Insufficient parameters given for %TAG directive';
8958     throw new PlainValueEc8e588e.YAMLSemanticError(directive, msg);
8959   }
8960
8961   if (tagPrefixes.some(p => p.handle === handle)) {
8962     const msg = 'The %TAG directive must only be given at most once per handle in the same document.';
8963     throw new PlainValueEc8e588e.YAMLSemanticError(directive, msg);
8964   }
8965
8966   return {
8967     handle,
8968     prefix
8969   };
8970 }
8971
8972 function resolveYamlDirective(doc, directive) {
8973   let [version] = directive.parameters;
8974   if (directive.name === 'YAML:1.0') version = '1.0';
8975
8976   if (!version) {
8977     const msg = 'Insufficient parameters given for %YAML directive';
8978     throw new PlainValueEc8e588e.YAMLSemanticError(directive, msg);
8979   }
8980
8981   if (!documentOptions[version]) {
8982     const v0 = doc.version || doc.options.version;
8983     const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`;
8984     doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(directive, msg));
8985   }
8986
8987   return version;
8988 }
8989
8990 function parseDirectives(doc, directives, prevDoc) {
8991   const directiveComments = [];
8992   let hasDirectives = false;
8993
8994   for (const directive of directives) {
8995     const {
8996       comment,
8997       name
8998     } = directive;
8999
9000     switch (name) {
9001       case 'TAG':
9002         try {
9003           doc.tagPrefixes.push(resolveTagDirective(doc, directive));
9004         } catch (error) {
9005           doc.errors.push(error);
9006         }
9007
9008         hasDirectives = true;
9009         break;
9010
9011       case 'YAML':
9012       case 'YAML:1.0':
9013         if (doc.version) {
9014           const msg = 'The %YAML directive must only be given at most once per document.';
9015           doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(directive, msg));
9016         }
9017
9018         try {
9019           doc.version = resolveYamlDirective(doc, directive);
9020         } catch (error) {
9021           doc.errors.push(error);
9022         }
9023
9024         hasDirectives = true;
9025         break;
9026
9027       default:
9028         if (name) {
9029           const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`;
9030           doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(directive, msg));
9031         }
9032
9033     }
9034
9035     if (comment) directiveComments.push(comment);
9036   }
9037
9038   if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) {
9039     const copyTagPrefix = ({
9040       handle,
9041       prefix
9042     }) => ({
9043       handle,
9044       prefix
9045     });
9046
9047     doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix);
9048     doc.version = prevDoc.version;
9049   }
9050
9051   doc.commentBefore = directiveComments.join('\n') || null;
9052 }
9053
9054 function assertCollection(contents) {
9055   if (contents instanceof resolveSeq4a68b39b.Collection) return true;
9056   throw new Error('Expected a YAML collection as document contents');
9057 }
9058
9059 class Document$1 {
9060   constructor(options) {
9061     this.anchors = new Anchors(options.anchorPrefix);
9062     this.commentBefore = null;
9063     this.comment = null;
9064     this.contents = null;
9065     this.directivesEndMarker = null;
9066     this.errors = [];
9067     this.options = options;
9068     this.schema = null;
9069     this.tagPrefixes = [];
9070     this.version = null;
9071     this.warnings = [];
9072   }
9073
9074   add(value) {
9075     assertCollection(this.contents);
9076     return this.contents.add(value);
9077   }
9078
9079   addIn(path, value) {
9080     assertCollection(this.contents);
9081     this.contents.addIn(path, value);
9082   }
9083
9084   delete(key) {
9085     assertCollection(this.contents);
9086     return this.contents.delete(key);
9087   }
9088
9089   deleteIn(path) {
9090     if (resolveSeq4a68b39b.isEmptyPath(path)) {
9091       if (this.contents == null) return false;
9092       this.contents = null;
9093       return true;
9094     }
9095
9096     assertCollection(this.contents);
9097     return this.contents.deleteIn(path);
9098   }
9099
9100   getDefaults() {
9101     return Document$1.defaults[this.version] || Document$1.defaults[this.options.version] || {};
9102   }
9103
9104   get(key, keepScalar) {
9105     return this.contents instanceof resolveSeq4a68b39b.Collection ? this.contents.get(key, keepScalar) : undefined;
9106   }
9107
9108   getIn(path, keepScalar) {
9109     if (resolveSeq4a68b39b.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq4a68b39b.Scalar ? this.contents.value : this.contents;
9110     return this.contents instanceof resolveSeq4a68b39b.Collection ? this.contents.getIn(path, keepScalar) : undefined;
9111   }
9112
9113   has(key) {
9114     return this.contents instanceof resolveSeq4a68b39b.Collection ? this.contents.has(key) : false;
9115   }
9116
9117   hasIn(path) {
9118     if (resolveSeq4a68b39b.isEmptyPath(path)) return this.contents !== undefined;
9119     return this.contents instanceof resolveSeq4a68b39b.Collection ? this.contents.hasIn(path) : false;
9120   }
9121
9122   set(key, value) {
9123     assertCollection(this.contents);
9124     this.contents.set(key, value);
9125   }
9126
9127   setIn(path, value) {
9128     if (resolveSeq4a68b39b.isEmptyPath(path)) this.contents = value;else {
9129       assertCollection(this.contents);
9130       this.contents.setIn(path, value);
9131     }
9132   }
9133
9134   setSchema(id, customTags) {
9135     if (!id && !customTags && this.schema) return;
9136     if (typeof id === 'number') id = id.toFixed(1);
9137
9138     if (id === '1.0' || id === '1.1' || id === '1.2') {
9139       if (this.version) this.version = id;else this.options.version = id;
9140       delete this.options.schema;
9141     } else if (id && typeof id === 'string') {
9142       this.options.schema = id;
9143     }
9144
9145     if (Array.isArray(customTags)) this.options.customTags = customTags;
9146     const opt = Object.assign({}, this.getDefaults(), this.options);
9147     this.schema = new Schema42e9705c.Schema(opt);
9148   }
9149
9150   parse(node, prevDoc) {
9151     if (this.options.keepCstNodes) this.cstNode = node;
9152     if (this.options.keepNodeTypes) this.type = 'DOCUMENT';
9153     const {
9154       directives = [],
9155       contents = [],
9156       directivesEndMarker,
9157       error,
9158       valueRange
9159     } = node;
9160
9161     if (error) {
9162       if (!error.source) error.source = this;
9163       this.errors.push(error);
9164     }
9165
9166     parseDirectives(this, directives, prevDoc);
9167     if (directivesEndMarker) this.directivesEndMarker = true;
9168     this.range = valueRange ? [valueRange.start, valueRange.end] : null;
9169     this.setSchema();
9170     this.anchors._cstAliases = [];
9171     parseContents(this, contents);
9172     this.anchors.resolveNodes();
9173
9174     if (this.options.prettyErrors) {
9175       for (const error of this.errors) if (error instanceof PlainValueEc8e588e.YAMLError) error.makePretty();
9176
9177       for (const warn of this.warnings) if (warn instanceof PlainValueEc8e588e.YAMLError) warn.makePretty();
9178     }
9179
9180     return this;
9181   }
9182
9183   listNonDefaultTags() {
9184     return listTagNames(this.contents).filter(t => t.indexOf(Schema42e9705c.Schema.defaultPrefix) !== 0);
9185   }
9186
9187   setTagPrefix(handle, prefix) {
9188     if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !');
9189
9190     if (prefix) {
9191       const prev = this.tagPrefixes.find(p => p.handle === handle);
9192       if (prev) prev.prefix = prefix;else this.tagPrefixes.push({
9193         handle,
9194         prefix
9195       });
9196     } else {
9197       this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle);
9198     }
9199   }
9200
9201   toJSON(arg, onAnchor) {
9202     const {
9203       keepBlobsInJSON,
9204       mapAsMap,
9205       maxAliasCount
9206     } = this.options;
9207     const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq4a68b39b.Scalar));
9208     const ctx = {
9209       doc: this,
9210       indentStep: '  ',
9211       keep,
9212       mapAsMap: keep && !!mapAsMap,
9213       maxAliasCount,
9214       stringify // Requiring directly in Pair would create circular dependencies
9215
9216     };
9217     const anchorNames = Object.keys(this.anchors.map);
9218     if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], {
9219       alias: [],
9220       aliasCount: 0,
9221       count: 1
9222     }]));
9223     const res = resolveSeq4a68b39b.toJSON(this.contents, arg, ctx);
9224     if (typeof onAnchor === 'function' && ctx.anchors) for (const {
9225       count,
9226       res
9227     } of ctx.anchors.values()) onAnchor(res, count);
9228     return res;
9229   }
9230
9231   toString() {
9232     if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified');
9233     const indentSize = this.options.indent;
9234
9235     if (!Number.isInteger(indentSize) || indentSize <= 0) {
9236       const s = JSON.stringify(indentSize);
9237       throw new Error(`"indent" option must be a positive integer, not ${s}`);
9238     }
9239
9240     this.setSchema();
9241     const lines = [];
9242     let hasDirectives = false;
9243
9244     if (this.version) {
9245       let vd = '%YAML 1.2';
9246
9247       if (this.schema.name === 'yaml-1.1') {
9248         if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1';
9249       }
9250
9251       lines.push(vd);
9252       hasDirectives = true;
9253     }
9254
9255     const tagNames = this.listNonDefaultTags();
9256     this.tagPrefixes.forEach(({
9257       handle,
9258       prefix
9259     }) => {
9260       if (tagNames.some(t => t.indexOf(prefix) === 0)) {
9261         lines.push(`%TAG ${handle} ${prefix}`);
9262         hasDirectives = true;
9263       }
9264     });
9265     if (hasDirectives || this.directivesEndMarker) lines.push('---');
9266
9267     if (this.commentBefore) {
9268       if (hasDirectives || !this.directivesEndMarker) lines.unshift('');
9269       lines.unshift(this.commentBefore.replace(/^/gm, '#'));
9270     }
9271
9272     const ctx = {
9273       anchors: {},
9274       doc: this,
9275       indent: '',
9276       indentStep: ' '.repeat(indentSize),
9277       stringify // Requiring directly in nodes would create circular dependencies
9278
9279     };
9280     let chompKeep = false;
9281     let contentComment = null;
9282
9283     if (this.contents) {
9284       if (this.contents instanceof resolveSeq4a68b39b.Node) {
9285         if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push('');
9286         if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment
9287
9288         ctx.forceBlockIndent = !!this.comment;
9289         contentComment = this.contents.comment;
9290       }
9291
9292       const onChompKeep = contentComment ? null : () => chompKeep = true;
9293       const body = stringify(this.contents, ctx, () => contentComment = null, onChompKeep);
9294       lines.push(resolveSeq4a68b39b.addComment(body, '', contentComment));
9295     } else if (this.contents !== undefined) {
9296       lines.push(stringify(this.contents, ctx));
9297     }
9298
9299     if (this.comment) {
9300       if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push('');
9301       lines.push(this.comment.replace(/^/gm, '#'));
9302     }
9303
9304     return lines.join('\n') + '\n';
9305   }
9306
9307 }
9308
9309 PlainValueEc8e588e._defineProperty(Document$1, "defaults", documentOptions);
9310
9311 var Document_1 = Document$1;
9312 var defaultOptions_1 = defaultOptions;
9313 var scalarOptions_1 = scalarOptions;
9314 var Document2cf6b08c = {
9315   Document: Document_1,
9316   defaultOptions: defaultOptions_1,
9317   scalarOptions: scalarOptions_1
9318 };
9319
9320 function createNode$1(value, wrapScalars = true, tag) {
9321   if (tag === undefined && typeof wrapScalars === 'string') {
9322     tag = wrapScalars;
9323     wrapScalars = true;
9324   }
9325
9326   const options = Object.assign({}, Document2cf6b08c.Document.defaults[Document2cf6b08c.defaultOptions.version], Document2cf6b08c.defaultOptions);
9327   const schema = new Schema42e9705c.Schema(options);
9328   return schema.createNode(value, wrapScalars, tag);
9329 }
9330
9331 class Document$2 extends Document2cf6b08c.Document {
9332   constructor(options) {
9333     super(Object.assign({}, Document2cf6b08c.defaultOptions, options));
9334   }
9335
9336 }
9337
9338 function parseAllDocuments(src, options) {
9339   const stream = [];
9340   let prev;
9341
9342   for (const cstDoc of parseCst.parse(src)) {
9343     const doc = new Document$2(options);
9344     doc.parse(cstDoc, prev);
9345     stream.push(doc);
9346     prev = doc;
9347   }
9348
9349   return stream;
9350 }
9351
9352 function parseDocument(src, options) {
9353   const cst = parseCst.parse(src);
9354   const doc = new Document$2(options).parse(cst[0]);
9355
9356   if (cst.length > 1) {
9357     const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()';
9358     doc.errors.unshift(new PlainValueEc8e588e.YAMLSemanticError(cst[1], errMsg));
9359   }
9360
9361   return doc;
9362 }
9363
9364 function parse$1(src, options) {
9365   const doc = parseDocument(src, options);
9366   doc.warnings.forEach(warning => warnings39684f17.warn(warning));
9367   if (doc.errors.length > 0) throw doc.errors[0];
9368   return doc.toJSON();
9369 }
9370
9371 function stringify$1(value, options) {
9372   const doc = new Document$2(options);
9373   doc.contents = value;
9374   return String(doc);
9375 }
9376
9377 const YAML = {
9378   createNode: createNode$1,
9379   defaultOptions: Document2cf6b08c.defaultOptions,
9380   Document: Document$2,
9381   parse: parse$1,
9382   parseAllDocuments,
9383   parseCST: parseCst.parse,
9384   parseDocument,
9385   scalarOptions: Document2cf6b08c.scalarOptions,
9386   stringify: stringify$1
9387 };
9388 var YAML_1 = YAML;
9389 var dist$1 = {
9390   YAML: YAML_1
9391 };
9392
9393 var yaml = dist$1.YAML;
9394
9395 var loaders_1 = createCommonjsModule(function (module, exports) {
9396
9397   Object.defineProperty(exports, "__esModule", {
9398     value: true
9399   });
9400   exports.loaders = void 0;
9401   /* eslint-disable @typescript-eslint/no-require-imports */
9402
9403   let importFresh$1;
9404
9405   const loadJs = function loadJs(filepath) {
9406     if (importFresh$1 === undefined) {
9407       importFresh$1 = importFresh;
9408     }
9409
9410     const result = importFresh$1(filepath);
9411     return result;
9412   };
9413
9414   let parseJson;
9415
9416   const loadJson = function loadJson(filepath, content) {
9417     if (parseJson === undefined) {
9418       parseJson = parseJson$1;
9419     }
9420
9421     try {
9422       const result = parseJson(content);
9423       return result;
9424     } catch (error) {
9425       error.message = `JSON Error in ${filepath}:\n${error.message}`;
9426       throw error;
9427     }
9428   };
9429
9430   let yaml$1;
9431
9432   const loadYaml = function loadYaml(filepath, content) {
9433     if (yaml$1 === undefined) {
9434       yaml$1 = yaml;
9435     }
9436
9437     try {
9438       const result = yaml$1.parse(content, {
9439         prettyErrors: true
9440       });
9441       return result;
9442     } catch (error) {
9443       error.message = `YAML Error in ${filepath}:\n${error.message}`;
9444       throw error;
9445     }
9446   };
9447
9448   const loaders = {
9449     loadJs,
9450     loadJson,
9451     loadYaml
9452   };
9453   exports.loaders = loaders;
9454 });
9455
9456 var getPropertyByPath_1 = createCommonjsModule(function (module, exports) {
9457
9458   Object.defineProperty(exports, "__esModule", {
9459     value: true
9460   });
9461   exports.getPropertyByPath = getPropertyByPath; // Resolves property names or property paths defined with period-delimited
9462   // strings or arrays of strings. Property names that are found on the source
9463   // object are used directly (even if they include a period).
9464   // Nested property names that include periods, within a path, are only
9465   // understood in array paths.
9466
9467   function getPropertyByPath(source, path) {
9468     if (typeof path === 'string' && Object.prototype.hasOwnProperty.call(source, path)) {
9469       return source[path];
9470     }
9471
9472     const parsedPath = typeof path === 'string' ? path.split('.') : path; // eslint-disable-next-line @typescript-eslint/no-explicit-any
9473
9474     return parsedPath.reduce((previous, key) => {
9475       if (previous === undefined) {
9476         return previous;
9477       }
9478
9479       return previous[key];
9480     }, source);
9481   }
9482 });
9483
9484 var ExplorerBase_1 = createCommonjsModule(function (module, exports) {
9485
9486   Object.defineProperty(exports, "__esModule", {
9487     value: true
9488   });
9489   exports.getExtensionDescription = getExtensionDescription;
9490   exports.ExplorerBase = void 0;
9491
9492   var _path = _interopRequireDefault(path__default['default']);
9493
9494   function _interopRequireDefault(obj) {
9495     return obj && obj.__esModule ? obj : {
9496       default: obj
9497     };
9498   }
9499
9500   class ExplorerBase {
9501     constructor(options) {
9502       if (options.cache === true) {
9503         this.loadCache = new Map();
9504         this.searchCache = new Map();
9505       }
9506
9507       this.config = options;
9508       this.validateConfig();
9509     }
9510
9511     clearLoadCache() {
9512       if (this.loadCache) {
9513         this.loadCache.clear();
9514       }
9515     }
9516
9517     clearSearchCache() {
9518       if (this.searchCache) {
9519         this.searchCache.clear();
9520       }
9521     }
9522
9523     clearCaches() {
9524       this.clearLoadCache();
9525       this.clearSearchCache();
9526     }
9527
9528     validateConfig() {
9529       const config = this.config;
9530       config.searchPlaces.forEach(place => {
9531         const loaderKey = _path.default.extname(place) || 'noExt';
9532         const loader = config.loaders[loaderKey];
9533
9534         if (!loader) {
9535           throw new Error(`No loader specified for ${getExtensionDescription(place)}, so searchPlaces item "${place}" is invalid`);
9536         }
9537
9538         if (typeof loader !== 'function') {
9539           throw new Error(`loader for ${getExtensionDescription(place)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`);
9540         }
9541       });
9542     }
9543
9544     shouldSearchStopWithResult(result) {
9545       if (result === null) return false;
9546       if (result.isEmpty && this.config.ignoreEmptySearchPlaces) return false;
9547       return true;
9548     }
9549
9550     nextDirectoryToSearch(currentDir, currentResult) {
9551       if (this.shouldSearchStopWithResult(currentResult)) {
9552         return null;
9553       }
9554
9555       const nextDir = nextDirUp(currentDir);
9556
9557       if (nextDir === currentDir || currentDir === this.config.stopDir) {
9558         return null;
9559       }
9560
9561       return nextDir;
9562     }
9563
9564     loadPackageProp(filepath, content) {
9565       const parsedContent = loaders_1.loaders.loadJson(filepath, content);
9566
9567       const packagePropValue = (0, getPropertyByPath_1.getPropertyByPath)(parsedContent, this.config.packageProp);
9568       return packagePropValue || null;
9569     }
9570
9571     getLoaderEntryForFile(filepath) {
9572       if (_path.default.basename(filepath) === 'package.json') {
9573         const loader = this.loadPackageProp.bind(this);
9574         return loader;
9575       }
9576
9577       const loaderKey = _path.default.extname(filepath) || 'noExt';
9578       const loader = this.config.loaders[loaderKey];
9579
9580       if (!loader) {
9581         throw new Error(`No loader specified for ${getExtensionDescription(filepath)}`);
9582       }
9583
9584       return loader;
9585     }
9586
9587     loadedContentToCosmiconfigResult(filepath, loadedContent) {
9588       if (loadedContent === null) {
9589         return null;
9590       }
9591
9592       if (loadedContent === undefined) {
9593         return {
9594           filepath,
9595           config: undefined,
9596           isEmpty: true
9597         };
9598       }
9599
9600       return {
9601         config: loadedContent,
9602         filepath
9603       };
9604     }
9605
9606     validateFilePath(filepath) {
9607       if (!filepath) {
9608         throw new Error('load must pass a non-empty string');
9609       }
9610     }
9611
9612   }
9613
9614   exports.ExplorerBase = ExplorerBase;
9615
9616   function nextDirUp(dir) {
9617     return _path.default.dirname(dir);
9618   }
9619
9620   function getExtensionDescription(filepath) {
9621     const ext = _path.default.extname(filepath);
9622
9623     return ext ? `extension "${ext}"` : 'files without extensions';
9624   }
9625 });
9626
9627 var readFile_1 = createCommonjsModule(function (module, exports) {
9628
9629   Object.defineProperty(exports, "__esModule", {
9630     value: true
9631   });
9632   exports.readFile = readFile;
9633   exports.readFileSync = readFileSync;
9634
9635   var _fs = _interopRequireDefault(fs__default['default']);
9636
9637   function _interopRequireDefault(obj) {
9638     return obj && obj.__esModule ? obj : {
9639       default: obj
9640     };
9641   }
9642
9643   async function fsReadFileAsync(pathname, encoding) {
9644     return new Promise((resolve, reject) => {
9645       _fs.default.readFile(pathname, encoding, (error, contents) => {
9646         if (error) {
9647           reject(error);
9648           return;
9649         }
9650
9651         resolve(contents);
9652       });
9653     });
9654   }
9655
9656   async function readFile(filepath, options = {}) {
9657     const throwNotFound = options.throwNotFound === true;
9658
9659     try {
9660       const content = await fsReadFileAsync(filepath, 'utf8');
9661       return content;
9662     } catch (error) {
9663       if (throwNotFound === false && error.code === 'ENOENT') {
9664         return null;
9665       }
9666
9667       throw error;
9668     }
9669   }
9670
9671   function readFileSync(filepath, options = {}) {
9672     const throwNotFound = options.throwNotFound === true;
9673
9674     try {
9675       const content = _fs.default.readFileSync(filepath, 'utf8');
9676
9677       return content;
9678     } catch (error) {
9679       if (throwNotFound === false && error.code === 'ENOENT') {
9680         return null;
9681       }
9682
9683       throw error;
9684     }
9685   }
9686 });
9687
9688 var cacheWrapper_1 = createCommonjsModule(function (module, exports) {
9689
9690   Object.defineProperty(exports, "__esModule", {
9691     value: true
9692   });
9693   exports.cacheWrapper = cacheWrapper;
9694   exports.cacheWrapperSync = cacheWrapperSync;
9695
9696   async function cacheWrapper(cache, key, fn) {
9697     const cached = cache.get(key);
9698
9699     if (cached !== undefined) {
9700       return cached;
9701     }
9702
9703     const result = await fn();
9704     cache.set(key, result);
9705     return result;
9706   }
9707
9708   function cacheWrapperSync(cache, key, fn) {
9709     const cached = cache.get(key);
9710
9711     if (cached !== undefined) {
9712       return cached;
9713     }
9714
9715     const result = fn();
9716     cache.set(key, result);
9717     return result;
9718   }
9719 });
9720
9721 const {
9722   promisify
9723 } = util__default['default'];
9724
9725 async function isType(fsStatType, statsMethodName, filePath) {
9726   if (typeof filePath !== 'string') {
9727     throw new TypeError(`Expected a string, got ${typeof filePath}`);
9728   }
9729
9730   try {
9731     const stats = await promisify(fs__default['default'][fsStatType])(filePath);
9732     return stats[statsMethodName]();
9733   } catch (error) {
9734     if (error.code === 'ENOENT') {
9735       return false;
9736     }
9737
9738     throw error;
9739   }
9740 }
9741
9742 function isTypeSync(fsStatType, statsMethodName, filePath) {
9743   if (typeof filePath !== 'string') {
9744     throw new TypeError(`Expected a string, got ${typeof filePath}`);
9745   }
9746
9747   try {
9748     return fs__default['default'][fsStatType](filePath)[statsMethodName]();
9749   } catch (error) {
9750     if (error.code === 'ENOENT') {
9751       return false;
9752     }
9753
9754     throw error;
9755   }
9756 }
9757
9758 var isFile = isType.bind(null, 'stat', 'isFile');
9759 var isDirectory = isType.bind(null, 'stat', 'isDirectory');
9760 var isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');
9761 var isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');
9762 var isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');
9763 var isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');
9764 var pathType = {
9765   isFile: isFile,
9766   isDirectory: isDirectory,
9767   isSymlink: isSymlink,
9768   isFileSync: isFileSync,
9769   isDirectorySync: isDirectorySync,
9770   isSymlinkSync: isSymlinkSync
9771 };
9772
9773 var getDirectory_1 = createCommonjsModule(function (module, exports) {
9774
9775   Object.defineProperty(exports, "__esModule", {
9776     value: true
9777   });
9778   exports.getDirectory = getDirectory;
9779   exports.getDirectorySync = getDirectorySync;
9780
9781   var _path = _interopRequireDefault(path__default['default']);
9782
9783   function _interopRequireDefault(obj) {
9784     return obj && obj.__esModule ? obj : {
9785       default: obj
9786     };
9787   }
9788
9789   async function getDirectory(filepath) {
9790     const filePathIsDirectory = await (0, pathType.isDirectory)(filepath);
9791
9792     if (filePathIsDirectory === true) {
9793       return filepath;
9794     }
9795
9796     const directory = _path.default.dirname(filepath);
9797
9798     return directory;
9799   }
9800
9801   function getDirectorySync(filepath) {
9802     const filePathIsDirectory = (0, pathType.isDirectorySync)(filepath);
9803
9804     if (filePathIsDirectory === true) {
9805       return filepath;
9806     }
9807
9808     const directory = _path.default.dirname(filepath);
9809
9810     return directory;
9811   }
9812 });
9813
9814 var Explorer_1 = createCommonjsModule(function (module, exports) {
9815
9816   Object.defineProperty(exports, "__esModule", {
9817     value: true
9818   });
9819   exports.Explorer = void 0;
9820
9821   var _path = _interopRequireDefault(path__default['default']);
9822
9823   function _interopRequireDefault(obj) {
9824     return obj && obj.__esModule ? obj : {
9825       default: obj
9826     };
9827   }
9828
9829   class Explorer extends ExplorerBase_1.ExplorerBase {
9830     constructor(options) {
9831       super(options);
9832     }
9833
9834     async search(searchFrom = process.cwd()) {
9835       const startDirectory = await (0, getDirectory_1.getDirectory)(searchFrom);
9836       const result = await this.searchFromDirectory(startDirectory);
9837       return result;
9838     }
9839
9840     async searchFromDirectory(dir) {
9841       const absoluteDir = _path.default.resolve(process.cwd(), dir);
9842
9843       const run = async () => {
9844         const result = await this.searchDirectory(absoluteDir);
9845         const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
9846
9847         if (nextDir) {
9848           return this.searchFromDirectory(nextDir);
9849         }
9850
9851         const transformResult = await this.config.transform(result);
9852         return transformResult;
9853       };
9854
9855       if (this.searchCache) {
9856         return (0, cacheWrapper_1.cacheWrapper)(this.searchCache, absoluteDir, run);
9857       }
9858
9859       return run();
9860     }
9861
9862     async searchDirectory(dir) {
9863       for await (const place of this.config.searchPlaces) {
9864         const placeResult = await this.loadSearchPlace(dir, place);
9865
9866         if (this.shouldSearchStopWithResult(placeResult) === true) {
9867           return placeResult;
9868         }
9869       } // config not found
9870
9871
9872       return null;
9873     }
9874
9875     async loadSearchPlace(dir, place) {
9876       const filepath = _path.default.join(dir, place);
9877
9878       const fileContents = await (0, readFile_1.readFile)(filepath);
9879       const result = await this.createCosmiconfigResult(filepath, fileContents);
9880       return result;
9881     }
9882
9883     async loadFileContent(filepath, content) {
9884       if (content === null) {
9885         return null;
9886       }
9887
9888       if (content.trim() === '') {
9889         return undefined;
9890       }
9891
9892       const loader = this.getLoaderEntryForFile(filepath);
9893       const loaderResult = await loader(filepath, content);
9894       return loaderResult;
9895     }
9896
9897     async createCosmiconfigResult(filepath, content) {
9898       const fileContent = await this.loadFileContent(filepath, content);
9899       const result = this.loadedContentToCosmiconfigResult(filepath, fileContent);
9900       return result;
9901     }
9902
9903     async load(filepath) {
9904       this.validateFilePath(filepath);
9905
9906       const absoluteFilePath = _path.default.resolve(process.cwd(), filepath);
9907
9908       const runLoad = async () => {
9909         const fileContents = await (0, readFile_1.readFile)(absoluteFilePath, {
9910           throwNotFound: true
9911         });
9912         const result = await this.createCosmiconfigResult(absoluteFilePath, fileContents);
9913         const transformResult = await this.config.transform(result);
9914         return transformResult;
9915       };
9916
9917       if (this.loadCache) {
9918         return (0, cacheWrapper_1.cacheWrapper)(this.loadCache, absoluteFilePath, runLoad);
9919       }
9920
9921       return runLoad();
9922     }
9923
9924   }
9925
9926   exports.Explorer = Explorer;
9927 });
9928
9929 var ExplorerSync_1 = createCommonjsModule(function (module, exports) {
9930
9931   Object.defineProperty(exports, "__esModule", {
9932     value: true
9933   });
9934   exports.ExplorerSync = void 0;
9935
9936   var _path = _interopRequireDefault(path__default['default']);
9937
9938   function _interopRequireDefault(obj) {
9939     return obj && obj.__esModule ? obj : {
9940       default: obj
9941     };
9942   }
9943
9944   class ExplorerSync extends ExplorerBase_1.ExplorerBase {
9945     constructor(options) {
9946       super(options);
9947     }
9948
9949     searchSync(searchFrom = process.cwd()) {
9950       const startDirectory = (0, getDirectory_1.getDirectorySync)(searchFrom);
9951       const result = this.searchFromDirectorySync(startDirectory);
9952       return result;
9953     }
9954
9955     searchFromDirectorySync(dir) {
9956       const absoluteDir = _path.default.resolve(process.cwd(), dir);
9957
9958       const run = () => {
9959         const result = this.searchDirectorySync(absoluteDir);
9960         const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
9961
9962         if (nextDir) {
9963           return this.searchFromDirectorySync(nextDir);
9964         }
9965
9966         const transformResult = this.config.transform(result);
9967         return transformResult;
9968       };
9969
9970       if (this.searchCache) {
9971         return (0, cacheWrapper_1.cacheWrapperSync)(this.searchCache, absoluteDir, run);
9972       }
9973
9974       return run();
9975     }
9976
9977     searchDirectorySync(dir) {
9978       for (const place of this.config.searchPlaces) {
9979         const placeResult = this.loadSearchPlaceSync(dir, place);
9980
9981         if (this.shouldSearchStopWithResult(placeResult) === true) {
9982           return placeResult;
9983         }
9984       } // config not found
9985
9986
9987       return null;
9988     }
9989
9990     loadSearchPlaceSync(dir, place) {
9991       const filepath = _path.default.join(dir, place);
9992
9993       const content = (0, readFile_1.readFileSync)(filepath);
9994       const result = this.createCosmiconfigResultSync(filepath, content);
9995       return result;
9996     }
9997
9998     loadFileContentSync(filepath, content) {
9999       if (content === null) {
10000         return null;
10001       }
10002
10003       if (content.trim() === '') {
10004         return undefined;
10005       }
10006
10007       const loader = this.getLoaderEntryForFile(filepath);
10008       const loaderResult = loader(filepath, content);
10009       return loaderResult;
10010     }
10011
10012     createCosmiconfigResultSync(filepath, content) {
10013       const fileContent = this.loadFileContentSync(filepath, content);
10014       const result = this.loadedContentToCosmiconfigResult(filepath, fileContent);
10015       return result;
10016     }
10017
10018     loadSync(filepath) {
10019       this.validateFilePath(filepath);
10020
10021       const absoluteFilePath = _path.default.resolve(process.cwd(), filepath);
10022
10023       const runLoadSync = () => {
10024         const content = (0, readFile_1.readFileSync)(absoluteFilePath, {
10025           throwNotFound: true
10026         });
10027         const cosmiconfigResult = this.createCosmiconfigResultSync(absoluteFilePath, content);
10028         const transformResult = this.config.transform(cosmiconfigResult);
10029         return transformResult;
10030       };
10031
10032       if (this.loadCache) {
10033         return (0, cacheWrapper_1.cacheWrapperSync)(this.loadCache, absoluteFilePath, runLoadSync);
10034       }
10035
10036       return runLoadSync();
10037     }
10038
10039   }
10040
10041   exports.ExplorerSync = ExplorerSync;
10042 });
10043
10044 var dist$2 = createCommonjsModule(function (module, exports) {
10045
10046   Object.defineProperty(exports, "__esModule", {
10047     value: true
10048   });
10049   exports.cosmiconfig = cosmiconfig;
10050   exports.cosmiconfigSync = cosmiconfigSync;
10051   exports.defaultLoaders = void 0;
10052
10053   var _os = _interopRequireDefault(os__default['default']);
10054
10055   function _interopRequireDefault(obj) {
10056     return obj && obj.__esModule ? obj : {
10057       default: obj
10058     };
10059   }
10060   /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
10061   // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
10062
10063
10064   function cosmiconfig(moduleName, options = {}) {
10065     const normalizedOptions = normalizeOptions(moduleName, options);
10066     const explorer = new Explorer_1.Explorer(normalizedOptions);
10067     return {
10068       search: explorer.search.bind(explorer),
10069       load: explorer.load.bind(explorer),
10070       clearLoadCache: explorer.clearLoadCache.bind(explorer),
10071       clearSearchCache: explorer.clearSearchCache.bind(explorer),
10072       clearCaches: explorer.clearCaches.bind(explorer)
10073     };
10074   } // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
10075
10076
10077   function cosmiconfigSync(moduleName, options = {}) {
10078     const normalizedOptions = normalizeOptions(moduleName, options);
10079     const explorerSync = new ExplorerSync_1.ExplorerSync(normalizedOptions);
10080     return {
10081       search: explorerSync.searchSync.bind(explorerSync),
10082       load: explorerSync.loadSync.bind(explorerSync),
10083       clearLoadCache: explorerSync.clearLoadCache.bind(explorerSync),
10084       clearSearchCache: explorerSync.clearSearchCache.bind(explorerSync),
10085       clearCaches: explorerSync.clearCaches.bind(explorerSync)
10086     };
10087   } // do not allow mutation of default loaders. Make sure it is set inside options
10088
10089
10090   const defaultLoaders = Object.freeze({
10091     '.cjs': loaders_1.loaders.loadJs,
10092     '.js': loaders_1.loaders.loadJs,
10093     '.json': loaders_1.loaders.loadJson,
10094     '.yaml': loaders_1.loaders.loadYaml,
10095     '.yml': loaders_1.loaders.loadYaml,
10096     noExt: loaders_1.loaders.loadYaml
10097   });
10098   exports.defaultLoaders = defaultLoaders;
10099
10100   const identity = function identity(x) {
10101     return x;
10102   };
10103
10104   function normalizeOptions(moduleName, options) {
10105     const defaults = {
10106       packageProp: moduleName,
10107       searchPlaces: ['package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.js`, `.${moduleName}rc.cjs`, `${moduleName}.config.js`, `${moduleName}.config.cjs`],
10108       ignoreEmptySearchPlaces: true,
10109       stopDir: _os.default.homedir(),
10110       cache: true,
10111       transform: identity,
10112       loaders: defaultLoaders
10113     };
10114     const normalizedOptions = Object.assign({}, defaults, options, {
10115       loaders: Object.assign({}, defaults.loaders, options.loaders)
10116     });
10117     return normalizedOptions;
10118   }
10119 });
10120
10121 var findParentDir = createCommonjsModule(function (module, exports) {
10122
10123   var exists = fs__default['default'].exists || path__default['default'].exists,
10124       existsSync = fs__default['default'].existsSync || path__default['default'].existsSync;
10125
10126   function splitPath(path) {
10127     var parts = path.split(/(\/|\\)/);
10128     if (!parts.length) return parts; // when path starts with a slash, the first part is empty string
10129
10130     return !parts[0].length ? parts.slice(1) : parts;
10131   }
10132
10133   exports = module.exports = function (currentFullPath, clue, cb) {
10134     function testDir(parts) {
10135       if (parts.length === 0) return cb(null, null);
10136       var p = parts.join('');
10137       exists(path__default['default'].join(p, clue), function (itdoes) {
10138         if (itdoes) return cb(null, p);
10139         testDir(parts.slice(0, -1));
10140       });
10141     }
10142
10143     testDir(splitPath(currentFullPath));
10144   };
10145
10146   exports.sync = function (currentFullPath, clue) {
10147     function testDir(parts) {
10148       if (parts.length === 0) return null;
10149       var p = parts.join('');
10150       var itdoes = existsSync(path__default['default'].join(p, clue));
10151       return itdoes ? p : testDir(parts.slice(0, -1));
10152     }
10153
10154     return testDir(splitPath(currentFullPath));
10155   };
10156 });
10157
10158 const {
10159   stdin
10160 } = process;
10161
10162 var getStdin = async () => {
10163   let result = '';
10164
10165   if (stdin.isTTY) {
10166     return result;
10167   }
10168
10169   stdin.setEncoding('utf8');
10170
10171   for await (const chunk of stdin) {
10172     result += chunk;
10173   }
10174
10175   return result;
10176 };
10177
10178 var buffer = async () => {
10179   const result = [];
10180   let length = 0;
10181
10182   if (stdin.isTTY) {
10183     return Buffer.concat([]);
10184   }
10185
10186   for await (const chunk of stdin) {
10187     result.push(chunk);
10188     length += chunk.length;
10189   }
10190
10191   return Buffer.concat(result, length);
10192 };
10193 getStdin.buffer = buffer;
10194
10195 var vendors = [
10196         {
10197                 name: "AppVeyor",
10198                 constant: "APPVEYOR",
10199                 env: "APPVEYOR",
10200                 pr: "APPVEYOR_PULL_REQUEST_NUMBER"
10201         },
10202         {
10203                 name: "Azure Pipelines",
10204                 constant: "AZURE_PIPELINES",
10205                 env: "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI",
10206                 pr: "SYSTEM_PULLREQUEST_PULLREQUESTID"
10207         },
10208         {
10209                 name: "Bamboo",
10210                 constant: "BAMBOO",
10211                 env: "bamboo_planKey"
10212         },
10213         {
10214                 name: "Bitbucket Pipelines",
10215                 constant: "BITBUCKET",
10216                 env: "BITBUCKET_COMMIT",
10217                 pr: "BITBUCKET_PR_ID"
10218         },
10219         {
10220                 name: "Bitrise",
10221                 constant: "BITRISE",
10222                 env: "BITRISE_IO",
10223                 pr: "BITRISE_PULL_REQUEST"
10224         },
10225         {
10226                 name: "Buddy",
10227                 constant: "BUDDY",
10228                 env: "BUDDY_WORKSPACE_ID",
10229                 pr: "BUDDY_EXECUTION_PULL_REQUEST_ID"
10230         },
10231         {
10232                 name: "Buildkite",
10233                 constant: "BUILDKITE",
10234                 env: "BUILDKITE",
10235                 pr: {
10236                         env: "BUILDKITE_PULL_REQUEST",
10237                         ne: "false"
10238                 }
10239         },
10240         {
10241                 name: "CircleCI",
10242                 constant: "CIRCLE",
10243                 env: "CIRCLECI",
10244                 pr: "CIRCLE_PULL_REQUEST"
10245         },
10246         {
10247                 name: "Cirrus CI",
10248                 constant: "CIRRUS",
10249                 env: "CIRRUS_CI",
10250                 pr: "CIRRUS_PR"
10251         },
10252         {
10253                 name: "AWS CodeBuild",
10254                 constant: "CODEBUILD",
10255                 env: "CODEBUILD_BUILD_ARN"
10256         },
10257         {
10258                 name: "Codeship",
10259                 constant: "CODESHIP",
10260                 env: {
10261                         CI_NAME: "codeship"
10262                 }
10263         },
10264         {
10265                 name: "Drone",
10266                 constant: "DRONE",
10267                 env: "DRONE",
10268                 pr: {
10269                         DRONE_BUILD_EVENT: "pull_request"
10270                 }
10271         },
10272         {
10273                 name: "dsari",
10274                 constant: "DSARI",
10275                 env: "DSARI"
10276         },
10277         {
10278                 name: "GitHub Actions",
10279                 constant: "GITHUB_ACTIONS",
10280                 env: "GITHUB_ACTIONS",
10281                 pr: {
10282                         GITHUB_EVENT_NAME: "pull_request"
10283                 }
10284         },
10285         {
10286                 name: "GitLab CI",
10287                 constant: "GITLAB",
10288                 env: "GITLAB_CI"
10289         },
10290         {
10291                 name: "GoCD",
10292                 constant: "GOCD",
10293                 env: "GO_PIPELINE_LABEL"
10294         },
10295         {
10296                 name: "Hudson",
10297                 constant: "HUDSON",
10298                 env: "HUDSON_URL"
10299         },
10300         {
10301                 name: "Jenkins",
10302                 constant: "JENKINS",
10303                 env: [
10304                         "JENKINS_URL",
10305                         "BUILD_ID"
10306                 ],
10307                 pr: {
10308                         any: [
10309                                 "ghprbPullId",
10310                                 "CHANGE_ID"
10311                         ]
10312                 }
10313         },
10314         {
10315                 name: "ZEIT Now",
10316                 constant: "ZEIT_NOW",
10317                 env: "NOW_BUILDER"
10318         },
10319         {
10320                 name: "Magnum CI",
10321                 constant: "MAGNUM",
10322                 env: "MAGNUM"
10323         },
10324         {
10325                 name: "Netlify CI",
10326                 constant: "NETLIFY",
10327                 env: "NETLIFY",
10328                 pr: {
10329                         env: "PULL_REQUEST",
10330                         ne: "false"
10331                 }
10332         },
10333         {
10334                 name: "Nevercode",
10335                 constant: "NEVERCODE",
10336                 env: "NEVERCODE",
10337                 pr: {
10338                         env: "NEVERCODE_PULL_REQUEST",
10339                         ne: "false"
10340                 }
10341         },
10342         {
10343                 name: "Render",
10344                 constant: "RENDER",
10345                 env: "RENDER",
10346                 pr: {
10347                         IS_PULL_REQUEST: "true"
10348                 }
10349         },
10350         {
10351                 name: "Sail CI",
10352                 constant: "SAIL",
10353                 env: "SAILCI",
10354                 pr: "SAIL_PULL_REQUEST_NUMBER"
10355         },
10356         {
10357                 name: "Semaphore",
10358                 constant: "SEMAPHORE",
10359                 env: "SEMAPHORE",
10360                 pr: "PULL_REQUEST_NUMBER"
10361         },
10362         {
10363                 name: "Shippable",
10364                 constant: "SHIPPABLE",
10365                 env: "SHIPPABLE",
10366                 pr: {
10367                         IS_PULL_REQUEST: "true"
10368                 }
10369         },
10370         {
10371                 name: "Solano CI",
10372                 constant: "SOLANO",
10373                 env: "TDDIUM",
10374                 pr: "TDDIUM_PR_ID"
10375         },
10376         {
10377                 name: "Strider CD",
10378                 constant: "STRIDER",
10379                 env: "STRIDER"
10380         },
10381         {
10382                 name: "TaskCluster",
10383                 constant: "TASKCLUSTER",
10384                 env: [
10385                         "TASK_ID",
10386                         "RUN_ID"
10387                 ]
10388         },
10389         {
10390                 name: "TeamCity",
10391                 constant: "TEAMCITY",
10392                 env: "TEAMCITY_VERSION"
10393         },
10394         {
10395                 name: "Travis CI",
10396                 constant: "TRAVIS",
10397                 env: "TRAVIS",
10398                 pr: {
10399                         env: "TRAVIS_PULL_REQUEST",
10400                         ne: "false"
10401                 }
10402         }
10403 ];
10404
10405 var ciInfo = createCommonjsModule(function (module, exports) {
10406
10407   var env = process.env; // Used for testing only
10408
10409   Object.defineProperty(exports, '_vendors', {
10410     value: vendors.map(function (v) {
10411       return v.constant;
10412     })
10413   });
10414   exports.name = null;
10415   exports.isPR = null;
10416   vendors.forEach(function (vendor) {
10417     var envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env];
10418     var isCI = envs.every(function (obj) {
10419       return checkEnv(obj);
10420     });
10421     exports[vendor.constant] = isCI;
10422
10423     if (isCI) {
10424       exports.name = vendor.name;
10425
10426       switch (typeof vendor.pr) {
10427         case 'string':
10428           // "pr": "CIRRUS_PR"
10429           exports.isPR = !!env[vendor.pr];
10430           break;
10431
10432         case 'object':
10433           if ('env' in vendor.pr) {
10434             // "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" }
10435             exports.isPR = vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne;
10436           } else if ('any' in vendor.pr) {
10437             // "pr": { "any": ["ghprbPullId", "CHANGE_ID"] }
10438             exports.isPR = vendor.pr.any.some(function (key) {
10439               return !!env[key];
10440             });
10441           } else {
10442             // "pr": { "DRONE_BUILD_EVENT": "pull_request" }
10443             exports.isPR = checkEnv(vendor.pr);
10444           }
10445
10446           break;
10447
10448         default:
10449           // PR detection not supported for this vendor
10450           exports.isPR = null;
10451       }
10452     }
10453   });
10454   exports.isCI = !!(env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari
10455   env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
10456   env.BUILD_NUMBER || // Jenkins, TeamCity
10457   env.RUN_ID || // TaskCluster, dsari
10458   exports.name || false);
10459
10460   function checkEnv(obj) {
10461     if (typeof obj === 'string') return !!env[obj];
10462     return Object.keys(obj).every(function (k) {
10463       return env[k] === obj[k];
10464     });
10465   }
10466 });
10467
10468 var thirdParty = {
10469   cosmiconfig: dist$2.cosmiconfig,
10470   cosmiconfigSync: dist$2.cosmiconfigSync,
10471   findParentDir: findParentDir.sync,
10472   getStdin: getStdin,
10473   isCI: () => ciInfo.isCI
10474 };
10475
10476 module.exports = thirdParty;