UNPKG

198 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3'use strict';
4
5var fs$3 = require('fs');
6var path$4 = require('path');
7var meow = require('meow');
8var require$$1 = require('resolve-from');
9var stream = require('stream');
10var SVGIcons2SVGFontStream = require('svgicons2svgfont');
11var require$$0$1 = require('os');
12var require$$0 = require('parse-json');
13var crypto = require('crypto');
14var deepmerge = require('deepmerge');
15var globby = require('globby');
16var nunjucks = require('nunjucks');
17var pLimit = require('p-limit');
18var svg2ttf = require('svg2ttf');
19var ttf2eot = require('ttf2eot');
20var ttf2woff = require('ttf2woff');
21var wawoff2 = require('wawoff2');
22var xml2js = require('xml2js');
23
24function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
25
26function _interopNamespace(e) {
27 if (e && e.__esModule) return e;
28 var n = Object.create(null);
29 if (e) {
30 Object.keys(e).forEach(function (k) {
31 if (k !== 'default') {
32 var d = Object.getOwnPropertyDescriptor(e, k);
33 Object.defineProperty(n, k, d.get ? d : {
34 enumerable: true,
35 get: function () {
36 return e[k];
37 }
38 });
39 }
40 });
41 }
42 n['default'] = e;
43 return Object.freeze(n);
44}
45
46var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$3);
47var fs__namespace = /*#__PURE__*/_interopNamespace(fs$3);
48var path__default = /*#__PURE__*/_interopDefaultLegacy(path$4);
49var path__namespace = /*#__PURE__*/_interopNamespace(path$4);
50var meow__default = /*#__PURE__*/_interopDefaultLegacy(meow);
51var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
52var SVGIcons2SVGFontStream__default = /*#__PURE__*/_interopDefaultLegacy(SVGIcons2SVGFontStream);
53var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
54var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
55var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
56var deepmerge__default = /*#__PURE__*/_interopDefaultLegacy(deepmerge);
57var globby__default = /*#__PURE__*/_interopDefaultLegacy(globby);
58var nunjucks__default = /*#__PURE__*/_interopDefaultLegacy(nunjucks);
59var pLimit__default = /*#__PURE__*/_interopDefaultLegacy(pLimit);
60var svg2ttf__default = /*#__PURE__*/_interopDefaultLegacy(svg2ttf);
61var ttf2eot__default = /*#__PURE__*/_interopDefaultLegacy(ttf2eot);
62var ttf2woff__default = /*#__PURE__*/_interopDefaultLegacy(ttf2woff);
63var wawoff2__default = /*#__PURE__*/_interopDefaultLegacy(wawoff2);
64var xml2js__default = /*#__PURE__*/_interopDefaultLegacy(xml2js);
65
66/*! *****************************************************************************
67Copyright (c) Microsoft Corporation.
68
69Permission to use, copy, modify, and/or distribute this software for any
70purpose with or without fee is hereby granted.
71
72THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
73REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
74AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
75INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
76LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
77OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
78PERFORMANCE OF THIS SOFTWARE.
79***************************************************************************** */
80
81var __assign = function() {
82 __assign = Object.assign || function __assign(t) {
83 for (var s, i = 1, n = arguments.length; i < n; i++) {
84 s = arguments[i];
85 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
86 }
87 return t;
88 };
89 return __assign.apply(this, arguments);
90};
91
92function __awaiter(thisArg, _arguments, P, generator) {
93 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
94 return new (P || (P = Promise))(function (resolve, reject) {
95 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
96 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
97 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
98 step((generator = generator.apply(thisArg, _arguments || [])).next());
99 });
100}
101
102function __generator(thisArg, body) {
103 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
104 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
105 function verb(n) { return function (v) { return step([n, v]); }; }
106 function step(op) {
107 if (f) throw new TypeError("Generator is already executing.");
108 while (_) try {
109 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
110 if (y = 0, t) op = [op[0] & 2, t.value];
111 switch (op[0]) {
112 case 0: case 1: t = op; break;
113 case 4: _.label++; return { value: op[1], done: false };
114 case 5: _.label++; y = op[1]; op = [0]; continue;
115 case 7: op = _.ops.pop(); _.trys.pop(); continue;
116 default:
117 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
118 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
119 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
120 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
121 if (t[2]) _.ops.pop();
122 _.trys.pop(); continue;
123 }
124 op = body.call(thisArg, _);
125 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
126 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
127 }
128}
129
130/* eslint-disable max-len, sort-keys */
131var meowCLI = meow__default['default']("\n Usage: webfont [input] [options]\n\n Input: File(s) or glob(s).\n\n If an input argument is wrapped in quotation marks, it will be passed to \"fast-glob\"\n for cross-platform glob support.\n\n Options:\n\n --config\n\n Path to a specific configuration file (JSON, YAML, or CommonJS)\n or the name of a module in `node_modules` that points to one.\n If no `--config` argument is provided, webfont will search for\n configuration files in the following places, in this order:\n - a `webfont` property in `package.json`\n - a `.webfontrc` file (with or without filename extension:\n `.json`, `.yaml`, and `.js` are available)\n - a `webfont.config.js` file exporting a JS object\n The search will begin in the working directory and move up the\n directory tree until a configuration file is found.\n\n -f, --fontName\n\n The font family name you want, default: \"webfont\".\n\n -h, --help\n\n Output usage information.\n\n -v, --version\n\n Output the version number.\n\n -r, --formats\n\n Only this formats generate.\n\n -d, --dest\n\n Destination for generated fonts.\n\n -m, --dest-create\n\n Create destination directory if it does not exist.\n\n -t, --template\n\n Type of template ('css', 'scss', 'styl') or path to custom template.\n\n -s, --destTemplate\n\n Destination for generated template. If not passed used `dest` argument value.\n\n -c, --templateClassName\n\n Class name in css template.\n\n -p, --templateFontPath\n\n Font path in css template.\n\n -n, --templateFontName\n\n Font name in css template.\n\n --templateCacheString\n\n Specify cache string in scss/css template.\n\n --no-sort\n\n Keeps the files in the same order of entry\n\n --verbose\n\n Tell me everything!.\n\n For \"svgicons2svgfont\":\n\n --fontId\n\n The font id you want, default as \"--fontName\".\n\n --fontStyle\n\n The font style you want.\n\n --fontWeight\n\n The font weight you want.\n\n --fixedWidth\n\n Creates a monospace font of the width of the largest input icon.\n\n --centerHorizontally\n\n Calculate the bounds of a glyph and center it horizontally.\n\n --normalize\n\n Normalize icons by scaling them to the height of the highest icon.\n\n --fontHeight\n\n The outputted font height [MAX(icons.height)].\n\n --round\n\n Setup the SVG path rounding [10e12].\n\n --descent\n\n The font descent [0].\n\n --ascent\n\n The font ascent [height - descent].\n\n --startUnicode\n\n The start unicode codepoint for files without prefix [0xEA01].\n\n --prependUnicode\n\n Prefix files with their automatically allocated unicode codepoint.\n\n --metadata\n\n Content of the metadata tag.\n\n --addHashInFontUrl\n\n Generated font url will be : [webfont].[ext]?v=[hash]\n", {
132 autoHelp: false,
133 autoVersion: false,
134 flags: {
135 ascent: {
136 type: "string"
137 },
138 centerHorizontally: {
139 type: "boolean"
140 },
141 config: {
142 "default": null
143 },
144 descent: {
145 type: "string"
146 },
147 dest: {
148 alias: "d",
149 "default": process.cwd(),
150 type: "string"
151 },
152 destCreate: {
153 alias: "m",
154 "default": false,
155 type: "boolean"
156 },
157 destTemplate: {
158 alias: "s",
159 type: "string"
160 },
161 fixedWidth: {
162 type: "boolean"
163 },
164 fontHeight: {
165 type: "string"
166 },
167 fontId: {
168 type: "string"
169 },
170 fontName: {
171 alias: "u",
172 type: "string"
173 },
174 fontStyle: {
175 type: "string"
176 },
177 fontWeight: {
178 type: "string"
179 },
180 formats: {
181 alias: "f"
182 },
183 help: {
184 alias: "h",
185 type: "boolean"
186 },
187 normalize: {
188 type: "boolean"
189 },
190 prependUnicode: {
191 type: "boolean"
192 },
193 round: {
194 type: "string"
195 },
196 sort: {
197 "default": true,
198 type: "boolean"
199 },
200 startUnicode: {
201 type: "string"
202 },
203 template: {
204 alias: "t",
205 type: "string"
206 },
207 templateClassName: {
208 alias: "c",
209 type: "string"
210 },
211 templateFontName: {
212 alias: "n",
213 type: "string"
214 },
215 addHashInFontUrl: {
216 "default": false,
217 type: "boolean"
218 },
219 templateFontPath: {
220 alias: "p",
221 type: "string"
222 },
223 templateCacheString: {
224 "default": "",
225 type: "string"
226 },
227 verbose: {
228 "default": false,
229 type: "boolean"
230 },
231 version: {
232 alias: "v",
233 type: "boolean"
234 }
235 }
236});
237
238var getTemplateDirectory = function () { return path__default['default'].resolve(__dirname, "../templates"); };
239var getTemplateFilePath = function (template) {
240 var templateDirectory = getTemplateDirectory();
241 return templateDirectory + "/template." + template + ".njk";
242};
243var getBuiltInTemplates = function () {
244 var templateDirectory = getTemplateDirectory();
245 return {
246 css: { path: path__default['default'].join(templateDirectory, "template.css.njk") },
247 html: { path: path__default['default'].join(templateDirectory, "template.html.njk") },
248 json: { path: path__default['default'].join(templateDirectory, "template.json.njk") },
249 scss: { path: path__default['default'].join(templateDirectory, "template.scss.njk") },
250 styl: { path: path__default['default'].join(templateDirectory, "template.styl.njk") }
251 };
252};
253
254function commonjsRequire (path) {
255 throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
256}
257
258var jsYaml$1 = {};
259
260var loader$1 = {};
261
262var common$6 = {};
263
264function isNothing(subject) {
265 return (typeof subject === 'undefined') || (subject === null);
266}
267
268
269function isObject(subject) {
270 return (typeof subject === 'object') && (subject !== null);
271}
272
273
274function toArray(sequence) {
275 if (Array.isArray(sequence)) return sequence;
276 else if (isNothing(sequence)) return [];
277
278 return [ sequence ];
279}
280
281
282function extend(target, source) {
283 var index, length, key, sourceKeys;
284
285 if (source) {
286 sourceKeys = Object.keys(source);
287
288 for (index = 0, length = sourceKeys.length; index < length; index += 1) {
289 key = sourceKeys[index];
290 target[key] = source[key];
291 }
292 }
293
294 return target;
295}
296
297
298function repeat(string, count) {
299 var result = '', cycle;
300
301 for (cycle = 0; cycle < count; cycle += 1) {
302 result += string;
303 }
304
305 return result;
306}
307
308
309function isNegativeZero(number) {
310 return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
311}
312
313
314common$6.isNothing = isNothing;
315common$6.isObject = isObject;
316common$6.toArray = toArray;
317common$6.repeat = repeat;
318common$6.isNegativeZero = isNegativeZero;
319common$6.extend = extend;
320
321function YAMLException$4(reason, mark) {
322 // Super constructor
323 Error.call(this);
324
325 this.name = 'YAMLException';
326 this.reason = reason;
327 this.mark = mark;
328 this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');
329
330 // Include stack trace in error object
331 if (Error.captureStackTrace) {
332 // Chrome and NodeJS
333 Error.captureStackTrace(this, this.constructor);
334 } else {
335 // FF, IE 10+ and Safari 6+. Fallback for others
336 this.stack = (new Error()).stack || '';
337 }
338}
339
340
341// Inherit from Error
342YAMLException$4.prototype = Object.create(Error.prototype);
343YAMLException$4.prototype.constructor = YAMLException$4;
344
345
346YAMLException$4.prototype.toString = function toString(compact) {
347 var result = this.name + ': ';
348
349 result += this.reason || '(unknown reason)';
350
351 if (!compact && this.mark) {
352 result += ' ' + this.mark.toString();
353 }
354
355 return result;
356};
357
358
359var exception = YAMLException$4;
360
361var common$5 = common$6;
362
363
364function Mark$1(name, buffer, position, line, column) {
365 this.name = name;
366 this.buffer = buffer;
367 this.position = position;
368 this.line = line;
369 this.column = column;
370}
371
372
373Mark$1.prototype.getSnippet = function getSnippet(indent, maxLength) {
374 var head, start, tail, end, snippet;
375
376 if (!this.buffer) return null;
377
378 indent = indent || 4;
379 maxLength = maxLength || 75;
380
381 head = '';
382 start = this.position;
383
384 while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
385 start -= 1;
386 if (this.position - start > (maxLength / 2 - 1)) {
387 head = ' ... ';
388 start += 5;
389 break;
390 }
391 }
392
393 tail = '';
394 end = this.position;
395
396 while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
397 end += 1;
398 if (end - this.position > (maxLength / 2 - 1)) {
399 tail = ' ... ';
400 end -= 5;
401 break;
402 }
403 }
404
405 snippet = this.buffer.slice(start, end);
406
407 return common$5.repeat(' ', indent) + head + snippet + tail + '\n' +
408 common$5.repeat(' ', indent + this.position - start + head.length) + '^';
409};
410
411
412Mark$1.prototype.toString = function toString(compact) {
413 var snippet, where = '';
414
415 if (this.name) {
416 where += 'in "' + this.name + '" ';
417 }
418
419 where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
420
421 if (!compact) {
422 snippet = this.getSnippet();
423
424 if (snippet) {
425 where += ':\n' + snippet;
426 }
427 }
428
429 return where;
430};
431
432
433var mark = Mark$1;
434
435var YAMLException$3 = exception;
436
437var TYPE_CONSTRUCTOR_OPTIONS = [
438 'kind',
439 'resolve',
440 'construct',
441 'instanceOf',
442 'predicate',
443 'represent',
444 'defaultStyle',
445 'styleAliases'
446];
447
448var YAML_NODE_KINDS = [
449 'scalar',
450 'sequence',
451 'mapping'
452];
453
454function compileStyleAliases(map) {
455 var result = {};
456
457 if (map !== null) {
458 Object.keys(map).forEach(function (style) {
459 map[style].forEach(function (alias) {
460 result[String(alias)] = style;
461 });
462 });
463 }
464
465 return result;
466}
467
468function Type$h(tag, options) {
469 options = options || {};
470
471 Object.keys(options).forEach(function (name) {
472 if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
473 throw new YAMLException$3('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
474 }
475 });
476
477 // TODO: Add tag format check.
478 this.tag = tag;
479 this.kind = options['kind'] || null;
480 this.resolve = options['resolve'] || function () { return true; };
481 this.construct = options['construct'] || function (data) { return data; };
482 this.instanceOf = options['instanceOf'] || null;
483 this.predicate = options['predicate'] || null;
484 this.represent = options['represent'] || null;
485 this.defaultStyle = options['defaultStyle'] || null;
486 this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
487
488 if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
489 throw new YAMLException$3('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
490 }
491}
492
493var type = Type$h;
494
495/*eslint-disable max-len*/
496
497var common$4 = common$6;
498var YAMLException$2 = exception;
499var Type$g = type;
500
501
502function compileList(schema, name, result) {
503 var exclude = [];
504
505 schema.include.forEach(function (includedSchema) {
506 result = compileList(includedSchema, name, result);
507 });
508
509 schema[name].forEach(function (currentType) {
510 result.forEach(function (previousType, previousIndex) {
511 if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
512 exclude.push(previousIndex);
513 }
514 });
515
516 result.push(currentType);
517 });
518
519 return result.filter(function (type, index) {
520 return exclude.indexOf(index) === -1;
521 });
522}
523
524
525function compileMap(/* lists... */) {
526 var result = {
527 scalar: {},
528 sequence: {},
529 mapping: {},
530 fallback: {}
531 }, index, length;
532
533 function collectType(type) {
534 result[type.kind][type.tag] = result['fallback'][type.tag] = type;
535 }
536
537 for (index = 0, length = arguments.length; index < length; index += 1) {
538 arguments[index].forEach(collectType);
539 }
540 return result;
541}
542
543
544function Schema$5(definition) {
545 this.include = definition.include || [];
546 this.implicit = definition.implicit || [];
547 this.explicit = definition.explicit || [];
548
549 this.implicit.forEach(function (type) {
550 if (type.loadKind && type.loadKind !== 'scalar') {
551 throw new YAMLException$2('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
552 }
553 });
554
555 this.compiledImplicit = compileList(this, 'implicit', []);
556 this.compiledExplicit = compileList(this, 'explicit', []);
557 this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
558}
559
560
561Schema$5.DEFAULT = null;
562
563
564Schema$5.create = function createSchema() {
565 var schemas, types;
566
567 switch (arguments.length) {
568 case 1:
569 schemas = Schema$5.DEFAULT;
570 types = arguments[0];
571 break;
572
573 case 2:
574 schemas = arguments[0];
575 types = arguments[1];
576 break;
577
578 default:
579 throw new YAMLException$2('Wrong number of arguments for Schema.create function');
580 }
581
582 schemas = common$4.toArray(schemas);
583 types = common$4.toArray(types);
584
585 if (!schemas.every(function (schema) { return schema instanceof Schema$5; })) {
586 throw new YAMLException$2('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
587 }
588
589 if (!types.every(function (type) { return type instanceof Type$g; })) {
590 throw new YAMLException$2('Specified list of YAML types (or a single Type object) contains a non-Type object.');
591 }
592
593 return new Schema$5({
594 include: schemas,
595 explicit: types
596 });
597};
598
599
600var schema = Schema$5;
601
602var Type$f = type;
603
604var str = new Type$f('tag:yaml.org,2002:str', {
605 kind: 'scalar',
606 construct: function (data) { return data !== null ? data : ''; }
607});
608
609var Type$e = type;
610
611var seq = new Type$e('tag:yaml.org,2002:seq', {
612 kind: 'sequence',
613 construct: function (data) { return data !== null ? data : []; }
614});
615
616var Type$d = type;
617
618var map = new Type$d('tag:yaml.org,2002:map', {
619 kind: 'mapping',
620 construct: function (data) { return data !== null ? data : {}; }
621});
622
623var Schema$4 = schema;
624
625
626var failsafe = new Schema$4({
627 explicit: [
628 str,
629 seq,
630 map
631 ]
632});
633
634var Type$c = type;
635
636function resolveYamlNull(data) {
637 if (data === null) return true;
638
639 var max = data.length;
640
641 return (max === 1 && data === '~') ||
642 (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
643}
644
645function constructYamlNull() {
646 return null;
647}
648
649function isNull(object) {
650 return object === null;
651}
652
653var _null = new Type$c('tag:yaml.org,2002:null', {
654 kind: 'scalar',
655 resolve: resolveYamlNull,
656 construct: constructYamlNull,
657 predicate: isNull,
658 represent: {
659 canonical: function () { return '~'; },
660 lowercase: function () { return 'null'; },
661 uppercase: function () { return 'NULL'; },
662 camelcase: function () { return 'Null'; }
663 },
664 defaultStyle: 'lowercase'
665});
666
667var Type$b = type;
668
669function resolveYamlBoolean(data) {
670 if (data === null) return false;
671
672 var max = data.length;
673
674 return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
675 (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
676}
677
678function constructYamlBoolean(data) {
679 return data === 'true' ||
680 data === 'True' ||
681 data === 'TRUE';
682}
683
684function isBoolean(object) {
685 return Object.prototype.toString.call(object) === '[object Boolean]';
686}
687
688var bool = new Type$b('tag:yaml.org,2002:bool', {
689 kind: 'scalar',
690 resolve: resolveYamlBoolean,
691 construct: constructYamlBoolean,
692 predicate: isBoolean,
693 represent: {
694 lowercase: function (object) { return object ? 'true' : 'false'; },
695 uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
696 camelcase: function (object) { return object ? 'True' : 'False'; }
697 },
698 defaultStyle: 'lowercase'
699});
700
701var common$3 = common$6;
702var Type$a = type;
703
704function isHexCode(c) {
705 return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
706 ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
707 ((0x61/* a */ <= c) && (c <= 0x66/* f */));
708}
709
710function isOctCode(c) {
711 return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
712}
713
714function isDecCode(c) {
715 return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
716}
717
718function resolveYamlInteger(data) {
719 if (data === null) return false;
720
721 var max = data.length,
722 index = 0,
723 hasDigits = false,
724 ch;
725
726 if (!max) return false;
727
728 ch = data[index];
729
730 // sign
731 if (ch === '-' || ch === '+') {
732 ch = data[++index];
733 }
734
735 if (ch === '0') {
736 // 0
737 if (index + 1 === max) return true;
738 ch = data[++index];
739
740 // base 2, base 8, base 16
741
742 if (ch === 'b') {
743 // base 2
744 index++;
745
746 for (; index < max; index++) {
747 ch = data[index];
748 if (ch === '_') continue;
749 if (ch !== '0' && ch !== '1') return false;
750 hasDigits = true;
751 }
752 return hasDigits && ch !== '_';
753 }
754
755
756 if (ch === 'x') {
757 // base 16
758 index++;
759
760 for (; index < max; index++) {
761 ch = data[index];
762 if (ch === '_') continue;
763 if (!isHexCode(data.charCodeAt(index))) return false;
764 hasDigits = true;
765 }
766 return hasDigits && ch !== '_';
767 }
768
769 // base 8
770 for (; index < max; index++) {
771 ch = data[index];
772 if (ch === '_') continue;
773 if (!isOctCode(data.charCodeAt(index))) return false;
774 hasDigits = true;
775 }
776 return hasDigits && ch !== '_';
777 }
778
779 // base 10 (except 0) or base 60
780
781 // value should not start with `_`;
782 if (ch === '_') return false;
783
784 for (; index < max; index++) {
785 ch = data[index];
786 if (ch === '_') continue;
787 if (ch === ':') break;
788 if (!isDecCode(data.charCodeAt(index))) {
789 return false;
790 }
791 hasDigits = true;
792 }
793
794 // Should have digits and should not end with `_`
795 if (!hasDigits || ch === '_') return false;
796
797 // if !base60 - done;
798 if (ch !== ':') return true;
799
800 // base60 almost not used, no needs to optimize
801 return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
802}
803
804function constructYamlInteger(data) {
805 var value = data, sign = 1, ch, base, digits = [];
806
807 if (value.indexOf('_') !== -1) {
808 value = value.replace(/_/g, '');
809 }
810
811 ch = value[0];
812
813 if (ch === '-' || ch === '+') {
814 if (ch === '-') sign = -1;
815 value = value.slice(1);
816 ch = value[0];
817 }
818
819 if (value === '0') return 0;
820
821 if (ch === '0') {
822 if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
823 if (value[1] === 'x') return sign * parseInt(value, 16);
824 return sign * parseInt(value, 8);
825 }
826
827 if (value.indexOf(':') !== -1) {
828 value.split(':').forEach(function (v) {
829 digits.unshift(parseInt(v, 10));
830 });
831
832 value = 0;
833 base = 1;
834
835 digits.forEach(function (d) {
836 value += (d * base);
837 base *= 60;
838 });
839
840 return sign * value;
841
842 }
843
844 return sign * parseInt(value, 10);
845}
846
847function isInteger(object) {
848 return (Object.prototype.toString.call(object)) === '[object Number]' &&
849 (object % 1 === 0 && !common$3.isNegativeZero(object));
850}
851
852var int = new Type$a('tag:yaml.org,2002:int', {
853 kind: 'scalar',
854 resolve: resolveYamlInteger,
855 construct: constructYamlInteger,
856 predicate: isInteger,
857 represent: {
858 binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
859 octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); },
860 decimal: function (obj) { return obj.toString(10); },
861 /* eslint-disable max-len */
862 hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
863 },
864 defaultStyle: 'decimal',
865 styleAliases: {
866 binary: [ 2, 'bin' ],
867 octal: [ 8, 'oct' ],
868 decimal: [ 10, 'dec' ],
869 hexadecimal: [ 16, 'hex' ]
870 }
871});
872
873var common$2 = common$6;
874var Type$9 = type;
875
876var YAML_FLOAT_PATTERN = new RegExp(
877 // 2.5e4, 2.5 and integers
878 '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
879 // .2e4, .2
880 // special case, seems not from spec
881 '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
882 // 20:59
883 '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
884 // .inf
885 '|[-+]?\\.(?:inf|Inf|INF)' +
886 // .nan
887 '|\\.(?:nan|NaN|NAN))$');
888
889function resolveYamlFloat(data) {
890 if (data === null) return false;
891
892 if (!YAML_FLOAT_PATTERN.test(data) ||
893 // Quick hack to not allow integers end with `_`
894 // Probably should update regexp & check speed
895 data[data.length - 1] === '_') {
896 return false;
897 }
898
899 return true;
900}
901
902function constructYamlFloat(data) {
903 var value, sign, base, digits;
904
905 value = data.replace(/_/g, '').toLowerCase();
906 sign = value[0] === '-' ? -1 : 1;
907 digits = [];
908
909 if ('+-'.indexOf(value[0]) >= 0) {
910 value = value.slice(1);
911 }
912
913 if (value === '.inf') {
914 return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
915
916 } else if (value === '.nan') {
917 return NaN;
918
919 } else if (value.indexOf(':') >= 0) {
920 value.split(':').forEach(function (v) {
921 digits.unshift(parseFloat(v, 10));
922 });
923
924 value = 0.0;
925 base = 1;
926
927 digits.forEach(function (d) {
928 value += d * base;
929 base *= 60;
930 });
931
932 return sign * value;
933
934 }
935 return sign * parseFloat(value, 10);
936}
937
938
939var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
940
941function representYamlFloat(object, style) {
942 var res;
943
944 if (isNaN(object)) {
945 switch (style) {
946 case 'lowercase': return '.nan';
947 case 'uppercase': return '.NAN';
948 case 'camelcase': return '.NaN';
949 }
950 } else if (Number.POSITIVE_INFINITY === object) {
951 switch (style) {
952 case 'lowercase': return '.inf';
953 case 'uppercase': return '.INF';
954 case 'camelcase': return '.Inf';
955 }
956 } else if (Number.NEGATIVE_INFINITY === object) {
957 switch (style) {
958 case 'lowercase': return '-.inf';
959 case 'uppercase': return '-.INF';
960 case 'camelcase': return '-.Inf';
961 }
962 } else if (common$2.isNegativeZero(object)) {
963 return '-0.0';
964 }
965
966 res = object.toString(10);
967
968 // JS stringifier can build scientific format without dots: 5e-100,
969 // while YAML requres dot: 5.e-100. Fix it with simple hack
970
971 return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
972}
973
974function isFloat(object) {
975 return (Object.prototype.toString.call(object) === '[object Number]') &&
976 (object % 1 !== 0 || common$2.isNegativeZero(object));
977}
978
979var float = new Type$9('tag:yaml.org,2002:float', {
980 kind: 'scalar',
981 resolve: resolveYamlFloat,
982 construct: constructYamlFloat,
983 predicate: isFloat,
984 represent: representYamlFloat,
985 defaultStyle: 'lowercase'
986});
987
988var Schema$3 = schema;
989
990
991var json = new Schema$3({
992 include: [
993 failsafe
994 ],
995 implicit: [
996 _null,
997 bool,
998 int,
999 float
1000 ]
1001});
1002
1003var Schema$2 = schema;
1004
1005
1006var core = new Schema$2({
1007 include: [
1008 json
1009 ]
1010});
1011
1012var Type$8 = type;
1013
1014var YAML_DATE_REGEXP = new RegExp(
1015 '^([0-9][0-9][0-9][0-9])' + // [1] year
1016 '-([0-9][0-9])' + // [2] month
1017 '-([0-9][0-9])$'); // [3] day
1018
1019var YAML_TIMESTAMP_REGEXP = new RegExp(
1020 '^([0-9][0-9][0-9][0-9])' + // [1] year
1021 '-([0-9][0-9]?)' + // [2] month
1022 '-([0-9][0-9]?)' + // [3] day
1023 '(?:[Tt]|[ \\t]+)' + // ...
1024 '([0-9][0-9]?)' + // [4] hour
1025 ':([0-9][0-9])' + // [5] minute
1026 ':([0-9][0-9])' + // [6] second
1027 '(?:\\.([0-9]*))?' + // [7] fraction
1028 '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
1029 '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
1030
1031function resolveYamlTimestamp(data) {
1032 if (data === null) return false;
1033 if (YAML_DATE_REGEXP.exec(data) !== null) return true;
1034 if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
1035 return false;
1036}
1037
1038function constructYamlTimestamp(data) {
1039 var match, year, month, day, hour, minute, second, fraction = 0,
1040 delta = null, tz_hour, tz_minute, date;
1041
1042 match = YAML_DATE_REGEXP.exec(data);
1043 if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
1044
1045 if (match === null) throw new Error('Date resolve error');
1046
1047 // match: [1] year [2] month [3] day
1048
1049 year = +(match[1]);
1050 month = +(match[2]) - 1; // JS month starts with 0
1051 day = +(match[3]);
1052
1053 if (!match[4]) { // no hour
1054 return new Date(Date.UTC(year, month, day));
1055 }
1056
1057 // match: [4] hour [5] minute [6] second [7] fraction
1058
1059 hour = +(match[4]);
1060 minute = +(match[5]);
1061 second = +(match[6]);
1062
1063 if (match[7]) {
1064 fraction = match[7].slice(0, 3);
1065 while (fraction.length < 3) { // milli-seconds
1066 fraction += '0';
1067 }
1068 fraction = +fraction;
1069 }
1070
1071 // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
1072
1073 if (match[9]) {
1074 tz_hour = +(match[10]);
1075 tz_minute = +(match[11] || 0);
1076 delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
1077 if (match[9] === '-') delta = -delta;
1078 }
1079
1080 date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
1081
1082 if (delta) date.setTime(date.getTime() - delta);
1083
1084 return date;
1085}
1086
1087function representYamlTimestamp(object /*, style*/) {
1088 return object.toISOString();
1089}
1090
1091var timestamp = new Type$8('tag:yaml.org,2002:timestamp', {
1092 kind: 'scalar',
1093 resolve: resolveYamlTimestamp,
1094 construct: constructYamlTimestamp,
1095 instanceOf: Date,
1096 represent: representYamlTimestamp
1097});
1098
1099var Type$7 = type;
1100
1101function resolveYamlMerge(data) {
1102 return data === '<<' || data === null;
1103}
1104
1105var merge = new Type$7('tag:yaml.org,2002:merge', {
1106 kind: 'scalar',
1107 resolve: resolveYamlMerge
1108});
1109
1110/*eslint-disable no-bitwise*/
1111
1112var NodeBuffer;
1113
1114try {
1115 // A trick for browserified version, to not include `Buffer` shim
1116 var _require$1 = commonjsRequire;
1117 NodeBuffer = _require$1('buffer').Buffer;
1118} catch (__) {}
1119
1120var Type$6 = type;
1121
1122
1123// [ 64, 65, 66 ] -> [ padding, CR, LF ]
1124var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
1125
1126
1127function resolveYamlBinary(data) {
1128 if (data === null) return false;
1129
1130 var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
1131
1132 // Convert one by one.
1133 for (idx = 0; idx < max; idx++) {
1134 code = map.indexOf(data.charAt(idx));
1135
1136 // Skip CR/LF
1137 if (code > 64) continue;
1138
1139 // Fail on illegal characters
1140 if (code < 0) return false;
1141
1142 bitlen += 6;
1143 }
1144
1145 // If there are any bits left, source was corrupted
1146 return (bitlen % 8) === 0;
1147}
1148
1149function constructYamlBinary(data) {
1150 var idx, tailbits,
1151 input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
1152 max = input.length,
1153 map = BASE64_MAP,
1154 bits = 0,
1155 result = [];
1156
1157 // Collect by 6*4 bits (3 bytes)
1158
1159 for (idx = 0; idx < max; idx++) {
1160 if ((idx % 4 === 0) && idx) {
1161 result.push((bits >> 16) & 0xFF);
1162 result.push((bits >> 8) & 0xFF);
1163 result.push(bits & 0xFF);
1164 }
1165
1166 bits = (bits << 6) | map.indexOf(input.charAt(idx));
1167 }
1168
1169 // Dump tail
1170
1171 tailbits = (max % 4) * 6;
1172
1173 if (tailbits === 0) {
1174 result.push((bits >> 16) & 0xFF);
1175 result.push((bits >> 8) & 0xFF);
1176 result.push(bits & 0xFF);
1177 } else if (tailbits === 18) {
1178 result.push((bits >> 10) & 0xFF);
1179 result.push((bits >> 2) & 0xFF);
1180 } else if (tailbits === 12) {
1181 result.push((bits >> 4) & 0xFF);
1182 }
1183
1184 // Wrap into Buffer for NodeJS and leave Array for browser
1185 if (NodeBuffer) {
1186 // Support node 6.+ Buffer API when available
1187 return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
1188 }
1189
1190 return result;
1191}
1192
1193function representYamlBinary(object /*, style*/) {
1194 var result = '', bits = 0, idx, tail,
1195 max = object.length,
1196 map = BASE64_MAP;
1197
1198 // Convert every three bytes to 4 ASCII characters.
1199
1200 for (idx = 0; idx < max; idx++) {
1201 if ((idx % 3 === 0) && idx) {
1202 result += map[(bits >> 18) & 0x3F];
1203 result += map[(bits >> 12) & 0x3F];
1204 result += map[(bits >> 6) & 0x3F];
1205 result += map[bits & 0x3F];
1206 }
1207
1208 bits = (bits << 8) + object[idx];
1209 }
1210
1211 // Dump tail
1212
1213 tail = max % 3;
1214
1215 if (tail === 0) {
1216 result += map[(bits >> 18) & 0x3F];
1217 result += map[(bits >> 12) & 0x3F];
1218 result += map[(bits >> 6) & 0x3F];
1219 result += map[bits & 0x3F];
1220 } else if (tail === 2) {
1221 result += map[(bits >> 10) & 0x3F];
1222 result += map[(bits >> 4) & 0x3F];
1223 result += map[(bits << 2) & 0x3F];
1224 result += map[64];
1225 } else if (tail === 1) {
1226 result += map[(bits >> 2) & 0x3F];
1227 result += map[(bits << 4) & 0x3F];
1228 result += map[64];
1229 result += map[64];
1230 }
1231
1232 return result;
1233}
1234
1235function isBinary$1(object) {
1236 return NodeBuffer && NodeBuffer.isBuffer(object);
1237}
1238
1239var binary = new Type$6('tag:yaml.org,2002:binary', {
1240 kind: 'scalar',
1241 resolve: resolveYamlBinary,
1242 construct: constructYamlBinary,
1243 predicate: isBinary$1,
1244 represent: representYamlBinary
1245});
1246
1247var Type$5 = type;
1248
1249var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
1250var _toString$2 = Object.prototype.toString;
1251
1252function resolveYamlOmap(data) {
1253 if (data === null) return true;
1254
1255 var objectKeys = [], index, length, pair, pairKey, pairHasKey,
1256 object = data;
1257
1258 for (index = 0, length = object.length; index < length; index += 1) {
1259 pair = object[index];
1260 pairHasKey = false;
1261
1262 if (_toString$2.call(pair) !== '[object Object]') return false;
1263
1264 for (pairKey in pair) {
1265 if (_hasOwnProperty$3.call(pair, pairKey)) {
1266 if (!pairHasKey) pairHasKey = true;
1267 else return false;
1268 }
1269 }
1270
1271 if (!pairHasKey) return false;
1272
1273 if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
1274 else return false;
1275 }
1276
1277 return true;
1278}
1279
1280function constructYamlOmap(data) {
1281 return data !== null ? data : [];
1282}
1283
1284var omap = new Type$5('tag:yaml.org,2002:omap', {
1285 kind: 'sequence',
1286 resolve: resolveYamlOmap,
1287 construct: constructYamlOmap
1288});
1289
1290var Type$4 = type;
1291
1292var _toString$1 = Object.prototype.toString;
1293
1294function resolveYamlPairs(data) {
1295 if (data === null) return true;
1296
1297 var index, length, pair, keys, result,
1298 object = data;
1299
1300 result = new Array(object.length);
1301
1302 for (index = 0, length = object.length; index < length; index += 1) {
1303 pair = object[index];
1304
1305 if (_toString$1.call(pair) !== '[object Object]') return false;
1306
1307 keys = Object.keys(pair);
1308
1309 if (keys.length !== 1) return false;
1310
1311 result[index] = [ keys[0], pair[keys[0]] ];
1312 }
1313
1314 return true;
1315}
1316
1317function constructYamlPairs(data) {
1318 if (data === null) return [];
1319
1320 var index, length, pair, keys, result,
1321 object = data;
1322
1323 result = new Array(object.length);
1324
1325 for (index = 0, length = object.length; index < length; index += 1) {
1326 pair = object[index];
1327
1328 keys = Object.keys(pair);
1329
1330 result[index] = [ keys[0], pair[keys[0]] ];
1331 }
1332
1333 return result;
1334}
1335
1336var pairs = new Type$4('tag:yaml.org,2002:pairs', {
1337 kind: 'sequence',
1338 resolve: resolveYamlPairs,
1339 construct: constructYamlPairs
1340});
1341
1342var Type$3 = type;
1343
1344var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
1345
1346function resolveYamlSet(data) {
1347 if (data === null) return true;
1348
1349 var key, object = data;
1350
1351 for (key in object) {
1352 if (_hasOwnProperty$2.call(object, key)) {
1353 if (object[key] !== null) return false;
1354 }
1355 }
1356
1357 return true;
1358}
1359
1360function constructYamlSet(data) {
1361 return data !== null ? data : {};
1362}
1363
1364var set = new Type$3('tag:yaml.org,2002:set', {
1365 kind: 'mapping',
1366 resolve: resolveYamlSet,
1367 construct: constructYamlSet
1368});
1369
1370var Schema$1 = schema;
1371
1372
1373var default_safe = new Schema$1({
1374 include: [
1375 core
1376 ],
1377 implicit: [
1378 timestamp,
1379 merge
1380 ],
1381 explicit: [
1382 binary,
1383 omap,
1384 pairs,
1385 set
1386 ]
1387});
1388
1389var Type$2 = type;
1390
1391function resolveJavascriptUndefined() {
1392 return true;
1393}
1394
1395function constructJavascriptUndefined() {
1396 /*eslint-disable no-undefined*/
1397 return undefined;
1398}
1399
1400function representJavascriptUndefined() {
1401 return '';
1402}
1403
1404function isUndefined(object) {
1405 return typeof object === 'undefined';
1406}
1407
1408var _undefined = new Type$2('tag:yaml.org,2002:js/undefined', {
1409 kind: 'scalar',
1410 resolve: resolveJavascriptUndefined,
1411 construct: constructJavascriptUndefined,
1412 predicate: isUndefined,
1413 represent: representJavascriptUndefined
1414});
1415
1416var Type$1 = type;
1417
1418function resolveJavascriptRegExp(data) {
1419 if (data === null) return false;
1420 if (data.length === 0) return false;
1421
1422 var regexp = data,
1423 tail = /\/([gim]*)$/.exec(data),
1424 modifiers = '';
1425
1426 // if regexp starts with '/' it can have modifiers and must be properly closed
1427 // `/foo/gim` - modifiers tail can be maximum 3 chars
1428 if (regexp[0] === '/') {
1429 if (tail) modifiers = tail[1];
1430
1431 if (modifiers.length > 3) return false;
1432 // if expression starts with /, is should be properly terminated
1433 if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
1434 }
1435
1436 return true;
1437}
1438
1439function constructJavascriptRegExp(data) {
1440 var regexp = data,
1441 tail = /\/([gim]*)$/.exec(data),
1442 modifiers = '';
1443
1444 // `/foo/gim` - tail can be maximum 4 chars
1445 if (regexp[0] === '/') {
1446 if (tail) modifiers = tail[1];
1447 regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
1448 }
1449
1450 return new RegExp(regexp, modifiers);
1451}
1452
1453function representJavascriptRegExp(object /*, style*/) {
1454 var result = '/' + object.source + '/';
1455
1456 if (object.global) result += 'g';
1457 if (object.multiline) result += 'm';
1458 if (object.ignoreCase) result += 'i';
1459
1460 return result;
1461}
1462
1463function isRegExp(object) {
1464 return Object.prototype.toString.call(object) === '[object RegExp]';
1465}
1466
1467var regexp = new Type$1('tag:yaml.org,2002:js/regexp', {
1468 kind: 'scalar',
1469 resolve: resolveJavascriptRegExp,
1470 construct: constructJavascriptRegExp,
1471 predicate: isRegExp,
1472 represent: representJavascriptRegExp
1473});
1474
1475var esprima;
1476
1477// Browserified version does not have esprima
1478//
1479// 1. For node.js just require module as deps
1480// 2. For browser try to require mudule via external AMD system.
1481// If not found - try to fallback to window.esprima. If not
1482// found too - then fail to parse.
1483//
1484try {
1485 // workaround to exclude package from browserify list.
1486 var _require = commonjsRequire;
1487 esprima = _require('esprima');
1488} catch (_) {
1489 /* eslint-disable no-redeclare */
1490 /* global window */
1491 if (typeof window !== 'undefined') esprima = window.esprima;
1492}
1493
1494var Type = type;
1495
1496function resolveJavascriptFunction(data) {
1497 if (data === null) return false;
1498
1499 try {
1500 var source = '(' + data + ')',
1501 ast = esprima.parse(source, { range: true });
1502
1503 if (ast.type !== 'Program' ||
1504 ast.body.length !== 1 ||
1505 ast.body[0].type !== 'ExpressionStatement' ||
1506 (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
1507 ast.body[0].expression.type !== 'FunctionExpression')) {
1508 return false;
1509 }
1510
1511 return true;
1512 } catch (err) {
1513 return false;
1514 }
1515}
1516
1517function constructJavascriptFunction(data) {
1518 /*jslint evil:true*/
1519
1520 var source = '(' + data + ')',
1521 ast = esprima.parse(source, { range: true }),
1522 params = [],
1523 body;
1524
1525 if (ast.type !== 'Program' ||
1526 ast.body.length !== 1 ||
1527 ast.body[0].type !== 'ExpressionStatement' ||
1528 (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
1529 ast.body[0].expression.type !== 'FunctionExpression')) {
1530 throw new Error('Failed to resolve function');
1531 }
1532
1533 ast.body[0].expression.params.forEach(function (param) {
1534 params.push(param.name);
1535 });
1536
1537 body = ast.body[0].expression.body.range;
1538
1539 // Esprima's ranges include the first '{' and the last '}' characters on
1540 // function expressions. So cut them out.
1541 if (ast.body[0].expression.body.type === 'BlockStatement') {
1542 /*eslint-disable no-new-func*/
1543 return new Function(params, source.slice(body[0] + 1, body[1] - 1));
1544 }
1545 // ES6 arrow functions can omit the BlockStatement. In that case, just return
1546 // the body.
1547 /*eslint-disable no-new-func*/
1548 return new Function(params, 'return ' + source.slice(body[0], body[1]));
1549}
1550
1551function representJavascriptFunction(object /*, style*/) {
1552 return object.toString();
1553}
1554
1555function isFunction$1(object) {
1556 return Object.prototype.toString.call(object) === '[object Function]';
1557}
1558
1559var _function = new Type('tag:yaml.org,2002:js/function', {
1560 kind: 'scalar',
1561 resolve: resolveJavascriptFunction,
1562 construct: constructJavascriptFunction,
1563 predicate: isFunction$1,
1564 represent: representJavascriptFunction
1565});
1566
1567var Schema = schema;
1568
1569
1570var default_full = Schema.DEFAULT = new Schema({
1571 include: [
1572 default_safe
1573 ],
1574 explicit: [
1575 _undefined,
1576 regexp,
1577 _function
1578 ]
1579});
1580
1581/*eslint-disable max-len,no-use-before-define*/
1582
1583var common$1 = common$6;
1584var YAMLException$1 = exception;
1585var Mark = mark;
1586var DEFAULT_SAFE_SCHEMA$1 = default_safe;
1587var DEFAULT_FULL_SCHEMA$1 = default_full;
1588
1589
1590var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
1591
1592
1593var CONTEXT_FLOW_IN = 1;
1594var CONTEXT_FLOW_OUT = 2;
1595var CONTEXT_BLOCK_IN = 3;
1596var CONTEXT_BLOCK_OUT = 4;
1597
1598
1599var CHOMPING_CLIP = 1;
1600var CHOMPING_STRIP = 2;
1601var CHOMPING_KEEP = 3;
1602
1603
1604var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
1605var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
1606var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
1607var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
1608var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
1609
1610
1611function _class(obj) { return Object.prototype.toString.call(obj); }
1612
1613function is_EOL(c) {
1614 return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
1615}
1616
1617function is_WHITE_SPACE(c) {
1618 return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
1619}
1620
1621function is_WS_OR_EOL(c) {
1622 return (c === 0x09/* Tab */) ||
1623 (c === 0x20/* Space */) ||
1624 (c === 0x0A/* LF */) ||
1625 (c === 0x0D/* CR */);
1626}
1627
1628function is_FLOW_INDICATOR(c) {
1629 return c === 0x2C/* , */ ||
1630 c === 0x5B/* [ */ ||
1631 c === 0x5D/* ] */ ||
1632 c === 0x7B/* { */ ||
1633 c === 0x7D/* } */;
1634}
1635
1636function fromHexCode(c) {
1637 var lc;
1638
1639 if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
1640 return c - 0x30;
1641 }
1642
1643 /*eslint-disable no-bitwise*/
1644 lc = c | 0x20;
1645
1646 if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
1647 return lc - 0x61 + 10;
1648 }
1649
1650 return -1;
1651}
1652
1653function escapedHexLen(c) {
1654 if (c === 0x78/* x */) { return 2; }
1655 if (c === 0x75/* u */) { return 4; }
1656 if (c === 0x55/* U */) { return 8; }
1657 return 0;
1658}
1659
1660function fromDecimalCode(c) {
1661 if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
1662 return c - 0x30;
1663 }
1664
1665 return -1;
1666}
1667
1668function simpleEscapeSequence(c) {
1669 /* eslint-disable indent */
1670 return (c === 0x30/* 0 */) ? '\x00' :
1671 (c === 0x61/* a */) ? '\x07' :
1672 (c === 0x62/* b */) ? '\x08' :
1673 (c === 0x74/* t */) ? '\x09' :
1674 (c === 0x09/* Tab */) ? '\x09' :
1675 (c === 0x6E/* n */) ? '\x0A' :
1676 (c === 0x76/* v */) ? '\x0B' :
1677 (c === 0x66/* f */) ? '\x0C' :
1678 (c === 0x72/* r */) ? '\x0D' :
1679 (c === 0x65/* e */) ? '\x1B' :
1680 (c === 0x20/* Space */) ? ' ' :
1681 (c === 0x22/* " */) ? '\x22' :
1682 (c === 0x2F/* / */) ? '/' :
1683 (c === 0x5C/* \ */) ? '\x5C' :
1684 (c === 0x4E/* N */) ? '\x85' :
1685 (c === 0x5F/* _ */) ? '\xA0' :
1686 (c === 0x4C/* L */) ? '\u2028' :
1687 (c === 0x50/* P */) ? '\u2029' : '';
1688}
1689
1690function charFromCodepoint(c) {
1691 if (c <= 0xFFFF) {
1692 return String.fromCharCode(c);
1693 }
1694 // Encode UTF-16 surrogate pair
1695 // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
1696 return String.fromCharCode(
1697 ((c - 0x010000) >> 10) + 0xD800,
1698 ((c - 0x010000) & 0x03FF) + 0xDC00
1699 );
1700}
1701
1702var simpleEscapeCheck = new Array(256); // integer, for fast access
1703var simpleEscapeMap = new Array(256);
1704for (var i = 0; i < 256; i++) {
1705 simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
1706 simpleEscapeMap[i] = simpleEscapeSequence(i);
1707}
1708
1709
1710function State$1(input, options) {
1711 this.input = input;
1712
1713 this.filename = options['filename'] || null;
1714 this.schema = options['schema'] || DEFAULT_FULL_SCHEMA$1;
1715 this.onWarning = options['onWarning'] || null;
1716 this.legacy = options['legacy'] || false;
1717 this.json = options['json'] || false;
1718 this.listener = options['listener'] || null;
1719
1720 this.implicitTypes = this.schema.compiledImplicit;
1721 this.typeMap = this.schema.compiledTypeMap;
1722
1723 this.length = input.length;
1724 this.position = 0;
1725 this.line = 0;
1726 this.lineStart = 0;
1727 this.lineIndent = 0;
1728
1729 this.documents = [];
1730
1731 /*
1732 this.version;
1733 this.checkLineBreaks;
1734 this.tagMap;
1735 this.anchorMap;
1736 this.tag;
1737 this.anchor;
1738 this.kind;
1739 this.result;*/
1740
1741}
1742
1743
1744function generateError(state, message) {
1745 return new YAMLException$1(
1746 message,
1747 new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));
1748}
1749
1750function throwError(state, message) {
1751 throw generateError(state, message);
1752}
1753
1754function throwWarning(state, message) {
1755 if (state.onWarning) {
1756 state.onWarning.call(null, generateError(state, message));
1757 }
1758}
1759
1760
1761var directiveHandlers = {
1762
1763 YAML: function handleYamlDirective(state, name, args) {
1764
1765 var match, major, minor;
1766
1767 if (state.version !== null) {
1768 throwError(state, 'duplication of %YAML directive');
1769 }
1770
1771 if (args.length !== 1) {
1772 throwError(state, 'YAML directive accepts exactly one argument');
1773 }
1774
1775 match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
1776
1777 if (match === null) {
1778 throwError(state, 'ill-formed argument of the YAML directive');
1779 }
1780
1781 major = parseInt(match[1], 10);
1782 minor = parseInt(match[2], 10);
1783
1784 if (major !== 1) {
1785 throwError(state, 'unacceptable YAML version of the document');
1786 }
1787
1788 state.version = args[0];
1789 state.checkLineBreaks = (minor < 2);
1790
1791 if (minor !== 1 && minor !== 2) {
1792 throwWarning(state, 'unsupported YAML version of the document');
1793 }
1794 },
1795
1796 TAG: function handleTagDirective(state, name, args) {
1797
1798 var handle, prefix;
1799
1800 if (args.length !== 2) {
1801 throwError(state, 'TAG directive accepts exactly two arguments');
1802 }
1803
1804 handle = args[0];
1805 prefix = args[1];
1806
1807 if (!PATTERN_TAG_HANDLE.test(handle)) {
1808 throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
1809 }
1810
1811 if (_hasOwnProperty$1.call(state.tagMap, handle)) {
1812 throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
1813 }
1814
1815 if (!PATTERN_TAG_URI.test(prefix)) {
1816 throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
1817 }
1818
1819 state.tagMap[handle] = prefix;
1820 }
1821};
1822
1823
1824function captureSegment(state, start, end, checkJson) {
1825 var _position, _length, _character, _result;
1826
1827 if (start < end) {
1828 _result = state.input.slice(start, end);
1829
1830 if (checkJson) {
1831 for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
1832 _character = _result.charCodeAt(_position);
1833 if (!(_character === 0x09 ||
1834 (0x20 <= _character && _character <= 0x10FFFF))) {
1835 throwError(state, 'expected valid JSON character');
1836 }
1837 }
1838 } else if (PATTERN_NON_PRINTABLE.test(_result)) {
1839 throwError(state, 'the stream contains non-printable characters');
1840 }
1841
1842 state.result += _result;
1843 }
1844}
1845
1846function mergeMappings(state, destination, source, overridableKeys) {
1847 var sourceKeys, key, index, quantity;
1848
1849 if (!common$1.isObject(source)) {
1850 throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
1851 }
1852
1853 sourceKeys = Object.keys(source);
1854
1855 for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
1856 key = sourceKeys[index];
1857
1858 if (!_hasOwnProperty$1.call(destination, key)) {
1859 destination[key] = source[key];
1860 overridableKeys[key] = true;
1861 }
1862 }
1863}
1864
1865function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
1866 var index, quantity;
1867
1868 // The output is a plain object here, so keys can only be strings.
1869 // We need to convert keyNode to a string, but doing so can hang the process
1870 // (deeply nested arrays that explode exponentially using aliases).
1871 if (Array.isArray(keyNode)) {
1872 keyNode = Array.prototype.slice.call(keyNode);
1873
1874 for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
1875 if (Array.isArray(keyNode[index])) {
1876 throwError(state, 'nested arrays are not supported inside keys');
1877 }
1878
1879 if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
1880 keyNode[index] = '[object Object]';
1881 }
1882 }
1883 }
1884
1885 // Avoid code execution in load() via toString property
1886 // (still use its own toString for arrays, timestamps,
1887 // and whatever user schema extensions happen to have @@toStringTag)
1888 if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
1889 keyNode = '[object Object]';
1890 }
1891
1892
1893 keyNode = String(keyNode);
1894
1895 if (_result === null) {
1896 _result = {};
1897 }
1898
1899 if (keyTag === 'tag:yaml.org,2002:merge') {
1900 if (Array.isArray(valueNode)) {
1901 for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
1902 mergeMappings(state, _result, valueNode[index], overridableKeys);
1903 }
1904 } else {
1905 mergeMappings(state, _result, valueNode, overridableKeys);
1906 }
1907 } else {
1908 if (!state.json &&
1909 !_hasOwnProperty$1.call(overridableKeys, keyNode) &&
1910 _hasOwnProperty$1.call(_result, keyNode)) {
1911 state.line = startLine || state.line;
1912 state.position = startPos || state.position;
1913 throwError(state, 'duplicated mapping key');
1914 }
1915 _result[keyNode] = valueNode;
1916 delete overridableKeys[keyNode];
1917 }
1918
1919 return _result;
1920}
1921
1922function readLineBreak(state) {
1923 var ch;
1924
1925 ch = state.input.charCodeAt(state.position);
1926
1927 if (ch === 0x0A/* LF */) {
1928 state.position++;
1929 } else if (ch === 0x0D/* CR */) {
1930 state.position++;
1931 if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
1932 state.position++;
1933 }
1934 } else {
1935 throwError(state, 'a line break is expected');
1936 }
1937
1938 state.line += 1;
1939 state.lineStart = state.position;
1940}
1941
1942function skipSeparationSpace(state, allowComments, checkIndent) {
1943 var lineBreaks = 0,
1944 ch = state.input.charCodeAt(state.position);
1945
1946 while (ch !== 0) {
1947 while (is_WHITE_SPACE(ch)) {
1948 ch = state.input.charCodeAt(++state.position);
1949 }
1950
1951 if (allowComments && ch === 0x23/* # */) {
1952 do {
1953 ch = state.input.charCodeAt(++state.position);
1954 } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
1955 }
1956
1957 if (is_EOL(ch)) {
1958 readLineBreak(state);
1959
1960 ch = state.input.charCodeAt(state.position);
1961 lineBreaks++;
1962 state.lineIndent = 0;
1963
1964 while (ch === 0x20/* Space */) {
1965 state.lineIndent++;
1966 ch = state.input.charCodeAt(++state.position);
1967 }
1968 } else {
1969 break;
1970 }
1971 }
1972
1973 if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
1974 throwWarning(state, 'deficient indentation');
1975 }
1976
1977 return lineBreaks;
1978}
1979
1980function testDocumentSeparator(state) {
1981 var _position = state.position,
1982 ch;
1983
1984 ch = state.input.charCodeAt(_position);
1985
1986 // Condition state.position === state.lineStart is tested
1987 // in parent on each call, for efficiency. No needs to test here again.
1988 if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
1989 ch === state.input.charCodeAt(_position + 1) &&
1990 ch === state.input.charCodeAt(_position + 2)) {
1991
1992 _position += 3;
1993
1994 ch = state.input.charCodeAt(_position);
1995
1996 if (ch === 0 || is_WS_OR_EOL(ch)) {
1997 return true;
1998 }
1999 }
2000
2001 return false;
2002}
2003
2004function writeFoldedLines(state, count) {
2005 if (count === 1) {
2006 state.result += ' ';
2007 } else if (count > 1) {
2008 state.result += common$1.repeat('\n', count - 1);
2009 }
2010}
2011
2012
2013function readPlainScalar(state, nodeIndent, withinFlowCollection) {
2014 var preceding,
2015 following,
2016 captureStart,
2017 captureEnd,
2018 hasPendingContent,
2019 _line,
2020 _lineStart,
2021 _lineIndent,
2022 _kind = state.kind,
2023 _result = state.result,
2024 ch;
2025
2026 ch = state.input.charCodeAt(state.position);
2027
2028 if (is_WS_OR_EOL(ch) ||
2029 is_FLOW_INDICATOR(ch) ||
2030 ch === 0x23/* # */ ||
2031 ch === 0x26/* & */ ||
2032 ch === 0x2A/* * */ ||
2033 ch === 0x21/* ! */ ||
2034 ch === 0x7C/* | */ ||
2035 ch === 0x3E/* > */ ||
2036 ch === 0x27/* ' */ ||
2037 ch === 0x22/* " */ ||
2038 ch === 0x25/* % */ ||
2039 ch === 0x40/* @ */ ||
2040 ch === 0x60/* ` */) {
2041 return false;
2042 }
2043
2044 if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
2045 following = state.input.charCodeAt(state.position + 1);
2046
2047 if (is_WS_OR_EOL(following) ||
2048 withinFlowCollection && is_FLOW_INDICATOR(following)) {
2049 return false;
2050 }
2051 }
2052
2053 state.kind = 'scalar';
2054 state.result = '';
2055 captureStart = captureEnd = state.position;
2056 hasPendingContent = false;
2057
2058 while (ch !== 0) {
2059 if (ch === 0x3A/* : */) {
2060 following = state.input.charCodeAt(state.position + 1);
2061
2062 if (is_WS_OR_EOL(following) ||
2063 withinFlowCollection && is_FLOW_INDICATOR(following)) {
2064 break;
2065 }
2066
2067 } else if (ch === 0x23/* # */) {
2068 preceding = state.input.charCodeAt(state.position - 1);
2069
2070 if (is_WS_OR_EOL(preceding)) {
2071 break;
2072 }
2073
2074 } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
2075 withinFlowCollection && is_FLOW_INDICATOR(ch)) {
2076 break;
2077
2078 } else if (is_EOL(ch)) {
2079 _line = state.line;
2080 _lineStart = state.lineStart;
2081 _lineIndent = state.lineIndent;
2082 skipSeparationSpace(state, false, -1);
2083
2084 if (state.lineIndent >= nodeIndent) {
2085 hasPendingContent = true;
2086 ch = state.input.charCodeAt(state.position);
2087 continue;
2088 } else {
2089 state.position = captureEnd;
2090 state.line = _line;
2091 state.lineStart = _lineStart;
2092 state.lineIndent = _lineIndent;
2093 break;
2094 }
2095 }
2096
2097 if (hasPendingContent) {
2098 captureSegment(state, captureStart, captureEnd, false);
2099 writeFoldedLines(state, state.line - _line);
2100 captureStart = captureEnd = state.position;
2101 hasPendingContent = false;
2102 }
2103
2104 if (!is_WHITE_SPACE(ch)) {
2105 captureEnd = state.position + 1;
2106 }
2107
2108 ch = state.input.charCodeAt(++state.position);
2109 }
2110
2111 captureSegment(state, captureStart, captureEnd, false);
2112
2113 if (state.result) {
2114 return true;
2115 }
2116
2117 state.kind = _kind;
2118 state.result = _result;
2119 return false;
2120}
2121
2122function readSingleQuotedScalar(state, nodeIndent) {
2123 var ch,
2124 captureStart, captureEnd;
2125
2126 ch = state.input.charCodeAt(state.position);
2127
2128 if (ch !== 0x27/* ' */) {
2129 return false;
2130 }
2131
2132 state.kind = 'scalar';
2133 state.result = '';
2134 state.position++;
2135 captureStart = captureEnd = state.position;
2136
2137 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
2138 if (ch === 0x27/* ' */) {
2139 captureSegment(state, captureStart, state.position, true);
2140 ch = state.input.charCodeAt(++state.position);
2141
2142 if (ch === 0x27/* ' */) {
2143 captureStart = state.position;
2144 state.position++;
2145 captureEnd = state.position;
2146 } else {
2147 return true;
2148 }
2149
2150 } else if (is_EOL(ch)) {
2151 captureSegment(state, captureStart, captureEnd, true);
2152 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
2153 captureStart = captureEnd = state.position;
2154
2155 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
2156 throwError(state, 'unexpected end of the document within a single quoted scalar');
2157
2158 } else {
2159 state.position++;
2160 captureEnd = state.position;
2161 }
2162 }
2163
2164 throwError(state, 'unexpected end of the stream within a single quoted scalar');
2165}
2166
2167function readDoubleQuotedScalar(state, nodeIndent) {
2168 var captureStart,
2169 captureEnd,
2170 hexLength,
2171 hexResult,
2172 tmp,
2173 ch;
2174
2175 ch = state.input.charCodeAt(state.position);
2176
2177 if (ch !== 0x22/* " */) {
2178 return false;
2179 }
2180
2181 state.kind = 'scalar';
2182 state.result = '';
2183 state.position++;
2184 captureStart = captureEnd = state.position;
2185
2186 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
2187 if (ch === 0x22/* " */) {
2188 captureSegment(state, captureStart, state.position, true);
2189 state.position++;
2190 return true;
2191
2192 } else if (ch === 0x5C/* \ */) {
2193 captureSegment(state, captureStart, state.position, true);
2194 ch = state.input.charCodeAt(++state.position);
2195
2196 if (is_EOL(ch)) {
2197 skipSeparationSpace(state, false, nodeIndent);
2198
2199 // TODO: rework to inline fn with no type cast?
2200 } else if (ch < 256 && simpleEscapeCheck[ch]) {
2201 state.result += simpleEscapeMap[ch];
2202 state.position++;
2203
2204 } else if ((tmp = escapedHexLen(ch)) > 0) {
2205 hexLength = tmp;
2206 hexResult = 0;
2207
2208 for (; hexLength > 0; hexLength--) {
2209 ch = state.input.charCodeAt(++state.position);
2210
2211 if ((tmp = fromHexCode(ch)) >= 0) {
2212 hexResult = (hexResult << 4) + tmp;
2213
2214 } else {
2215 throwError(state, 'expected hexadecimal character');
2216 }
2217 }
2218
2219 state.result += charFromCodepoint(hexResult);
2220
2221 state.position++;
2222
2223 } else {
2224 throwError(state, 'unknown escape sequence');
2225 }
2226
2227 captureStart = captureEnd = state.position;
2228
2229 } else if (is_EOL(ch)) {
2230 captureSegment(state, captureStart, captureEnd, true);
2231 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
2232 captureStart = captureEnd = state.position;
2233
2234 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
2235 throwError(state, 'unexpected end of the document within a double quoted scalar');
2236
2237 } else {
2238 state.position++;
2239 captureEnd = state.position;
2240 }
2241 }
2242
2243 throwError(state, 'unexpected end of the stream within a double quoted scalar');
2244}
2245
2246function readFlowCollection(state, nodeIndent) {
2247 var readNext = true,
2248 _line,
2249 _tag = state.tag,
2250 _result,
2251 _anchor = state.anchor,
2252 following,
2253 terminator,
2254 isPair,
2255 isExplicitPair,
2256 isMapping,
2257 overridableKeys = {},
2258 keyNode,
2259 keyTag,
2260 valueNode,
2261 ch;
2262
2263 ch = state.input.charCodeAt(state.position);
2264
2265 if (ch === 0x5B/* [ */) {
2266 terminator = 0x5D;/* ] */
2267 isMapping = false;
2268 _result = [];
2269 } else if (ch === 0x7B/* { */) {
2270 terminator = 0x7D;/* } */
2271 isMapping = true;
2272 _result = {};
2273 } else {
2274 return false;
2275 }
2276
2277 if (state.anchor !== null) {
2278 state.anchorMap[state.anchor] = _result;
2279 }
2280
2281 ch = state.input.charCodeAt(++state.position);
2282
2283 while (ch !== 0) {
2284 skipSeparationSpace(state, true, nodeIndent);
2285
2286 ch = state.input.charCodeAt(state.position);
2287
2288 if (ch === terminator) {
2289 state.position++;
2290 state.tag = _tag;
2291 state.anchor = _anchor;
2292 state.kind = isMapping ? 'mapping' : 'sequence';
2293 state.result = _result;
2294 return true;
2295 } else if (!readNext) {
2296 throwError(state, 'missed comma between flow collection entries');
2297 }
2298
2299 keyTag = keyNode = valueNode = null;
2300 isPair = isExplicitPair = false;
2301
2302 if (ch === 0x3F/* ? */) {
2303 following = state.input.charCodeAt(state.position + 1);
2304
2305 if (is_WS_OR_EOL(following)) {
2306 isPair = isExplicitPair = true;
2307 state.position++;
2308 skipSeparationSpace(state, true, nodeIndent);
2309 }
2310 }
2311
2312 _line = state.line;
2313 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
2314 keyTag = state.tag;
2315 keyNode = state.result;
2316 skipSeparationSpace(state, true, nodeIndent);
2317
2318 ch = state.input.charCodeAt(state.position);
2319
2320 if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
2321 isPair = true;
2322 ch = state.input.charCodeAt(++state.position);
2323 skipSeparationSpace(state, true, nodeIndent);
2324 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
2325 valueNode = state.result;
2326 }
2327
2328 if (isMapping) {
2329 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
2330 } else if (isPair) {
2331 _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
2332 } else {
2333 _result.push(keyNode);
2334 }
2335
2336 skipSeparationSpace(state, true, nodeIndent);
2337
2338 ch = state.input.charCodeAt(state.position);
2339
2340 if (ch === 0x2C/* , */) {
2341 readNext = true;
2342 ch = state.input.charCodeAt(++state.position);
2343 } else {
2344 readNext = false;
2345 }
2346 }
2347
2348 throwError(state, 'unexpected end of the stream within a flow collection');
2349}
2350
2351function readBlockScalar(state, nodeIndent) {
2352 var captureStart,
2353 folding,
2354 chomping = CHOMPING_CLIP,
2355 didReadContent = false,
2356 detectedIndent = false,
2357 textIndent = nodeIndent,
2358 emptyLines = 0,
2359 atMoreIndented = false,
2360 tmp,
2361 ch;
2362
2363 ch = state.input.charCodeAt(state.position);
2364
2365 if (ch === 0x7C/* | */) {
2366 folding = false;
2367 } else if (ch === 0x3E/* > */) {
2368 folding = true;
2369 } else {
2370 return false;
2371 }
2372
2373 state.kind = 'scalar';
2374 state.result = '';
2375
2376 while (ch !== 0) {
2377 ch = state.input.charCodeAt(++state.position);
2378
2379 if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
2380 if (CHOMPING_CLIP === chomping) {
2381 chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
2382 } else {
2383 throwError(state, 'repeat of a chomping mode identifier');
2384 }
2385
2386 } else if ((tmp = fromDecimalCode(ch)) >= 0) {
2387 if (tmp === 0) {
2388 throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
2389 } else if (!detectedIndent) {
2390 textIndent = nodeIndent + tmp - 1;
2391 detectedIndent = true;
2392 } else {
2393 throwError(state, 'repeat of an indentation width identifier');
2394 }
2395
2396 } else {
2397 break;
2398 }
2399 }
2400
2401 if (is_WHITE_SPACE(ch)) {
2402 do { ch = state.input.charCodeAt(++state.position); }
2403 while (is_WHITE_SPACE(ch));
2404
2405 if (ch === 0x23/* # */) {
2406 do { ch = state.input.charCodeAt(++state.position); }
2407 while (!is_EOL(ch) && (ch !== 0));
2408 }
2409 }
2410
2411 while (ch !== 0) {
2412 readLineBreak(state);
2413 state.lineIndent = 0;
2414
2415 ch = state.input.charCodeAt(state.position);
2416
2417 while ((!detectedIndent || state.lineIndent < textIndent) &&
2418 (ch === 0x20/* Space */)) {
2419 state.lineIndent++;
2420 ch = state.input.charCodeAt(++state.position);
2421 }
2422
2423 if (!detectedIndent && state.lineIndent > textIndent) {
2424 textIndent = state.lineIndent;
2425 }
2426
2427 if (is_EOL(ch)) {
2428 emptyLines++;
2429 continue;
2430 }
2431
2432 // End of the scalar.
2433 if (state.lineIndent < textIndent) {
2434
2435 // Perform the chomping.
2436 if (chomping === CHOMPING_KEEP) {
2437 state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
2438 } else if (chomping === CHOMPING_CLIP) {
2439 if (didReadContent) { // i.e. only if the scalar is not empty.
2440 state.result += '\n';
2441 }
2442 }
2443
2444 // Break this `while` cycle and go to the funciton's epilogue.
2445 break;
2446 }
2447
2448 // Folded style: use fancy rules to handle line breaks.
2449 if (folding) {
2450
2451 // Lines starting with white space characters (more-indented lines) are not folded.
2452 if (is_WHITE_SPACE(ch)) {
2453 atMoreIndented = true;
2454 // except for the first content line (cf. Example 8.1)
2455 state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
2456
2457 // End of more-indented block.
2458 } else if (atMoreIndented) {
2459 atMoreIndented = false;
2460 state.result += common$1.repeat('\n', emptyLines + 1);
2461
2462 // Just one line break - perceive as the same line.
2463 } else if (emptyLines === 0) {
2464 if (didReadContent) { // i.e. only if we have already read some scalar content.
2465 state.result += ' ';
2466 }
2467
2468 // Several line breaks - perceive as different lines.
2469 } else {
2470 state.result += common$1.repeat('\n', emptyLines);
2471 }
2472
2473 // Literal style: just add exact number of line breaks between content lines.
2474 } else {
2475 // Keep all line breaks except the header line break.
2476 state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
2477 }
2478
2479 didReadContent = true;
2480 detectedIndent = true;
2481 emptyLines = 0;
2482 captureStart = state.position;
2483
2484 while (!is_EOL(ch) && (ch !== 0)) {
2485 ch = state.input.charCodeAt(++state.position);
2486 }
2487
2488 captureSegment(state, captureStart, state.position, false);
2489 }
2490
2491 return true;
2492}
2493
2494function readBlockSequence(state, nodeIndent) {
2495 var _line,
2496 _tag = state.tag,
2497 _anchor = state.anchor,
2498 _result = [],
2499 following,
2500 detected = false,
2501 ch;
2502
2503 if (state.anchor !== null) {
2504 state.anchorMap[state.anchor] = _result;
2505 }
2506
2507 ch = state.input.charCodeAt(state.position);
2508
2509 while (ch !== 0) {
2510
2511 if (ch !== 0x2D/* - */) {
2512 break;
2513 }
2514
2515 following = state.input.charCodeAt(state.position + 1);
2516
2517 if (!is_WS_OR_EOL(following)) {
2518 break;
2519 }
2520
2521 detected = true;
2522 state.position++;
2523
2524 if (skipSeparationSpace(state, true, -1)) {
2525 if (state.lineIndent <= nodeIndent) {
2526 _result.push(null);
2527 ch = state.input.charCodeAt(state.position);
2528 continue;
2529 }
2530 }
2531
2532 _line = state.line;
2533 composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
2534 _result.push(state.result);
2535 skipSeparationSpace(state, true, -1);
2536
2537 ch = state.input.charCodeAt(state.position);
2538
2539 if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
2540 throwError(state, 'bad indentation of a sequence entry');
2541 } else if (state.lineIndent < nodeIndent) {
2542 break;
2543 }
2544 }
2545
2546 if (detected) {
2547 state.tag = _tag;
2548 state.anchor = _anchor;
2549 state.kind = 'sequence';
2550 state.result = _result;
2551 return true;
2552 }
2553 return false;
2554}
2555
2556function readBlockMapping(state, nodeIndent, flowIndent) {
2557 var following,
2558 allowCompact,
2559 _line,
2560 _pos,
2561 _tag = state.tag,
2562 _anchor = state.anchor,
2563 _result = {},
2564 overridableKeys = {},
2565 keyTag = null,
2566 keyNode = null,
2567 valueNode = null,
2568 atExplicitKey = false,
2569 detected = false,
2570 ch;
2571
2572 if (state.anchor !== null) {
2573 state.anchorMap[state.anchor] = _result;
2574 }
2575
2576 ch = state.input.charCodeAt(state.position);
2577
2578 while (ch !== 0) {
2579 following = state.input.charCodeAt(state.position + 1);
2580 _line = state.line; // Save the current line.
2581 _pos = state.position;
2582
2583 //
2584 // Explicit notation case. There are two separate blocks:
2585 // first for the key (denoted by "?") and second for the value (denoted by ":")
2586 //
2587 if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
2588
2589 if (ch === 0x3F/* ? */) {
2590 if (atExplicitKey) {
2591 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
2592 keyTag = keyNode = valueNode = null;
2593 }
2594
2595 detected = true;
2596 atExplicitKey = true;
2597 allowCompact = true;
2598
2599 } else if (atExplicitKey) {
2600 // i.e. 0x3A/* : */ === character after the explicit key.
2601 atExplicitKey = false;
2602 allowCompact = true;
2603
2604 } else {
2605 throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
2606 }
2607
2608 state.position += 1;
2609 ch = following;
2610
2611 //
2612 // Implicit notation case. Flow-style node as the key first, then ":", and the value.
2613 //
2614 } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
2615
2616 if (state.line === _line) {
2617 ch = state.input.charCodeAt(state.position);
2618
2619 while (is_WHITE_SPACE(ch)) {
2620 ch = state.input.charCodeAt(++state.position);
2621 }
2622
2623 if (ch === 0x3A/* : */) {
2624 ch = state.input.charCodeAt(++state.position);
2625
2626 if (!is_WS_OR_EOL(ch)) {
2627 throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
2628 }
2629
2630 if (atExplicitKey) {
2631 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
2632 keyTag = keyNode = valueNode = null;
2633 }
2634
2635 detected = true;
2636 atExplicitKey = false;
2637 allowCompact = false;
2638 keyTag = state.tag;
2639 keyNode = state.result;
2640
2641 } else if (detected) {
2642 throwError(state, 'can not read an implicit mapping pair; a colon is missed');
2643
2644 } else {
2645 state.tag = _tag;
2646 state.anchor = _anchor;
2647 return true; // Keep the result of `composeNode`.
2648 }
2649
2650 } else if (detected) {
2651 throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
2652
2653 } else {
2654 state.tag = _tag;
2655 state.anchor = _anchor;
2656 return true; // Keep the result of `composeNode`.
2657 }
2658
2659 } else {
2660 break; // Reading is done. Go to the epilogue.
2661 }
2662
2663 //
2664 // Common reading code for both explicit and implicit notations.
2665 //
2666 if (state.line === _line || state.lineIndent > nodeIndent) {
2667 if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
2668 if (atExplicitKey) {
2669 keyNode = state.result;
2670 } else {
2671 valueNode = state.result;
2672 }
2673 }
2674
2675 if (!atExplicitKey) {
2676 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
2677 keyTag = keyNode = valueNode = null;
2678 }
2679
2680 skipSeparationSpace(state, true, -1);
2681 ch = state.input.charCodeAt(state.position);
2682 }
2683
2684 if (state.lineIndent > nodeIndent && (ch !== 0)) {
2685 throwError(state, 'bad indentation of a mapping entry');
2686 } else if (state.lineIndent < nodeIndent) {
2687 break;
2688 }
2689 }
2690
2691 //
2692 // Epilogue.
2693 //
2694
2695 // Special case: last mapping's node contains only the key in explicit notation.
2696 if (atExplicitKey) {
2697 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
2698 }
2699
2700 // Expose the resulting mapping.
2701 if (detected) {
2702 state.tag = _tag;
2703 state.anchor = _anchor;
2704 state.kind = 'mapping';
2705 state.result = _result;
2706 }
2707
2708 return detected;
2709}
2710
2711function readTagProperty(state) {
2712 var _position,
2713 isVerbatim = false,
2714 isNamed = false,
2715 tagHandle,
2716 tagName,
2717 ch;
2718
2719 ch = state.input.charCodeAt(state.position);
2720
2721 if (ch !== 0x21/* ! */) return false;
2722
2723 if (state.tag !== null) {
2724 throwError(state, 'duplication of a tag property');
2725 }
2726
2727 ch = state.input.charCodeAt(++state.position);
2728
2729 if (ch === 0x3C/* < */) {
2730 isVerbatim = true;
2731 ch = state.input.charCodeAt(++state.position);
2732
2733 } else if (ch === 0x21/* ! */) {
2734 isNamed = true;
2735 tagHandle = '!!';
2736 ch = state.input.charCodeAt(++state.position);
2737
2738 } else {
2739 tagHandle = '!';
2740 }
2741
2742 _position = state.position;
2743
2744 if (isVerbatim) {
2745 do { ch = state.input.charCodeAt(++state.position); }
2746 while (ch !== 0 && ch !== 0x3E/* > */);
2747
2748 if (state.position < state.length) {
2749 tagName = state.input.slice(_position, state.position);
2750 ch = state.input.charCodeAt(++state.position);
2751 } else {
2752 throwError(state, 'unexpected end of the stream within a verbatim tag');
2753 }
2754 } else {
2755 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
2756
2757 if (ch === 0x21/* ! */) {
2758 if (!isNamed) {
2759 tagHandle = state.input.slice(_position - 1, state.position + 1);
2760
2761 if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
2762 throwError(state, 'named tag handle cannot contain such characters');
2763 }
2764
2765 isNamed = true;
2766 _position = state.position + 1;
2767 } else {
2768 throwError(state, 'tag suffix cannot contain exclamation marks');
2769 }
2770 }
2771
2772 ch = state.input.charCodeAt(++state.position);
2773 }
2774
2775 tagName = state.input.slice(_position, state.position);
2776
2777 if (PATTERN_FLOW_INDICATORS.test(tagName)) {
2778 throwError(state, 'tag suffix cannot contain flow indicator characters');
2779 }
2780 }
2781
2782 if (tagName && !PATTERN_TAG_URI.test(tagName)) {
2783 throwError(state, 'tag name cannot contain such characters: ' + tagName);
2784 }
2785
2786 if (isVerbatim) {
2787 state.tag = tagName;
2788
2789 } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
2790 state.tag = state.tagMap[tagHandle] + tagName;
2791
2792 } else if (tagHandle === '!') {
2793 state.tag = '!' + tagName;
2794
2795 } else if (tagHandle === '!!') {
2796 state.tag = 'tag:yaml.org,2002:' + tagName;
2797
2798 } else {
2799 throwError(state, 'undeclared tag handle "' + tagHandle + '"');
2800 }
2801
2802 return true;
2803}
2804
2805function readAnchorProperty(state) {
2806 var _position,
2807 ch;
2808
2809 ch = state.input.charCodeAt(state.position);
2810
2811 if (ch !== 0x26/* & */) return false;
2812
2813 if (state.anchor !== null) {
2814 throwError(state, 'duplication of an anchor property');
2815 }
2816
2817 ch = state.input.charCodeAt(++state.position);
2818 _position = state.position;
2819
2820 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
2821 ch = state.input.charCodeAt(++state.position);
2822 }
2823
2824 if (state.position === _position) {
2825 throwError(state, 'name of an anchor node must contain at least one character');
2826 }
2827
2828 state.anchor = state.input.slice(_position, state.position);
2829 return true;
2830}
2831
2832function readAlias(state) {
2833 var _position, alias,
2834 ch;
2835
2836 ch = state.input.charCodeAt(state.position);
2837
2838 if (ch !== 0x2A/* * */) return false;
2839
2840 ch = state.input.charCodeAt(++state.position);
2841 _position = state.position;
2842
2843 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
2844 ch = state.input.charCodeAt(++state.position);
2845 }
2846
2847 if (state.position === _position) {
2848 throwError(state, 'name of an alias node must contain at least one character');
2849 }
2850
2851 alias = state.input.slice(_position, state.position);
2852
2853 if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
2854 throwError(state, 'unidentified alias "' + alias + '"');
2855 }
2856
2857 state.result = state.anchorMap[alias];
2858 skipSeparationSpace(state, true, -1);
2859 return true;
2860}
2861
2862function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
2863 var allowBlockStyles,
2864 allowBlockScalars,
2865 allowBlockCollections,
2866 indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
2867 atNewLine = false,
2868 hasContent = false,
2869 typeIndex,
2870 typeQuantity,
2871 type,
2872 flowIndent,
2873 blockIndent;
2874
2875 if (state.listener !== null) {
2876 state.listener('open', state);
2877 }
2878
2879 state.tag = null;
2880 state.anchor = null;
2881 state.kind = null;
2882 state.result = null;
2883
2884 allowBlockStyles = allowBlockScalars = allowBlockCollections =
2885 CONTEXT_BLOCK_OUT === nodeContext ||
2886 CONTEXT_BLOCK_IN === nodeContext;
2887
2888 if (allowToSeek) {
2889 if (skipSeparationSpace(state, true, -1)) {
2890 atNewLine = true;
2891
2892 if (state.lineIndent > parentIndent) {
2893 indentStatus = 1;
2894 } else if (state.lineIndent === parentIndent) {
2895 indentStatus = 0;
2896 } else if (state.lineIndent < parentIndent) {
2897 indentStatus = -1;
2898 }
2899 }
2900 }
2901
2902 if (indentStatus === 1) {
2903 while (readTagProperty(state) || readAnchorProperty(state)) {
2904 if (skipSeparationSpace(state, true, -1)) {
2905 atNewLine = true;
2906 allowBlockCollections = allowBlockStyles;
2907
2908 if (state.lineIndent > parentIndent) {
2909 indentStatus = 1;
2910 } else if (state.lineIndent === parentIndent) {
2911 indentStatus = 0;
2912 } else if (state.lineIndent < parentIndent) {
2913 indentStatus = -1;
2914 }
2915 } else {
2916 allowBlockCollections = false;
2917 }
2918 }
2919 }
2920
2921 if (allowBlockCollections) {
2922 allowBlockCollections = atNewLine || allowCompact;
2923 }
2924
2925 if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
2926 if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
2927 flowIndent = parentIndent;
2928 } else {
2929 flowIndent = parentIndent + 1;
2930 }
2931
2932 blockIndent = state.position - state.lineStart;
2933
2934 if (indentStatus === 1) {
2935 if (allowBlockCollections &&
2936 (readBlockSequence(state, blockIndent) ||
2937 readBlockMapping(state, blockIndent, flowIndent)) ||
2938 readFlowCollection(state, flowIndent)) {
2939 hasContent = true;
2940 } else {
2941 if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
2942 readSingleQuotedScalar(state, flowIndent) ||
2943 readDoubleQuotedScalar(state, flowIndent)) {
2944 hasContent = true;
2945
2946 } else if (readAlias(state)) {
2947 hasContent = true;
2948
2949 if (state.tag !== null || state.anchor !== null) {
2950 throwError(state, 'alias node should not have any properties');
2951 }
2952
2953 } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
2954 hasContent = true;
2955
2956 if (state.tag === null) {
2957 state.tag = '?';
2958 }
2959 }
2960
2961 if (state.anchor !== null) {
2962 state.anchorMap[state.anchor] = state.result;
2963 }
2964 }
2965 } else if (indentStatus === 0) {
2966 // Special case: block sequences are allowed to have same indentation level as the parent.
2967 // http://www.yaml.org/spec/1.2/spec.html#id2799784
2968 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
2969 }
2970 }
2971
2972 if (state.tag !== null && state.tag !== '!') {
2973 if (state.tag === '?') {
2974 // Implicit resolving is not allowed for non-scalar types, and '?'
2975 // non-specific tag is only automatically assigned to plain scalars.
2976 //
2977 // We only need to check kind conformity in case user explicitly assigns '?'
2978 // tag, for example like this: "!<?> [0]"
2979 //
2980 if (state.result !== null && state.kind !== 'scalar') {
2981 throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
2982 }
2983
2984 for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
2985 type = state.implicitTypes[typeIndex];
2986
2987 if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
2988 state.result = type.construct(state.result);
2989 state.tag = type.tag;
2990 if (state.anchor !== null) {
2991 state.anchorMap[state.anchor] = state.result;
2992 }
2993 break;
2994 }
2995 }
2996 } else if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
2997 type = state.typeMap[state.kind || 'fallback'][state.tag];
2998
2999 if (state.result !== null && type.kind !== state.kind) {
3000 throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
3001 }
3002
3003 if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched
3004 throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
3005 } else {
3006 state.result = type.construct(state.result);
3007 if (state.anchor !== null) {
3008 state.anchorMap[state.anchor] = state.result;
3009 }
3010 }
3011 } else {
3012 throwError(state, 'unknown tag !<' + state.tag + '>');
3013 }
3014 }
3015
3016 if (state.listener !== null) {
3017 state.listener('close', state);
3018 }
3019 return state.tag !== null || state.anchor !== null || hasContent;
3020}
3021
3022function readDocument(state) {
3023 var documentStart = state.position,
3024 _position,
3025 directiveName,
3026 directiveArgs,
3027 hasDirectives = false,
3028 ch;
3029
3030 state.version = null;
3031 state.checkLineBreaks = state.legacy;
3032 state.tagMap = {};
3033 state.anchorMap = {};
3034
3035 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
3036 skipSeparationSpace(state, true, -1);
3037
3038 ch = state.input.charCodeAt(state.position);
3039
3040 if (state.lineIndent > 0 || ch !== 0x25/* % */) {
3041 break;
3042 }
3043
3044 hasDirectives = true;
3045 ch = state.input.charCodeAt(++state.position);
3046 _position = state.position;
3047
3048 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
3049 ch = state.input.charCodeAt(++state.position);
3050 }
3051
3052 directiveName = state.input.slice(_position, state.position);
3053 directiveArgs = [];
3054
3055 if (directiveName.length < 1) {
3056 throwError(state, 'directive name must not be less than one character in length');
3057 }
3058
3059 while (ch !== 0) {
3060 while (is_WHITE_SPACE(ch)) {
3061 ch = state.input.charCodeAt(++state.position);
3062 }
3063
3064 if (ch === 0x23/* # */) {
3065 do { ch = state.input.charCodeAt(++state.position); }
3066 while (ch !== 0 && !is_EOL(ch));
3067 break;
3068 }
3069
3070 if (is_EOL(ch)) break;
3071
3072 _position = state.position;
3073
3074 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
3075 ch = state.input.charCodeAt(++state.position);
3076 }
3077
3078 directiveArgs.push(state.input.slice(_position, state.position));
3079 }
3080
3081 if (ch !== 0) readLineBreak(state);
3082
3083 if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
3084 directiveHandlers[directiveName](state, directiveName, directiveArgs);
3085 } else {
3086 throwWarning(state, 'unknown document directive "' + directiveName + '"');
3087 }
3088 }
3089
3090 skipSeparationSpace(state, true, -1);
3091
3092 if (state.lineIndent === 0 &&
3093 state.input.charCodeAt(state.position) === 0x2D/* - */ &&
3094 state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
3095 state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
3096 state.position += 3;
3097 skipSeparationSpace(state, true, -1);
3098
3099 } else if (hasDirectives) {
3100 throwError(state, 'directives end mark is expected');
3101 }
3102
3103 composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
3104 skipSeparationSpace(state, true, -1);
3105
3106 if (state.checkLineBreaks &&
3107 PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
3108 throwWarning(state, 'non-ASCII line breaks are interpreted as content');
3109 }
3110
3111 state.documents.push(state.result);
3112
3113 if (state.position === state.lineStart && testDocumentSeparator(state)) {
3114
3115 if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
3116 state.position += 3;
3117 skipSeparationSpace(state, true, -1);
3118 }
3119 return;
3120 }
3121
3122 if (state.position < (state.length - 1)) {
3123 throwError(state, 'end of the stream or a document separator is expected');
3124 } else {
3125 return;
3126 }
3127}
3128
3129
3130function loadDocuments(input, options) {
3131 input = String(input);
3132 options = options || {};
3133
3134 if (input.length !== 0) {
3135
3136 // Add tailing `\n` if not exists
3137 if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
3138 input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
3139 input += '\n';
3140 }
3141
3142 // Strip BOM
3143 if (input.charCodeAt(0) === 0xFEFF) {
3144 input = input.slice(1);
3145 }
3146 }
3147
3148 var state = new State$1(input, options);
3149
3150 var nullpos = input.indexOf('\0');
3151
3152 if (nullpos !== -1) {
3153 state.position = nullpos;
3154 throwError(state, 'null byte is not allowed in input');
3155 }
3156
3157 // Use 0 as string terminator. That significantly simplifies bounds check.
3158 state.input += '\0';
3159
3160 while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
3161 state.lineIndent += 1;
3162 state.position += 1;
3163 }
3164
3165 while (state.position < (state.length - 1)) {
3166 readDocument(state);
3167 }
3168
3169 return state.documents;
3170}
3171
3172
3173function loadAll(input, iterator, options) {
3174 if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
3175 options = iterator;
3176 iterator = null;
3177 }
3178
3179 var documents = loadDocuments(input, options);
3180
3181 if (typeof iterator !== 'function') {
3182 return documents;
3183 }
3184
3185 for (var index = 0, length = documents.length; index < length; index += 1) {
3186 iterator(documents[index]);
3187 }
3188}
3189
3190
3191function load(input, options) {
3192 var documents = loadDocuments(input, options);
3193
3194 if (documents.length === 0) {
3195 /*eslint-disable no-undefined*/
3196 return undefined;
3197 } else if (documents.length === 1) {
3198 return documents[0];
3199 }
3200 throw new YAMLException$1('expected a single document in the stream, but found more');
3201}
3202
3203
3204function safeLoadAll(input, iterator, options) {
3205 if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') {
3206 options = iterator;
3207 iterator = null;
3208 }
3209
3210 return loadAll(input, iterator, common$1.extend({ schema: DEFAULT_SAFE_SCHEMA$1 }, options));
3211}
3212
3213
3214function safeLoad(input, options) {
3215 return load(input, common$1.extend({ schema: DEFAULT_SAFE_SCHEMA$1 }, options));
3216}
3217
3218
3219loader$1.loadAll = loadAll;
3220loader$1.load = load;
3221loader$1.safeLoadAll = safeLoadAll;
3222loader$1.safeLoad = safeLoad;
3223
3224var dumper$1 = {};
3225
3226/*eslint-disable no-use-before-define*/
3227
3228var common = common$6;
3229var YAMLException = exception;
3230var DEFAULT_FULL_SCHEMA = default_full;
3231var DEFAULT_SAFE_SCHEMA = default_safe;
3232
3233var _toString = Object.prototype.toString;
3234var _hasOwnProperty = Object.prototype.hasOwnProperty;
3235
3236var CHAR_TAB = 0x09; /* Tab */
3237var CHAR_LINE_FEED = 0x0A; /* LF */
3238var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
3239var CHAR_SPACE = 0x20; /* Space */
3240var CHAR_EXCLAMATION = 0x21; /* ! */
3241var CHAR_DOUBLE_QUOTE = 0x22; /* " */
3242var CHAR_SHARP = 0x23; /* # */
3243var CHAR_PERCENT = 0x25; /* % */
3244var CHAR_AMPERSAND = 0x26; /* & */
3245var CHAR_SINGLE_QUOTE = 0x27; /* ' */
3246var CHAR_ASTERISK = 0x2A; /* * */
3247var CHAR_COMMA = 0x2C; /* , */
3248var CHAR_MINUS = 0x2D; /* - */
3249var CHAR_COLON = 0x3A; /* : */
3250var CHAR_EQUALS = 0x3D; /* = */
3251var CHAR_GREATER_THAN = 0x3E; /* > */
3252var CHAR_QUESTION = 0x3F; /* ? */
3253var CHAR_COMMERCIAL_AT = 0x40; /* @ */
3254var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
3255var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
3256var CHAR_GRAVE_ACCENT = 0x60; /* ` */
3257var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
3258var CHAR_VERTICAL_LINE = 0x7C; /* | */
3259var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
3260
3261var ESCAPE_SEQUENCES = {};
3262
3263ESCAPE_SEQUENCES[0x00] = '\\0';
3264ESCAPE_SEQUENCES[0x07] = '\\a';
3265ESCAPE_SEQUENCES[0x08] = '\\b';
3266ESCAPE_SEQUENCES[0x09] = '\\t';
3267ESCAPE_SEQUENCES[0x0A] = '\\n';
3268ESCAPE_SEQUENCES[0x0B] = '\\v';
3269ESCAPE_SEQUENCES[0x0C] = '\\f';
3270ESCAPE_SEQUENCES[0x0D] = '\\r';
3271ESCAPE_SEQUENCES[0x1B] = '\\e';
3272ESCAPE_SEQUENCES[0x22] = '\\"';
3273ESCAPE_SEQUENCES[0x5C] = '\\\\';
3274ESCAPE_SEQUENCES[0x85] = '\\N';
3275ESCAPE_SEQUENCES[0xA0] = '\\_';
3276ESCAPE_SEQUENCES[0x2028] = '\\L';
3277ESCAPE_SEQUENCES[0x2029] = '\\P';
3278
3279var DEPRECATED_BOOLEANS_SYNTAX = [
3280 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
3281 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
3282];
3283
3284function compileStyleMap(schema, map) {
3285 var result, keys, index, length, tag, style, type;
3286
3287 if (map === null) return {};
3288
3289 result = {};
3290 keys = Object.keys(map);
3291
3292 for (index = 0, length = keys.length; index < length; index += 1) {
3293 tag = keys[index];
3294 style = String(map[tag]);
3295
3296 if (tag.slice(0, 2) === '!!') {
3297 tag = 'tag:yaml.org,2002:' + tag.slice(2);
3298 }
3299 type = schema.compiledTypeMap['fallback'][tag];
3300
3301 if (type && _hasOwnProperty.call(type.styleAliases, style)) {
3302 style = type.styleAliases[style];
3303 }
3304
3305 result[tag] = style;
3306 }
3307
3308 return result;
3309}
3310
3311function encodeHex(character) {
3312 var string, handle, length;
3313
3314 string = character.toString(16).toUpperCase();
3315
3316 if (character <= 0xFF) {
3317 handle = 'x';
3318 length = 2;
3319 } else if (character <= 0xFFFF) {
3320 handle = 'u';
3321 length = 4;
3322 } else if (character <= 0xFFFFFFFF) {
3323 handle = 'U';
3324 length = 8;
3325 } else {
3326 throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
3327 }
3328
3329 return '\\' + handle + common.repeat('0', length - string.length) + string;
3330}
3331
3332function State(options) {
3333 this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
3334 this.indent = Math.max(1, (options['indent'] || 2));
3335 this.noArrayIndent = options['noArrayIndent'] || false;
3336 this.skipInvalid = options['skipInvalid'] || false;
3337 this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
3338 this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
3339 this.sortKeys = options['sortKeys'] || false;
3340 this.lineWidth = options['lineWidth'] || 80;
3341 this.noRefs = options['noRefs'] || false;
3342 this.noCompatMode = options['noCompatMode'] || false;
3343 this.condenseFlow = options['condenseFlow'] || false;
3344
3345 this.implicitTypes = this.schema.compiledImplicit;
3346 this.explicitTypes = this.schema.compiledExplicit;
3347
3348 this.tag = null;
3349 this.result = '';
3350
3351 this.duplicates = [];
3352 this.usedDuplicates = null;
3353}
3354
3355// Indents every line in a string. Empty lines (\n only) are not indented.
3356function indentString(string, spaces) {
3357 var ind = common.repeat(' ', spaces),
3358 position = 0,
3359 next = -1,
3360 result = '',
3361 line,
3362 length = string.length;
3363
3364 while (position < length) {
3365 next = string.indexOf('\n', position);
3366 if (next === -1) {
3367 line = string.slice(position);
3368 position = length;
3369 } else {
3370 line = string.slice(position, next + 1);
3371 position = next + 1;
3372 }
3373
3374 if (line.length && line !== '\n') result += ind;
3375
3376 result += line;
3377 }
3378
3379 return result;
3380}
3381
3382function generateNextLine(state, level) {
3383 return '\n' + common.repeat(' ', state.indent * level);
3384}
3385
3386function testImplicitResolving(state, str) {
3387 var index, length, type;
3388
3389 for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
3390 type = state.implicitTypes[index];
3391
3392 if (type.resolve(str)) {
3393 return true;
3394 }
3395 }
3396
3397 return false;
3398}
3399
3400// [33] s-white ::= s-space | s-tab
3401function isWhitespace(c) {
3402 return c === CHAR_SPACE || c === CHAR_TAB;
3403}
3404
3405// Returns true if the character can be printed without escaping.
3406// From YAML 1.2: "any allowed characters known to be non-printable
3407// should also be escaped. [However,] This isn’t mandatory"
3408// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
3409function isPrintable(c) {
3410 return (0x00020 <= c && c <= 0x00007E)
3411 || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
3412 || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
3413 || (0x10000 <= c && c <= 0x10FFFF);
3414}
3415
3416// [34] ns-char ::= nb-char - s-white
3417// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
3418// [26] b-char ::= b-line-feed | b-carriage-return
3419// [24] b-line-feed ::= #xA /* LF */
3420// [25] b-carriage-return ::= #xD /* CR */
3421// [3] c-byte-order-mark ::= #xFEFF
3422function isNsChar(c) {
3423 return isPrintable(c) && !isWhitespace(c)
3424 // byte-order-mark
3425 && c !== 0xFEFF
3426 // b-char
3427 && c !== CHAR_CARRIAGE_RETURN
3428 && c !== CHAR_LINE_FEED;
3429}
3430
3431// Simplified test for values allowed after the first character in plain style.
3432function isPlainSafe(c, prev) {
3433 // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
3434 // where nb-char ::= c-printable - b-char - c-byte-order-mark.
3435 return isPrintable(c) && c !== 0xFEFF
3436 // - c-flow-indicator
3437 && c !== CHAR_COMMA
3438 && c !== CHAR_LEFT_SQUARE_BRACKET
3439 && c !== CHAR_RIGHT_SQUARE_BRACKET
3440 && c !== CHAR_LEFT_CURLY_BRACKET
3441 && c !== CHAR_RIGHT_CURLY_BRACKET
3442 // - ":" - "#"
3443 // /* An ns-char preceding */ "#"
3444 && c !== CHAR_COLON
3445 && ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));
3446}
3447
3448// Simplified test for values allowed as the first character in plain style.
3449function isPlainSafeFirst(c) {
3450 // Uses a subset of ns-char - c-indicator
3451 // where ns-char = nb-char - s-white.
3452 return isPrintable(c) && c !== 0xFEFF
3453 && !isWhitespace(c) // - s-white
3454 // - (c-indicator ::=
3455 // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
3456 && c !== CHAR_MINUS
3457 && c !== CHAR_QUESTION
3458 && c !== CHAR_COLON
3459 && c !== CHAR_COMMA
3460 && c !== CHAR_LEFT_SQUARE_BRACKET
3461 && c !== CHAR_RIGHT_SQUARE_BRACKET
3462 && c !== CHAR_LEFT_CURLY_BRACKET
3463 && c !== CHAR_RIGHT_CURLY_BRACKET
3464 // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
3465 && c !== CHAR_SHARP
3466 && c !== CHAR_AMPERSAND
3467 && c !== CHAR_ASTERISK
3468 && c !== CHAR_EXCLAMATION
3469 && c !== CHAR_VERTICAL_LINE
3470 && c !== CHAR_EQUALS
3471 && c !== CHAR_GREATER_THAN
3472 && c !== CHAR_SINGLE_QUOTE
3473 && c !== CHAR_DOUBLE_QUOTE
3474 // | “%” | “@” | “`”)
3475 && c !== CHAR_PERCENT
3476 && c !== CHAR_COMMERCIAL_AT
3477 && c !== CHAR_GRAVE_ACCENT;
3478}
3479
3480// Determines whether block indentation indicator is required.
3481function needIndentIndicator(string) {
3482 var leadingSpaceRe = /^\n* /;
3483 return leadingSpaceRe.test(string);
3484}
3485
3486var STYLE_PLAIN = 1,
3487 STYLE_SINGLE = 2,
3488 STYLE_LITERAL = 3,
3489 STYLE_FOLDED = 4,
3490 STYLE_DOUBLE = 5;
3491
3492// Determines which scalar styles are possible and returns the preferred style.
3493// lineWidth = -1 => no limit.
3494// Pre-conditions: str.length > 0.
3495// Post-conditions:
3496// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
3497// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
3498// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
3499function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
3500 var i;
3501 var char, prev_char;
3502 var hasLineBreak = false;
3503 var hasFoldableLine = false; // only checked if shouldTrackWidth
3504 var shouldTrackWidth = lineWidth !== -1;
3505 var previousLineBreak = -1; // count the first line correctly
3506 var plain = isPlainSafeFirst(string.charCodeAt(0))
3507 && !isWhitespace(string.charCodeAt(string.length - 1));
3508
3509 if (singleLineOnly) {
3510 // Case: no block styles.
3511 // Check for disallowed characters to rule out plain and single.
3512 for (i = 0; i < string.length; i++) {
3513 char = string.charCodeAt(i);
3514 if (!isPrintable(char)) {
3515 return STYLE_DOUBLE;
3516 }
3517 prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
3518 plain = plain && isPlainSafe(char, prev_char);
3519 }
3520 } else {
3521 // Case: block styles permitted.
3522 for (i = 0; i < string.length; i++) {
3523 char = string.charCodeAt(i);
3524 if (char === CHAR_LINE_FEED) {
3525 hasLineBreak = true;
3526 // Check if any line can be folded.
3527 if (shouldTrackWidth) {
3528 hasFoldableLine = hasFoldableLine ||
3529 // Foldable line = too long, and not more-indented.
3530 (i - previousLineBreak - 1 > lineWidth &&
3531 string[previousLineBreak + 1] !== ' ');
3532 previousLineBreak = i;
3533 }
3534 } else if (!isPrintable(char)) {
3535 return STYLE_DOUBLE;
3536 }
3537 prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
3538 plain = plain && isPlainSafe(char, prev_char);
3539 }
3540 // in case the end is missing a \n
3541 hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
3542 (i - previousLineBreak - 1 > lineWidth &&
3543 string[previousLineBreak + 1] !== ' '));
3544 }
3545 // Although every style can represent \n without escaping, prefer block styles
3546 // for multiline, since they're more readable and they don't add empty lines.
3547 // Also prefer folding a super-long line.
3548 if (!hasLineBreak && !hasFoldableLine) {
3549 // Strings interpretable as another type have to be quoted;
3550 // e.g. the string 'true' vs. the boolean true.
3551 return plain && !testAmbiguousType(string)
3552 ? STYLE_PLAIN : STYLE_SINGLE;
3553 }
3554 // Edge case: block indentation indicator can only have one digit.
3555 if (indentPerLevel > 9 && needIndentIndicator(string)) {
3556 return STYLE_DOUBLE;
3557 }
3558 // At this point we know block styles are valid.
3559 // Prefer literal style unless we want to fold.
3560 return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
3561}
3562
3563// Note: line breaking/folding is implemented for only the folded style.
3564// NB. We drop the last trailing newline (if any) of a returned block scalar
3565// since the dumper adds its own newline. This always works:
3566// • No ending newline => unaffected; already using strip "-" chomping.
3567// • Ending newline => removed then restored.
3568// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
3569function writeScalar(state, string, level, iskey) {
3570 state.dump = (function () {
3571 if (string.length === 0) {
3572 return "''";
3573 }
3574 if (!state.noCompatMode &&
3575 DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
3576 return "'" + string + "'";
3577 }
3578
3579 var indent = state.indent * Math.max(1, level); // no 0-indent scalars
3580 // As indentation gets deeper, let the width decrease monotonically
3581 // to the lower bound min(state.lineWidth, 40).
3582 // Note that this implies
3583 // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
3584 // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
3585 // This behaves better than a constant minimum width which disallows narrower options,
3586 // or an indent threshold which causes the width to suddenly increase.
3587 var lineWidth = state.lineWidth === -1
3588 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
3589
3590 // Without knowing if keys are implicit/explicit, assume implicit for safety.
3591 var singleLineOnly = iskey
3592 // No block styles in flow mode.
3593 || (state.flowLevel > -1 && level >= state.flowLevel);
3594 function testAmbiguity(string) {
3595 return testImplicitResolving(state, string);
3596 }
3597
3598 switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
3599 case STYLE_PLAIN:
3600 return string;
3601 case STYLE_SINGLE:
3602 return "'" + string.replace(/'/g, "''") + "'";
3603 case STYLE_LITERAL:
3604 return '|' + blockHeader(string, state.indent)
3605 + dropEndingNewline(indentString(string, indent));
3606 case STYLE_FOLDED:
3607 return '>' + blockHeader(string, state.indent)
3608 + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
3609 case STYLE_DOUBLE:
3610 return '"' + escapeString(string) + '"';
3611 default:
3612 throw new YAMLException('impossible error: invalid scalar style');
3613 }
3614 }());
3615}
3616
3617// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
3618function blockHeader(string, indentPerLevel) {
3619 var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
3620
3621 // note the special case: the string '\n' counts as a "trailing" empty line.
3622 var clip = string[string.length - 1] === '\n';
3623 var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
3624 var chomp = keep ? '+' : (clip ? '' : '-');
3625
3626 return indentIndicator + chomp + '\n';
3627}
3628
3629// (See the note for writeScalar.)
3630function dropEndingNewline(string) {
3631 return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
3632}
3633
3634// Note: a long line without a suitable break point will exceed the width limit.
3635// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
3636function foldString(string, width) {
3637 // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
3638 // unless they're before or after a more-indented line, or at the very
3639 // beginning or end, in which case $k$ maps to $k$.
3640 // Therefore, parse each chunk as newline(s) followed by a content line.
3641 var lineRe = /(\n+)([^\n]*)/g;
3642
3643 // first line (possibly an empty line)
3644 var result = (function () {
3645 var nextLF = string.indexOf('\n');
3646 nextLF = nextLF !== -1 ? nextLF : string.length;
3647 lineRe.lastIndex = nextLF;
3648 return foldLine(string.slice(0, nextLF), width);
3649 }());
3650 // If we haven't reached the first content line yet, don't add an extra \n.
3651 var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
3652 var moreIndented;
3653
3654 // rest of the lines
3655 var match;
3656 while ((match = lineRe.exec(string))) {
3657 var prefix = match[1], line = match[2];
3658 moreIndented = (line[0] === ' ');
3659 result += prefix
3660 + (!prevMoreIndented && !moreIndented && line !== ''
3661 ? '\n' : '')
3662 + foldLine(line, width);
3663 prevMoreIndented = moreIndented;
3664 }
3665
3666 return result;
3667}
3668
3669// Greedy line breaking.
3670// Picks the longest line under the limit each time,
3671// otherwise settles for the shortest line over the limit.
3672// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
3673function foldLine(line, width) {
3674 if (line === '' || line[0] === ' ') return line;
3675
3676 // Since a more-indented line adds a \n, breaks can't be followed by a space.
3677 var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
3678 var match;
3679 // start is an inclusive index. end, curr, and next are exclusive.
3680 var start = 0, end, curr = 0, next = 0;
3681 var result = '';
3682
3683 // Invariants: 0 <= start <= length-1.
3684 // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
3685 // Inside the loop:
3686 // A match implies length >= 2, so curr and next are <= length-2.
3687 while ((match = breakRe.exec(line))) {
3688 next = match.index;
3689 // maintain invariant: curr - start <= width
3690 if (next - start > width) {
3691 end = (curr > start) ? curr : next; // derive end <= length-2
3692 result += '\n' + line.slice(start, end);
3693 // skip the space that was output as \n
3694 start = end + 1; // derive start <= length-1
3695 }
3696 curr = next;
3697 }
3698
3699 // By the invariants, start <= length-1, so there is something left over.
3700 // It is either the whole string or a part starting from non-whitespace.
3701 result += '\n';
3702 // Insert a break if the remainder is too long and there is a break available.
3703 if (line.length - start > width && curr > start) {
3704 result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
3705 } else {
3706 result += line.slice(start);
3707 }
3708
3709 return result.slice(1); // drop extra \n joiner
3710}
3711
3712// Escapes a double-quoted string.
3713function escapeString(string) {
3714 var result = '';
3715 var char, nextChar;
3716 var escapeSeq;
3717
3718 for (var i = 0; i < string.length; i++) {
3719 char = string.charCodeAt(i);
3720 // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
3721 if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
3722 nextChar = string.charCodeAt(i + 1);
3723 if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
3724 // Combine the surrogate pair and store it escaped.
3725 result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
3726 // Advance index one extra since we already used that char here.
3727 i++; continue;
3728 }
3729 }
3730 escapeSeq = ESCAPE_SEQUENCES[char];
3731 result += !escapeSeq && isPrintable(char)
3732 ? string[i]
3733 : escapeSeq || encodeHex(char);
3734 }
3735
3736 return result;
3737}
3738
3739function writeFlowSequence(state, level, object) {
3740 var _result = '',
3741 _tag = state.tag,
3742 index,
3743 length;
3744
3745 for (index = 0, length = object.length; index < length; index += 1) {
3746 // Write only valid elements.
3747 if (writeNode(state, level, object[index], false, false)) {
3748 if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
3749 _result += state.dump;
3750 }
3751 }
3752
3753 state.tag = _tag;
3754 state.dump = '[' + _result + ']';
3755}
3756
3757function writeBlockSequence(state, level, object, compact) {
3758 var _result = '',
3759 _tag = state.tag,
3760 index,
3761 length;
3762
3763 for (index = 0, length = object.length; index < length; index += 1) {
3764 // Write only valid elements.
3765 if (writeNode(state, level + 1, object[index], true, true)) {
3766 if (!compact || index !== 0) {
3767 _result += generateNextLine(state, level);
3768 }
3769
3770 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3771 _result += '-';
3772 } else {
3773 _result += '- ';
3774 }
3775
3776 _result += state.dump;
3777 }
3778 }
3779
3780 state.tag = _tag;
3781 state.dump = _result || '[]'; // Empty sequence if no valid values.
3782}
3783
3784function writeFlowMapping(state, level, object) {
3785 var _result = '',
3786 _tag = state.tag,
3787 objectKeyList = Object.keys(object),
3788 index,
3789 length,
3790 objectKey,
3791 objectValue,
3792 pairBuffer;
3793
3794 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
3795
3796 pairBuffer = '';
3797 if (index !== 0) pairBuffer += ', ';
3798
3799 if (state.condenseFlow) pairBuffer += '"';
3800
3801 objectKey = objectKeyList[index];
3802 objectValue = object[objectKey];
3803
3804 if (!writeNode(state, level, objectKey, false, false)) {
3805 continue; // Skip this pair because of invalid key;
3806 }
3807
3808 if (state.dump.length > 1024) pairBuffer += '? ';
3809
3810 pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
3811
3812 if (!writeNode(state, level, objectValue, false, false)) {
3813 continue; // Skip this pair because of invalid value.
3814 }
3815
3816 pairBuffer += state.dump;
3817
3818 // Both key and value are valid.
3819 _result += pairBuffer;
3820 }
3821
3822 state.tag = _tag;
3823 state.dump = '{' + _result + '}';
3824}
3825
3826function writeBlockMapping(state, level, object, compact) {
3827 var _result = '',
3828 _tag = state.tag,
3829 objectKeyList = Object.keys(object),
3830 index,
3831 length,
3832 objectKey,
3833 objectValue,
3834 explicitPair,
3835 pairBuffer;
3836
3837 // Allow sorting keys so that the output file is deterministic
3838 if (state.sortKeys === true) {
3839 // Default sorting
3840 objectKeyList.sort();
3841 } else if (typeof state.sortKeys === 'function') {
3842 // Custom sort function
3843 objectKeyList.sort(state.sortKeys);
3844 } else if (state.sortKeys) {
3845 // Something is wrong
3846 throw new YAMLException('sortKeys must be a boolean or a function');
3847 }
3848
3849 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
3850 pairBuffer = '';
3851
3852 if (!compact || index !== 0) {
3853 pairBuffer += generateNextLine(state, level);
3854 }
3855
3856 objectKey = objectKeyList[index];
3857 objectValue = object[objectKey];
3858
3859 if (!writeNode(state, level + 1, objectKey, true, true, true)) {
3860 continue; // Skip this pair because of invalid key.
3861 }
3862
3863 explicitPair = (state.tag !== null && state.tag !== '?') ||
3864 (state.dump && state.dump.length > 1024);
3865
3866 if (explicitPair) {
3867 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3868 pairBuffer += '?';
3869 } else {
3870 pairBuffer += '? ';
3871 }
3872 }
3873
3874 pairBuffer += state.dump;
3875
3876 if (explicitPair) {
3877 pairBuffer += generateNextLine(state, level);
3878 }
3879
3880 if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
3881 continue; // Skip this pair because of invalid value.
3882 }
3883
3884 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3885 pairBuffer += ':';
3886 } else {
3887 pairBuffer += ': ';
3888 }
3889
3890 pairBuffer += state.dump;
3891
3892 // Both key and value are valid.
3893 _result += pairBuffer;
3894 }
3895
3896 state.tag = _tag;
3897 state.dump = _result || '{}'; // Empty mapping if no valid pairs.
3898}
3899
3900function detectType(state, object, explicit) {
3901 var _result, typeList, index, length, type, style;
3902
3903 typeList = explicit ? state.explicitTypes : state.implicitTypes;
3904
3905 for (index = 0, length = typeList.length; index < length; index += 1) {
3906 type = typeList[index];
3907
3908 if ((type.instanceOf || type.predicate) &&
3909 (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
3910 (!type.predicate || type.predicate(object))) {
3911
3912 state.tag = explicit ? type.tag : '?';
3913
3914 if (type.represent) {
3915 style = state.styleMap[type.tag] || type.defaultStyle;
3916
3917 if (_toString.call(type.represent) === '[object Function]') {
3918 _result = type.represent(object, style);
3919 } else if (_hasOwnProperty.call(type.represent, style)) {
3920 _result = type.represent[style](object, style);
3921 } else {
3922 throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
3923 }
3924
3925 state.dump = _result;
3926 }
3927
3928 return true;
3929 }
3930 }
3931
3932 return false;
3933}
3934
3935// Serializes `object` and writes it to global `result`.
3936// Returns true on success, or false on invalid object.
3937//
3938function writeNode(state, level, object, block, compact, iskey) {
3939 state.tag = null;
3940 state.dump = object;
3941
3942 if (!detectType(state, object, false)) {
3943 detectType(state, object, true);
3944 }
3945
3946 var type = _toString.call(state.dump);
3947
3948 if (block) {
3949 block = (state.flowLevel < 0 || state.flowLevel > level);
3950 }
3951
3952 var objectOrArray = type === '[object Object]' || type === '[object Array]',
3953 duplicateIndex,
3954 duplicate;
3955
3956 if (objectOrArray) {
3957 duplicateIndex = state.duplicates.indexOf(object);
3958 duplicate = duplicateIndex !== -1;
3959 }
3960
3961 if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
3962 compact = false;
3963 }
3964
3965 if (duplicate && state.usedDuplicates[duplicateIndex]) {
3966 state.dump = '*ref_' + duplicateIndex;
3967 } else {
3968 if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
3969 state.usedDuplicates[duplicateIndex] = true;
3970 }
3971 if (type === '[object Object]') {
3972 if (block && (Object.keys(state.dump).length !== 0)) {
3973 writeBlockMapping(state, level, state.dump, compact);
3974 if (duplicate) {
3975 state.dump = '&ref_' + duplicateIndex + state.dump;
3976 }
3977 } else {
3978 writeFlowMapping(state, level, state.dump);
3979 if (duplicate) {
3980 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
3981 }
3982 }
3983 } else if (type === '[object Array]') {
3984 var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;
3985 if (block && (state.dump.length !== 0)) {
3986 writeBlockSequence(state, arrayLevel, state.dump, compact);
3987 if (duplicate) {
3988 state.dump = '&ref_' + duplicateIndex + state.dump;
3989 }
3990 } else {
3991 writeFlowSequence(state, arrayLevel, state.dump);
3992 if (duplicate) {
3993 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
3994 }
3995 }
3996 } else if (type === '[object String]') {
3997 if (state.tag !== '?') {
3998 writeScalar(state, state.dump, level, iskey);
3999 }
4000 } else {
4001 if (state.skipInvalid) return false;
4002 throw new YAMLException('unacceptable kind of an object to dump ' + type);
4003 }
4004
4005 if (state.tag !== null && state.tag !== '?') {
4006 state.dump = '!<' + state.tag + '> ' + state.dump;
4007 }
4008 }
4009
4010 return true;
4011}
4012
4013function getDuplicateReferences(object, state) {
4014 var objects = [],
4015 duplicatesIndexes = [],
4016 index,
4017 length;
4018
4019 inspectNode(object, objects, duplicatesIndexes);
4020
4021 for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
4022 state.duplicates.push(objects[duplicatesIndexes[index]]);
4023 }
4024 state.usedDuplicates = new Array(length);
4025}
4026
4027function inspectNode(object, objects, duplicatesIndexes) {
4028 var objectKeyList,
4029 index,
4030 length;
4031
4032 if (object !== null && typeof object === 'object') {
4033 index = objects.indexOf(object);
4034 if (index !== -1) {
4035 if (duplicatesIndexes.indexOf(index) === -1) {
4036 duplicatesIndexes.push(index);
4037 }
4038 } else {
4039 objects.push(object);
4040
4041 if (Array.isArray(object)) {
4042 for (index = 0, length = object.length; index < length; index += 1) {
4043 inspectNode(object[index], objects, duplicatesIndexes);
4044 }
4045 } else {
4046 objectKeyList = Object.keys(object);
4047
4048 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
4049 inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
4050 }
4051 }
4052 }
4053 }
4054}
4055
4056function dump(input, options) {
4057 options = options || {};
4058
4059 var state = new State(options);
4060
4061 if (!state.noRefs) getDuplicateReferences(input, state);
4062
4063 if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
4064
4065 return '';
4066}
4067
4068function safeDump(input, options) {
4069 return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
4070}
4071
4072dumper$1.dump = dump;
4073dumper$1.safeDump = safeDump;
4074
4075var loader = loader$1;
4076var dumper = dumper$1;
4077
4078
4079function deprecated(name) {
4080 return function () {
4081 throw new Error('Function ' + name + ' is deprecated and cannot be used.');
4082 };
4083}
4084
4085
4086jsYaml$1.Type = type;
4087jsYaml$1.Schema = schema;
4088jsYaml$1.FAILSAFE_SCHEMA = failsafe;
4089jsYaml$1.JSON_SCHEMA = json;
4090jsYaml$1.CORE_SCHEMA = core;
4091jsYaml$1.DEFAULT_SAFE_SCHEMA = default_safe;
4092jsYaml$1.DEFAULT_FULL_SCHEMA = default_full;
4093jsYaml$1.load = loader.load;
4094jsYaml$1.loadAll = loader.loadAll;
4095jsYaml$1.safeLoad = loader.safeLoad;
4096jsYaml$1.safeLoadAll = loader.safeLoadAll;
4097jsYaml$1.dump = dumper.dump;
4098jsYaml$1.safeDump = dumper.safeDump;
4099jsYaml$1.YAMLException = exception;
4100
4101// Deprecated schema names from JS-YAML 2.0.x
4102jsYaml$1.MINIMAL_SCHEMA = failsafe;
4103jsYaml$1.SAFE_SCHEMA = default_safe;
4104jsYaml$1.DEFAULT_SCHEMA = default_full;
4105
4106// Deprecated functions from JS-YAML 1.x.x
4107jsYaml$1.scan = deprecated('scan');
4108jsYaml$1.parse = deprecated('parse');
4109jsYaml$1.compose = deprecated('compose');
4110jsYaml$1.addConstructor = deprecated('addConstructor');
4111
4112var yaml$1 = jsYaml$1;
4113
4114
4115var jsYaml = yaml$1;
4116
4117var callsites$1 = () => {
4118 const _ = Error.prepareStackTrace;
4119 Error.prepareStackTrace = (_, stack) => stack;
4120 const stack = new Error().stack.slice(1);
4121 Error.prepareStackTrace = _;
4122 return stack;
4123};
4124
4125const callsites = callsites$1;
4126
4127var callerCallsite$1 = () => {
4128 const c = callsites();
4129 let caller;
4130
4131 for (let i = 0; i < c.length; i++) {
4132 const hasReceiver = c[i].getTypeName() !== null;
4133
4134 if (hasReceiver) {
4135 caller = i;
4136 break;
4137 }
4138 }
4139
4140 return c[caller];
4141};
4142
4143const callerCallsite = callerCallsite$1;
4144
4145var callerPath$1 = () => callerCallsite().getFileName();
4146
4147const path$3 = path__default['default'];
4148const resolveFrom = require$$1__default['default'];
4149const callerPath = callerPath$1;
4150
4151var importFresh$1 = moduleId => {
4152 if (typeof moduleId !== 'string') {
4153 throw new TypeError('Expected a string');
4154 }
4155
4156 const filePath = resolveFrom(path$3.dirname(callerPath()), moduleId);
4157
4158 // Delete itself from module parent
4159 if (require.cache[filePath] && require.cache[filePath].parent) {
4160 let i = require.cache[filePath].parent.children.length;
4161
4162 while (i--) {
4163 if (require.cache[filePath].parent.children[i].id === filePath) {
4164 require.cache[filePath].parent.children.splice(i, 1);
4165 }
4166 }
4167 }
4168
4169 // Delete module from cache
4170 delete require.cache[filePath];
4171
4172 // Return fresh module
4173 return commonjsRequire(filePath);
4174};
4175
4176const parseJson = require$$0__default['default'];
4177const yaml = jsYaml;
4178const importFresh = importFresh$1;
4179
4180function loadJs(filepath ) {
4181 const result = importFresh(filepath);
4182 return result;
4183}
4184
4185function loadJson(filepath , content ) {
4186 try {
4187 return parseJson(content);
4188 } catch (err) {
4189 err.message = `JSON Error in ${filepath}:\n${err.message}`;
4190 throw err;
4191 }
4192}
4193
4194function loadYaml(filepath , content ) {
4195 return yaml.safeLoad(content, { filename: filepath });
4196}
4197
4198var loaders$2 = {
4199 loadJs,
4200 loadJson,
4201 loadYaml,
4202};
4203
4204const fs$2 = fs__default['default'];
4205
4206
4207
4208
4209
4210function readFile$1(filepath , options ) {
4211 options = options || {};
4212 const throwNotFound = options.throwNotFound || false;
4213
4214 return new Promise((resolve, reject) => {
4215 fs$2.readFile(filepath, 'utf8', (err, content) => {
4216 if (err && err.code === 'ENOENT' && !throwNotFound) {
4217 return resolve(null);
4218 }
4219 if (err) return reject(err);
4220 resolve(content);
4221 });
4222 });
4223}
4224
4225readFile$1.sync = function readFileSync(
4226 filepath ,
4227 options
4228) {
4229 options = options || {};
4230 const throwNotFound = options.throwNotFound || false;
4231
4232 try {
4233 return fs$2.readFileSync(filepath, 'utf8');
4234 } catch (err) {
4235 if (err.code === 'ENOENT' && !throwNotFound) {
4236 return null;
4237 }
4238 throw err;
4239 }
4240};
4241
4242var readFile_1 = readFile$1;
4243
4244function cacheWrapper$1 (cache , key , fn ) {
4245 if (!cache) {
4246 return fn();
4247 }
4248
4249 const cached = cache.get(key);
4250 if (cached !== undefined) {
4251 return cached;
4252 }
4253
4254 const result = fn();
4255 cache.set(key, result);
4256 return result;
4257}
4258
4259var cacheWrapper_1 = cacheWrapper$1;
4260
4261/*!
4262 * is-directory <https://github.com/jonschlinkert/is-directory>
4263 *
4264 * Copyright (c) 2014-2015, Jon Schlinkert.
4265 * Licensed under the MIT License.
4266 */
4267
4268var fs$1 = fs__default['default'];
4269
4270/**
4271 * async
4272 */
4273
4274function isDirectory$1(filepath, cb) {
4275 if (typeof cb !== 'function') {
4276 throw new Error('expected a callback function');
4277 }
4278
4279 if (typeof filepath !== 'string') {
4280 cb(new Error('expected filepath to be a string'));
4281 return;
4282 }
4283
4284 fs$1.stat(filepath, function(err, stats) {
4285 if (err) {
4286 if (err.code === 'ENOENT') {
4287 cb(null, false);
4288 return;
4289 }
4290 cb(err);
4291 return;
4292 }
4293 cb(null, stats.isDirectory());
4294 });
4295}
4296
4297/**
4298 * sync
4299 */
4300
4301isDirectory$1.sync = function isDirectorySync(filepath) {
4302 if (typeof filepath !== 'string') {
4303 throw new Error('expected filepath to be a string');
4304 }
4305
4306 try {
4307 var stat = fs$1.statSync(filepath);
4308 return stat.isDirectory();
4309 } catch (err) {
4310 if (err.code === 'ENOENT') {
4311 return false;
4312 } else {
4313 throw err;
4314 }
4315 }
4316 return false;
4317};
4318
4319/**
4320 * Expose `isDirectory`
4321 */
4322
4323var isDirectory_1 = isDirectory$1;
4324
4325const path$2 = path__default['default'];
4326const isDirectory = isDirectory_1;
4327
4328function getDirectory$1(filepath ) {
4329 return new Promise((resolve, reject) => {
4330 return isDirectory(filepath, (err, filepathIsDirectory) => {
4331 if (err) {
4332 return reject(err);
4333 }
4334 return resolve(filepathIsDirectory ? filepath : path$2.dirname(filepath));
4335 });
4336 });
4337}
4338
4339getDirectory$1.sync = function getDirectorySync(filepath ) {
4340 return isDirectory.sync(filepath) ? filepath : path$2.dirname(filepath);
4341};
4342
4343var getDirectory_1 = getDirectory$1;
4344
4345// Resolves property names or property paths defined with period-delimited
4346// strings or arrays of strings. Property names that are found on the source
4347// object are used directly (even if they include a period).
4348// Nested property names that include periods, within a path, are only
4349// understood in array paths.
4350function getPropertyByPath$1(source , path ) {
4351 if (typeof path === 'string' && source.hasOwnProperty(path)) {
4352 return source[path];
4353 }
4354
4355 const parsedPath = typeof path === 'string' ? path.split('.') : path;
4356 return parsedPath.reduce((previous, key) => {
4357 if (previous === undefined) {
4358 return previous;
4359 }
4360 return previous[key];
4361 }, source);
4362}
4363
4364var getPropertyByPath_1 = getPropertyByPath$1;
4365
4366const path$1 = path__default['default'];
4367const loaders$1 = loaders$2;
4368const readFile = readFile_1;
4369const cacheWrapper = cacheWrapper_1;
4370const getDirectory = getDirectory_1;
4371const getPropertyByPath = getPropertyByPath_1;
4372
4373const MODE_SYNC = 'sync';
4374
4375// An object value represents a config object.
4376// null represents that the loader did not find anything relevant.
4377// undefined represents that the loader found something relevant
4378// but it was empty.
4379
4380
4381class Explorer {
4382
4383
4384
4385
4386
4387
4388 constructor(options ) {
4389 this.loadCache = options.cache ? new Map() : null;
4390 this.loadSyncCache = options.cache ? new Map() : null;
4391 this.searchCache = options.cache ? new Map() : null;
4392 this.searchSyncCache = options.cache ? new Map() : null;
4393 this.config = options;
4394 this.validateConfig();
4395 }
4396
4397 clearLoadCache() {
4398 if (this.loadCache) {
4399 this.loadCache.clear();
4400 }
4401 if (this.loadSyncCache) {
4402 this.loadSyncCache.clear();
4403 }
4404 }
4405
4406 clearSearchCache() {
4407 if (this.searchCache) {
4408 this.searchCache.clear();
4409 }
4410 if (this.searchSyncCache) {
4411 this.searchSyncCache.clear();
4412 }
4413 }
4414
4415 clearCaches() {
4416 this.clearLoadCache();
4417 this.clearSearchCache();
4418 }
4419
4420 validateConfig() {
4421 const config = this.config;
4422
4423 config.searchPlaces.forEach(place => {
4424 const loaderKey = path$1.extname(place) || 'noExt';
4425 const loader = config.loaders[loaderKey];
4426 if (!loader) {
4427 throw new Error(
4428 `No loader specified for ${getExtensionDescription(
4429 place
4430 )}, so searchPlaces item "${place}" is invalid`
4431 );
4432 }
4433 });
4434 }
4435
4436 search(searchFrom ) {
4437 searchFrom = searchFrom || process.cwd();
4438 return getDirectory(searchFrom).then(dir => {
4439 return this.searchFromDirectory(dir);
4440 });
4441 }
4442
4443 searchFromDirectory(dir ) {
4444 const absoluteDir = path$1.resolve(process.cwd(), dir);
4445 const run = () => {
4446 return this.searchDirectory(absoluteDir).then(result => {
4447 const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
4448 if (nextDir) {
4449 return this.searchFromDirectory(nextDir);
4450 }
4451 return this.config.transform(result);
4452 });
4453 };
4454
4455 if (this.searchCache) {
4456 return cacheWrapper(this.searchCache, absoluteDir, run);
4457 }
4458 return run();
4459 }
4460
4461 searchSync(searchFrom ) {
4462 searchFrom = searchFrom || process.cwd();
4463 const dir = getDirectory.sync(searchFrom);
4464 return this.searchFromDirectorySync(dir);
4465 }
4466
4467 searchFromDirectorySync(dir ) {
4468 const absoluteDir = path$1.resolve(process.cwd(), dir);
4469 const run = () => {
4470 const result = this.searchDirectorySync(absoluteDir);
4471 const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
4472 if (nextDir) {
4473 return this.searchFromDirectorySync(nextDir);
4474 }
4475 return this.config.transform(result);
4476 };
4477
4478 if (this.searchSyncCache) {
4479 return cacheWrapper(this.searchSyncCache, absoluteDir, run);
4480 }
4481 return run();
4482 }
4483
4484 searchDirectory(dir ) {
4485 return this.config.searchPlaces.reduce((prevResultPromise, place) => {
4486 return prevResultPromise.then(prevResult => {
4487 if (this.shouldSearchStopWithResult(prevResult)) {
4488 return prevResult;
4489 }
4490 return this.loadSearchPlace(dir, place);
4491 });
4492 }, Promise.resolve(null));
4493 }
4494
4495 searchDirectorySync(dir ) {
4496 let result = null;
4497 for (const place of this.config.searchPlaces) {
4498 result = this.loadSearchPlaceSync(dir, place);
4499 if (this.shouldSearchStopWithResult(result)) break;
4500 }
4501 return result;
4502 }
4503
4504 shouldSearchStopWithResult(result ) {
4505 if (result === null) return false;
4506 if (result.isEmpty && this.config.ignoreEmptySearchPlaces) return false;
4507 return true;
4508 }
4509
4510 loadSearchPlace(dir , place ) {
4511 const filepath = path$1.join(dir, place);
4512 return readFile(filepath).then(content => {
4513 return this.createCosmiconfigResult(filepath, content);
4514 });
4515 }
4516
4517 loadSearchPlaceSync(dir , place ) {
4518 const filepath = path$1.join(dir, place);
4519 const content = readFile.sync(filepath);
4520 return this.createCosmiconfigResultSync(filepath, content);
4521 }
4522
4523 nextDirectoryToSearch(
4524 currentDir ,
4525 currentResult
4526 ) {
4527 if (this.shouldSearchStopWithResult(currentResult)) {
4528 return null;
4529 }
4530 const nextDir = nextDirUp(currentDir);
4531 if (nextDir === currentDir || currentDir === this.config.stopDir) {
4532 return null;
4533 }
4534 return nextDir;
4535 }
4536
4537 loadPackageProp(filepath , content ) {
4538 const parsedContent = loaders$1.loadJson(filepath, content);
4539 const packagePropValue = getPropertyByPath(
4540 parsedContent,
4541 this.config.packageProp
4542 );
4543 return packagePropValue || null;
4544 }
4545
4546 getLoaderEntryForFile(filepath ) {
4547 if (path$1.basename(filepath) === 'package.json') {
4548 const loader = this.loadPackageProp.bind(this);
4549 return { sync: loader, async: loader };
4550 }
4551
4552 const loaderKey = path$1.extname(filepath) || 'noExt';
4553 return this.config.loaders[loaderKey] || {};
4554 }
4555
4556 getSyncLoaderForFile(filepath ) {
4557 const entry = this.getLoaderEntryForFile(filepath);
4558 if (!entry.sync) {
4559 throw new Error(
4560 `No sync loader specified for ${getExtensionDescription(filepath)}`
4561 );
4562 }
4563 return entry.sync;
4564 }
4565
4566 getAsyncLoaderForFile(filepath ) {
4567 const entry = this.getLoaderEntryForFile(filepath);
4568 const loader = entry.async || entry.sync;
4569 if (!loader) {
4570 throw new Error(
4571 `No async loader specified for ${getExtensionDescription(filepath)}`
4572 );
4573 }
4574 return loader;
4575 }
4576
4577 loadFileContent(
4578 mode ,
4579 filepath ,
4580 content
4581 ) {
4582 if (content === null) {
4583 return null;
4584 }
4585 if (content.trim() === '') {
4586 return undefined;
4587 }
4588 const loader =
4589 mode === MODE_SYNC
4590 ? this.getSyncLoaderForFile(filepath)
4591 : this.getAsyncLoaderForFile(filepath);
4592 return loader(filepath, content);
4593 }
4594
4595 loadedContentToCosmiconfigResult(
4596 filepath ,
4597 loadedContent
4598 ) {
4599 if (loadedContent === null) {
4600 return null;
4601 }
4602 if (loadedContent === undefined) {
4603 return { filepath, config: undefined, isEmpty: true };
4604 }
4605 return { config: loadedContent, filepath };
4606 }
4607
4608 createCosmiconfigResult(
4609 filepath ,
4610 content
4611 ) {
4612 return Promise.resolve()
4613 .then(() => {
4614 return this.loadFileContent('async', filepath, content);
4615 })
4616 .then(loaderResult => {
4617 return this.loadedContentToCosmiconfigResult(filepath, loaderResult);
4618 });
4619 }
4620
4621 createCosmiconfigResultSync(
4622 filepath ,
4623 content
4624 ) {
4625 const loaderResult = this.loadFileContent('sync', filepath, content);
4626 return this.loadedContentToCosmiconfigResult(filepath, loaderResult);
4627 }
4628
4629 validateFilePath(filepath ) {
4630 if (!filepath) {
4631 throw new Error('load and loadSync must pass a non-empty string');
4632 }
4633 }
4634
4635 load(filepath ) {
4636 return Promise.resolve().then(() => {
4637 this.validateFilePath(filepath);
4638 const absoluteFilePath = path$1.resolve(process.cwd(), filepath);
4639 return cacheWrapper(this.loadCache, absoluteFilePath, () => {
4640 return readFile(absoluteFilePath, { throwNotFound: true })
4641 .then(content => {
4642 return this.createCosmiconfigResult(absoluteFilePath, content);
4643 })
4644 .then(this.config.transform);
4645 });
4646 });
4647 }
4648
4649 loadSync(filepath ) {
4650 this.validateFilePath(filepath);
4651 const absoluteFilePath = path$1.resolve(process.cwd(), filepath);
4652 return cacheWrapper(this.loadSyncCache, absoluteFilePath, () => {
4653 const content = readFile.sync(absoluteFilePath, { throwNotFound: true });
4654 const result = this.createCosmiconfigResultSync(
4655 absoluteFilePath,
4656 content
4657 );
4658 return this.config.transform(result);
4659 });
4660 }
4661}
4662
4663var createExplorer$1 = function createExplorer(options ) {
4664 const explorer = new Explorer(options);
4665
4666 return {
4667 search: explorer.search.bind(explorer),
4668 searchSync: explorer.searchSync.bind(explorer),
4669 load: explorer.load.bind(explorer),
4670 loadSync: explorer.loadSync.bind(explorer),
4671 clearLoadCache: explorer.clearLoadCache.bind(explorer),
4672 clearSearchCache: explorer.clearSearchCache.bind(explorer),
4673 clearCaches: explorer.clearCaches.bind(explorer),
4674 };
4675};
4676
4677function nextDirUp(dir ) {
4678 return path$1.dirname(dir);
4679}
4680
4681function getExtensionDescription(filepath ) {
4682 const ext = path$1.extname(filepath);
4683 return ext ? `extension "${ext}"` : 'files without extensions';
4684}
4685
4686const os = require$$0__default$1['default'];
4687const createExplorer = createExplorer$1;
4688const loaders = loaders$2;
4689
4690var dist = cosmiconfig;
4691
4692function cosmiconfig(
4693 moduleName ,
4694 options
4695
4696
4697
4698
4699
4700
4701
4702
4703) {
4704 options = options || {};
4705 const defaults = {
4706 packageProp: moduleName,
4707 searchPlaces: [
4708 'package.json',
4709 `.${moduleName}rc`,
4710 `.${moduleName}rc.json`,
4711 `.${moduleName}rc.yaml`,
4712 `.${moduleName}rc.yml`,
4713 `.${moduleName}rc.js`,
4714 `${moduleName}.config.js`,
4715 ],
4716 ignoreEmptySearchPlaces: true,
4717 stopDir: os.homedir(),
4718 cache: true,
4719 transform: identity,
4720 };
4721 const normalizedOptions = Object.assign(
4722 {},
4723 defaults,
4724 options,
4725 {
4726 loaders: normalizeLoaders(options.loaders),
4727 }
4728 );
4729
4730 return createExplorer(normalizedOptions);
4731}
4732
4733cosmiconfig.loadJs = loaders.loadJs;
4734cosmiconfig.loadJson = loaders.loadJson;
4735cosmiconfig.loadYaml = loaders.loadYaml;
4736
4737function normalizeLoaders(rawLoaders ) {
4738 const defaults = {
4739 '.js': { sync: loaders.loadJs, async: loaders.loadJs },
4740 '.json': { sync: loaders.loadJson, async: loaders.loadJson },
4741 '.yaml': { sync: loaders.loadYaml, async: loaders.loadYaml },
4742 '.yml': { sync: loaders.loadYaml, async: loaders.loadYaml },
4743 noExt: { sync: loaders.loadYaml, async: loaders.loadYaml },
4744 };
4745
4746 if (!rawLoaders) {
4747 return defaults;
4748 }
4749
4750 return Object.keys(rawLoaders).reduce((result, ext) => {
4751 const entry = rawLoaders && rawLoaders[ext];
4752 if (typeof entry === 'function') {
4753 result[ext] = { sync: entry, async: entry };
4754 } else {
4755 result[ext] = entry;
4756 }
4757 return result;
4758 }, defaults);
4759}
4760
4761function identity(x) {
4762 return x;
4763}
4764
4765/* eslint-disable complexity */
4766
4767const testExpression = /(^|\/|\\)(?:((?:u[0-9a-f]{4,6},?)+)-)(.+)\.svg$/i;
4768
4769function fileSorter(fileA, fileB) {
4770 const hasUnicodeA = testExpression.test(fileA);
4771 const hasUnicodeB = testExpression.test(fileB);
4772
4773 if (hasUnicodeA == hasUnicodeB) {
4774 // just compare alphabetically
4775 const fileA_ = fileA.substr(0, fileA.lastIndexOf('.'));
4776 const fileB_ = fileB.substr(0, fileB.lastIndexOf('.'));
4777 return fileA_ < fileB_ ? -1 : 1;
4778 } else {
4779 // map true to 0, because we want it to be first
4780 return (hasUnicodeA ? 0 : 1) - (hasUnicodeB ? 0 : 1);
4781 }
4782}
4783
4784var filesorter = fileSorter;
4785
4786var callBind$6 = {exports: {}};
4787
4788/* eslint no-invalid-this: 1 */
4789
4790var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
4791var slice$1 = Array.prototype.slice;
4792var toStr$7 = Object.prototype.toString;
4793var funcType = '[object Function]';
4794
4795var implementation$8 = function bind(that) {
4796 var target = this;
4797 if (typeof target !== 'function' || toStr$7.call(target) !== funcType) {
4798 throw new TypeError(ERROR_MESSAGE + target);
4799 }
4800 var args = slice$1.call(arguments, 1);
4801
4802 var bound;
4803 var binder = function () {
4804 if (this instanceof bound) {
4805 var result = target.apply(
4806 this,
4807 args.concat(slice$1.call(arguments))
4808 );
4809 if (Object(result) === result) {
4810 return result;
4811 }
4812 return this;
4813 } else {
4814 return target.apply(
4815 that,
4816 args.concat(slice$1.call(arguments))
4817 );
4818 }
4819 };
4820
4821 var boundLength = Math.max(0, target.length - args.length);
4822 var boundArgs = [];
4823 for (var i = 0; i < boundLength; i++) {
4824 boundArgs.push('$' + i);
4825 }
4826
4827 bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
4828
4829 if (target.prototype) {
4830 var Empty = function Empty() {};
4831 Empty.prototype = target.prototype;
4832 bound.prototype = new Empty();
4833 Empty.prototype = null;
4834 }
4835
4836 return bound;
4837};
4838
4839var implementation$7 = implementation$8;
4840
4841var functionBind = Function.prototype.bind || implementation$7;
4842
4843/* eslint complexity: [2, 18], max-statements: [2, 33] */
4844var shams = function hasSymbols() {
4845 if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
4846 if (typeof Symbol.iterator === 'symbol') { return true; }
4847
4848 var obj = {};
4849 var sym = Symbol('test');
4850 var symObj = Object(sym);
4851 if (typeof sym === 'string') { return false; }
4852
4853 if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
4854 if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
4855
4856 // temp disabled per https://github.com/ljharb/object.assign/issues/17
4857 // if (sym instanceof Symbol) { return false; }
4858 // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
4859 // if (!(symObj instanceof Symbol)) { return false; }
4860
4861 // if (typeof Symbol.prototype.toString !== 'function') { return false; }
4862 // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
4863
4864 var symVal = 42;
4865 obj[sym] = symVal;
4866 for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
4867 if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
4868
4869 if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
4870
4871 var syms = Object.getOwnPropertySymbols(obj);
4872 if (syms.length !== 1 || syms[0] !== sym) { return false; }
4873
4874 if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
4875
4876 if (typeof Object.getOwnPropertyDescriptor === 'function') {
4877 var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
4878 if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
4879 }
4880
4881 return true;
4882};
4883
4884var origSymbol = typeof Symbol !== 'undefined' && Symbol;
4885var hasSymbolSham = shams;
4886
4887var hasSymbols$4 = function hasNativeSymbols() {
4888 if (typeof origSymbol !== 'function') { return false; }
4889 if (typeof Symbol !== 'function') { return false; }
4890 if (typeof origSymbol('foo') !== 'symbol') { return false; }
4891 if (typeof Symbol('bar') !== 'symbol') { return false; }
4892
4893 return hasSymbolSham();
4894};
4895
4896var bind$1 = functionBind;
4897
4898var src = bind$1.call(Function.call, Object.prototype.hasOwnProperty);
4899
4900var undefined$1;
4901
4902var $SyntaxError = SyntaxError;
4903var $Function = Function;
4904var $TypeError$3 = TypeError;
4905
4906// eslint-disable-next-line consistent-return
4907var getEvalledConstructor = function (expressionSyntax) {
4908 try {
4909 return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
4910 } catch (e) {}
4911};
4912
4913var $gOPD = Object.getOwnPropertyDescriptor;
4914if ($gOPD) {
4915 try {
4916 $gOPD({}, '');
4917 } catch (e) {
4918 $gOPD = null; // this is IE 8, which has a broken gOPD
4919 }
4920}
4921
4922var throwTypeError = function () {
4923 throw new $TypeError$3();
4924};
4925var ThrowTypeError = $gOPD
4926 ? (function () {
4927 try {
4928 // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
4929 arguments.callee; // IE 8 does not throw here
4930 return throwTypeError;
4931 } catch (calleeThrows) {
4932 try {
4933 // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
4934 return $gOPD(arguments, 'callee').get;
4935 } catch (gOPDthrows) {
4936 return throwTypeError;
4937 }
4938 }
4939 }())
4940 : throwTypeError;
4941
4942var hasSymbols$3 = hasSymbols$4();
4943
4944var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
4945
4946var needsEval = {};
4947
4948var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array);
4949
4950var INTRINSICS = {
4951 '%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError,
4952 '%Array%': Array,
4953 '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
4954 '%ArrayIteratorPrototype%': hasSymbols$3 ? getProto([][Symbol.iterator]()) : undefined$1,
4955 '%AsyncFromSyncIteratorPrototype%': undefined$1,
4956 '%AsyncFunction%': needsEval,
4957 '%AsyncGenerator%': needsEval,
4958 '%AsyncGeneratorFunction%': needsEval,
4959 '%AsyncIteratorPrototype%': needsEval,
4960 '%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
4961 '%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt,
4962 '%Boolean%': Boolean,
4963 '%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
4964 '%Date%': Date,
4965 '%decodeURI%': decodeURI,
4966 '%decodeURIComponent%': decodeURIComponent,
4967 '%encodeURI%': encodeURI,
4968 '%encodeURIComponent%': encodeURIComponent,
4969 '%Error%': Error,
4970 '%eval%': eval, // eslint-disable-line no-eval
4971 '%EvalError%': EvalError,
4972 '%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
4973 '%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
4974 '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry,
4975 '%Function%': $Function,
4976 '%GeneratorFunction%': needsEval,
4977 '%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
4978 '%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
4979 '%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
4980 '%isFinite%': isFinite,
4981 '%isNaN%': isNaN,
4982 '%IteratorPrototype%': hasSymbols$3 ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
4983 '%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
4984 '%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
4985 '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols$3 ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
4986 '%Math%': Math,
4987 '%Number%': Number,
4988 '%Object%': Object,
4989 '%parseFloat%': parseFloat,
4990 '%parseInt%': parseInt,
4991 '%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
4992 '%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
4993 '%RangeError%': RangeError,
4994 '%ReferenceError%': ReferenceError,
4995 '%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
4996 '%RegExp%': RegExp,
4997 '%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
4998 '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols$3 ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
4999 '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
5000 '%String%': String,
5001 '%StringIteratorPrototype%': hasSymbols$3 ? getProto(''[Symbol.iterator]()) : undefined$1,
5002 '%Symbol%': hasSymbols$3 ? Symbol : undefined$1,
5003 '%SyntaxError%': $SyntaxError,
5004 '%ThrowTypeError%': ThrowTypeError,
5005 '%TypedArray%': TypedArray,
5006 '%TypeError%': $TypeError$3,
5007 '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
5008 '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
5009 '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
5010 '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
5011 '%URIError%': URIError,
5012 '%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
5013 '%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef,
5014 '%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet
5015};
5016
5017var doEval = function doEval(name) {
5018 var value;
5019 if (name === '%AsyncFunction%') {
5020 value = getEvalledConstructor('async function () {}');
5021 } else if (name === '%GeneratorFunction%') {
5022 value = getEvalledConstructor('function* () {}');
5023 } else if (name === '%AsyncGeneratorFunction%') {
5024 value = getEvalledConstructor('async function* () {}');
5025 } else if (name === '%AsyncGenerator%') {
5026 var fn = doEval('%AsyncGeneratorFunction%');
5027 if (fn) {
5028 value = fn.prototype;
5029 }
5030 } else if (name === '%AsyncIteratorPrototype%') {
5031 var gen = doEval('%AsyncGenerator%');
5032 if (gen) {
5033 value = getProto(gen.prototype);
5034 }
5035 }
5036
5037 INTRINSICS[name] = value;
5038
5039 return value;
5040};
5041
5042var LEGACY_ALIASES = {
5043 '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
5044 '%ArrayPrototype%': ['Array', 'prototype'],
5045 '%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
5046 '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
5047 '%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
5048 '%ArrayProto_values%': ['Array', 'prototype', 'values'],
5049 '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
5050 '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
5051 '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
5052 '%BooleanPrototype%': ['Boolean', 'prototype'],
5053 '%DataViewPrototype%': ['DataView', 'prototype'],
5054 '%DatePrototype%': ['Date', 'prototype'],
5055 '%ErrorPrototype%': ['Error', 'prototype'],
5056 '%EvalErrorPrototype%': ['EvalError', 'prototype'],
5057 '%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
5058 '%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
5059 '%FunctionPrototype%': ['Function', 'prototype'],
5060 '%Generator%': ['GeneratorFunction', 'prototype'],
5061 '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
5062 '%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
5063 '%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
5064 '%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
5065 '%JSONParse%': ['JSON', 'parse'],
5066 '%JSONStringify%': ['JSON', 'stringify'],
5067 '%MapPrototype%': ['Map', 'prototype'],
5068 '%NumberPrototype%': ['Number', 'prototype'],
5069 '%ObjectPrototype%': ['Object', 'prototype'],
5070 '%ObjProto_toString%': ['Object', 'prototype', 'toString'],
5071 '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
5072 '%PromisePrototype%': ['Promise', 'prototype'],
5073 '%PromiseProto_then%': ['Promise', 'prototype', 'then'],
5074 '%Promise_all%': ['Promise', 'all'],
5075 '%Promise_reject%': ['Promise', 'reject'],
5076 '%Promise_resolve%': ['Promise', 'resolve'],
5077 '%RangeErrorPrototype%': ['RangeError', 'prototype'],
5078 '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
5079 '%RegExpPrototype%': ['RegExp', 'prototype'],
5080 '%SetPrototype%': ['Set', 'prototype'],
5081 '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
5082 '%StringPrototype%': ['String', 'prototype'],
5083 '%SymbolPrototype%': ['Symbol', 'prototype'],
5084 '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
5085 '%TypedArrayPrototype%': ['TypedArray', 'prototype'],
5086 '%TypeErrorPrototype%': ['TypeError', 'prototype'],
5087 '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
5088 '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
5089 '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
5090 '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
5091 '%URIErrorPrototype%': ['URIError', 'prototype'],
5092 '%WeakMapPrototype%': ['WeakMap', 'prototype'],
5093 '%WeakSetPrototype%': ['WeakSet', 'prototype']
5094};
5095
5096var bind = functionBind;
5097var hasOwn = src;
5098var $concat = bind.call(Function.call, Array.prototype.concat);
5099var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
5100var $replace$1 = bind.call(Function.call, String.prototype.replace);
5101var $strSlice$1 = bind.call(Function.call, String.prototype.slice);
5102
5103/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
5104var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
5105var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
5106var stringToPath = function stringToPath(string) {
5107 var first = $strSlice$1(string, 0, 1);
5108 var last = $strSlice$1(string, -1);
5109 if (first === '%' && last !== '%') {
5110 throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
5111 } else if (last === '%' && first !== '%') {
5112 throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
5113 }
5114 var result = [];
5115 $replace$1(string, rePropName, function (match, number, quote, subString) {
5116 result[result.length] = quote ? $replace$1(subString, reEscapeChar, '$1') : number || match;
5117 });
5118 return result;
5119};
5120/* end adaptation */
5121
5122var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
5123 var intrinsicName = name;
5124 var alias;
5125 if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
5126 alias = LEGACY_ALIASES[intrinsicName];
5127 intrinsicName = '%' + alias[0] + '%';
5128 }
5129
5130 if (hasOwn(INTRINSICS, intrinsicName)) {
5131 var value = INTRINSICS[intrinsicName];
5132 if (value === needsEval) {
5133 value = doEval(intrinsicName);
5134 }
5135 if (typeof value === 'undefined' && !allowMissing) {
5136 throw new $TypeError$3('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
5137 }
5138
5139 return {
5140 alias: alias,
5141 name: intrinsicName,
5142 value: value
5143 };
5144 }
5145
5146 throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
5147};
5148
5149var getIntrinsic = function GetIntrinsic(name, allowMissing) {
5150 if (typeof name !== 'string' || name.length === 0) {
5151 throw new $TypeError$3('intrinsic name must be a non-empty string');
5152 }
5153 if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
5154 throw new $TypeError$3('"allowMissing" argument must be a boolean');
5155 }
5156
5157 var parts = stringToPath(name);
5158 var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
5159
5160 var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
5161 var intrinsicRealName = intrinsic.name;
5162 var value = intrinsic.value;
5163 var skipFurtherCaching = false;
5164
5165 var alias = intrinsic.alias;
5166 if (alias) {
5167 intrinsicBaseName = alias[0];
5168 $spliceApply(parts, $concat([0, 1], alias));
5169 }
5170
5171 for (var i = 1, isOwn = true; i < parts.length; i += 1) {
5172 var part = parts[i];
5173 var first = $strSlice$1(part, 0, 1);
5174 var last = $strSlice$1(part, -1);
5175 if (
5176 (
5177 (first === '"' || first === "'" || first === '`')
5178 || (last === '"' || last === "'" || last === '`')
5179 )
5180 && first !== last
5181 ) {
5182 throw new $SyntaxError('property names with quotes must have matching quotes');
5183 }
5184 if (part === 'constructor' || !isOwn) {
5185 skipFurtherCaching = true;
5186 }
5187
5188 intrinsicBaseName += '.' + part;
5189 intrinsicRealName = '%' + intrinsicBaseName + '%';
5190
5191 if (hasOwn(INTRINSICS, intrinsicRealName)) {
5192 value = INTRINSICS[intrinsicRealName];
5193 } else if (value != null) {
5194 if (!(part in value)) {
5195 if (!allowMissing) {
5196 throw new $TypeError$3('base intrinsic for ' + name + ' exists, but the property is not available.');
5197 }
5198 return void undefined$1;
5199 }
5200 if ($gOPD && (i + 1) >= parts.length) {
5201 var desc = $gOPD(value, part);
5202 isOwn = !!desc;
5203
5204 // By convention, when a data property is converted to an accessor
5205 // property to emulate a data property that does not suffer from
5206 // the override mistake, that accessor's getter is marked with
5207 // an `originalValue` property. Here, when we detect this, we
5208 // uphold the illusion by pretending to see that original data
5209 // property, i.e., returning the value rather than the getter
5210 // itself.
5211 if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
5212 value = desc.get;
5213 } else {
5214 value = value[part];
5215 }
5216 } else {
5217 isOwn = hasOwn(value, part);
5218 value = value[part];
5219 }
5220
5221 if (isOwn && !skipFurtherCaching) {
5222 INTRINSICS[intrinsicRealName] = value;
5223 }
5224 }
5225 }
5226 return value;
5227};
5228
5229(function (module) {
5230
5231var bind = functionBind;
5232var GetIntrinsic = getIntrinsic;
5233
5234var $apply = GetIntrinsic('%Function.prototype.apply%');
5235var $call = GetIntrinsic('%Function.prototype.call%');
5236var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
5237
5238var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
5239var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
5240var $max = GetIntrinsic('%Math.max%');
5241
5242if ($defineProperty) {
5243 try {
5244 $defineProperty({}, 'a', { value: 1 });
5245 } catch (e) {
5246 // IE 8 has a broken defineProperty
5247 $defineProperty = null;
5248 }
5249}
5250
5251module.exports = function callBind(originalFunction) {
5252 var func = $reflectApply(bind, $call, arguments);
5253 if ($gOPD && $defineProperty) {
5254 var desc = $gOPD(func, 'length');
5255 if (desc.configurable) {
5256 // original length, plus the receiver, minus any additional arguments (after the receiver)
5257 $defineProperty(
5258 func,
5259 'length',
5260 { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
5261 );
5262 }
5263 }
5264 return func;
5265};
5266
5267var applyBind = function applyBind() {
5268 return $reflectApply(bind, $apply, arguments);
5269};
5270
5271if ($defineProperty) {
5272 $defineProperty(module.exports, 'apply', { value: applyBind });
5273} else {
5274 module.exports.apply = applyBind;
5275}
5276}(callBind$6));
5277
5278// TODO; semver-major: remove
5279
5280var callBind$5 = callBind$6.exports;
5281
5282var toStr$6 = Object.prototype.toString;
5283
5284var isArguments = function isArguments(value) {
5285 var str = toStr$6.call(value);
5286 var isArgs = str === '[object Arguments]';
5287 if (!isArgs) {
5288 isArgs = str !== '[object Array]' &&
5289 value !== null &&
5290 typeof value === 'object' &&
5291 typeof value.length === 'number' &&
5292 value.length >= 0 &&
5293 toStr$6.call(value.callee) === '[object Function]';
5294 }
5295 return isArgs;
5296};
5297
5298var keysShim$1;
5299if (!Object.keys) {
5300 // modified from https://github.com/es-shims/es5-shim
5301 var has = Object.prototype.hasOwnProperty;
5302 var toStr$5 = Object.prototype.toString;
5303 var isArgs$1 = isArguments; // eslint-disable-line global-require
5304 var isEnumerable = Object.prototype.propertyIsEnumerable;
5305 var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
5306 var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
5307 var dontEnums = [
5308 'toString',
5309 'toLocaleString',
5310 'valueOf',
5311 'hasOwnProperty',
5312 'isPrototypeOf',
5313 'propertyIsEnumerable',
5314 'constructor'
5315 ];
5316 var equalsConstructorPrototype = function (o) {
5317 var ctor = o.constructor;
5318 return ctor && ctor.prototype === o;
5319 };
5320 var excludedKeys = {
5321 $applicationCache: true,
5322 $console: true,
5323 $external: true,
5324 $frame: true,
5325 $frameElement: true,
5326 $frames: true,
5327 $innerHeight: true,
5328 $innerWidth: true,
5329 $onmozfullscreenchange: true,
5330 $onmozfullscreenerror: true,
5331 $outerHeight: true,
5332 $outerWidth: true,
5333 $pageXOffset: true,
5334 $pageYOffset: true,
5335 $parent: true,
5336 $scrollLeft: true,
5337 $scrollTop: true,
5338 $scrollX: true,
5339 $scrollY: true,
5340 $self: true,
5341 $webkitIndexedDB: true,
5342 $webkitStorageInfo: true,
5343 $window: true
5344 };
5345 var hasAutomationEqualityBug = (function () {
5346 /* global window */
5347 if (typeof window === 'undefined') { return false; }
5348 for (var k in window) {
5349 try {
5350 if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
5351 try {
5352 equalsConstructorPrototype(window[k]);
5353 } catch (e) {
5354 return true;
5355 }
5356 }
5357 } catch (e) {
5358 return true;
5359 }
5360 }
5361 return false;
5362 }());
5363 var equalsConstructorPrototypeIfNotBuggy = function (o) {
5364 /* global window */
5365 if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
5366 return equalsConstructorPrototype(o);
5367 }
5368 try {
5369 return equalsConstructorPrototype(o);
5370 } catch (e) {
5371 return false;
5372 }
5373 };
5374
5375 keysShim$1 = function keys(object) {
5376 var isObject = object !== null && typeof object === 'object';
5377 var isFunction = toStr$5.call(object) === '[object Function]';
5378 var isArguments = isArgs$1(object);
5379 var isString = isObject && toStr$5.call(object) === '[object String]';
5380 var theKeys = [];
5381
5382 if (!isObject && !isFunction && !isArguments) {
5383 throw new TypeError('Object.keys called on a non-object');
5384 }
5385
5386 var skipProto = hasProtoEnumBug && isFunction;
5387 if (isString && object.length > 0 && !has.call(object, 0)) {
5388 for (var i = 0; i < object.length; ++i) {
5389 theKeys.push(String(i));
5390 }
5391 }
5392
5393 if (isArguments && object.length > 0) {
5394 for (var j = 0; j < object.length; ++j) {
5395 theKeys.push(String(j));
5396 }
5397 } else {
5398 for (var name in object) {
5399 if (!(skipProto && name === 'prototype') && has.call(object, name)) {
5400 theKeys.push(String(name));
5401 }
5402 }
5403 }
5404
5405 if (hasDontEnumBug) {
5406 var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
5407
5408 for (var k = 0; k < dontEnums.length; ++k) {
5409 if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
5410 theKeys.push(dontEnums[k]);
5411 }
5412 }
5413 }
5414 return theKeys;
5415 };
5416}
5417var implementation$6 = keysShim$1;
5418
5419var slice = Array.prototype.slice;
5420var isArgs = isArguments;
5421
5422var origKeys = Object.keys;
5423var keysShim = origKeys ? function keys(o) { return origKeys(o); } : implementation$6;
5424
5425var originalKeys = Object.keys;
5426
5427keysShim.shim = function shimObjectKeys() {
5428 if (Object.keys) {
5429 var keysWorksWithArguments = (function () {
5430 // Safari 5.0 bug
5431 var args = Object.keys(arguments);
5432 return args && args.length === arguments.length;
5433 }(1, 2));
5434 if (!keysWorksWithArguments) {
5435 Object.keys = function keys(object) { // eslint-disable-line func-name-matching
5436 if (isArgs(object)) {
5437 return originalKeys(slice.call(object));
5438 }
5439 return originalKeys(object);
5440 };
5441 }
5442 } else {
5443 Object.keys = keysShim;
5444 }
5445 return Object.keys || keysShim;
5446};
5447
5448var objectKeys = keysShim;
5449
5450var keys = objectKeys;
5451var hasSymbols$2 = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
5452
5453var toStr$4 = Object.prototype.toString;
5454var concat = Array.prototype.concat;
5455var origDefineProperty = Object.defineProperty;
5456
5457var isFunction = function (fn) {
5458 return typeof fn === 'function' && toStr$4.call(fn) === '[object Function]';
5459};
5460
5461var arePropertyDescriptorsSupported = function () {
5462 var obj = {};
5463 try {
5464 origDefineProperty(obj, 'x', { enumerable: false, value: obj });
5465 // eslint-disable-next-line no-unused-vars, no-restricted-syntax
5466 for (var _ in obj) { // jscs:ignore disallowUnusedVariables
5467 return false;
5468 }
5469 return obj.x === obj;
5470 } catch (e) { /* this is IE 8. */
5471 return false;
5472 }
5473};
5474var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
5475
5476var defineProperty = function (object, name, value, predicate) {
5477 if (name in object && (!isFunction(predicate) || !predicate())) {
5478 return;
5479 }
5480 if (supportsDescriptors) {
5481 origDefineProperty(object, name, {
5482 configurable: true,
5483 enumerable: false,
5484 value: value,
5485 writable: true
5486 });
5487 } else {
5488 object[name] = value;
5489 }
5490};
5491
5492var defineProperties = function (object, map) {
5493 var predicates = arguments.length > 2 ? arguments[2] : {};
5494 var props = keys(map);
5495 if (hasSymbols$2) {
5496 props = concat.call(props, Object.getOwnPropertySymbols(map));
5497 }
5498 for (var i = 0; i < props.length; i += 1) {
5499 defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
5500 }
5501};
5502
5503defineProperties.supportsDescriptors = !!supportsDescriptors;
5504
5505var defineProperties_1 = defineProperties;
5506
5507var GetIntrinsic$6 = getIntrinsic;
5508
5509var callBind$4 = callBind$6.exports;
5510
5511var $indexOf = callBind$4(GetIntrinsic$6('String.prototype.indexOf'));
5512
5513var callBound$4 = function callBoundIntrinsic(name, allowMissing) {
5514 var intrinsic = GetIntrinsic$6(name, !!allowMissing);
5515 if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
5516 return callBind$4(intrinsic);
5517 }
5518 return intrinsic;
5519};
5520
5521var GetIntrinsic$5 = getIntrinsic;
5522
5523var $test = GetIntrinsic$5('RegExp.prototype.test');
5524
5525var callBind$3 = callBind$6.exports;
5526
5527var regexTester$1 = function regexTester(regex) {
5528 return callBind$3($test, regex);
5529};
5530
5531var isPrimitive$4 = function isPrimitive(value) {
5532 return value === null || (typeof value !== 'function' && typeof value !== 'object');
5533};
5534
5535var isPrimitive$3 = function isPrimitive(value) {
5536 return value === null || (typeof value !== 'function' && typeof value !== 'object');
5537};
5538
5539var fnToStr = Function.prototype.toString;
5540var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
5541var badArrayLike;
5542var isCallableMarker;
5543if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
5544 try {
5545 badArrayLike = Object.defineProperty({}, 'length', {
5546 get: function () {
5547 throw isCallableMarker;
5548 }
5549 });
5550 isCallableMarker = {};
5551 // eslint-disable-next-line no-throw-literal
5552 reflectApply(function () { throw 42; }, null, badArrayLike);
5553 } catch (_) {
5554 if (_ !== isCallableMarker) {
5555 reflectApply = null;
5556 }
5557 }
5558} else {
5559 reflectApply = null;
5560}
5561
5562var constructorRegex = /^\s*class\b/;
5563var isES6ClassFn = function isES6ClassFunction(value) {
5564 try {
5565 var fnStr = fnToStr.call(value);
5566 return constructorRegex.test(fnStr);
5567 } catch (e) {
5568 return false; // not a function
5569 }
5570};
5571
5572var tryFunctionObject = function tryFunctionToStr(value) {
5573 try {
5574 if (isES6ClassFn(value)) { return false; }
5575 fnToStr.call(value);
5576 return true;
5577 } catch (e) {
5578 return false;
5579 }
5580};
5581var toStr$3 = Object.prototype.toString;
5582var fnClass = '[object Function]';
5583var genClass = '[object GeneratorFunction]';
5584var hasToStringTag$1 = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
5585/* globals document: false */
5586var documentDotAll = typeof document === 'object' && typeof document.all === 'undefined' && document.all !== undefined ? document.all : {};
5587
5588var isCallable$2 = reflectApply
5589 ? function isCallable(value) {
5590 if (value === documentDotAll) { return true; }
5591 if (!value) { return false; }
5592 if (typeof value !== 'function' && typeof value !== 'object') { return false; }
5593 if (typeof value === 'function' && !value.prototype) { return true; }
5594 try {
5595 reflectApply(value, null, badArrayLike);
5596 } catch (e) {
5597 if (e !== isCallableMarker) { return false; }
5598 }
5599 return !isES6ClassFn(value);
5600 }
5601 : function isCallable(value) {
5602 if (value === documentDotAll) { return true; }
5603 if (!value) { return false; }
5604 if (typeof value !== 'function' && typeof value !== 'object') { return false; }
5605 if (typeof value === 'function' && !value.prototype) { return true; }
5606 if (hasToStringTag$1) { return tryFunctionObject(value); }
5607 if (isES6ClassFn(value)) { return false; }
5608 var strClass = toStr$3.call(value);
5609 return strClass === fnClass || strClass === genClass;
5610 };
5611
5612var getDay = Date.prototype.getDay;
5613var tryDateObject = function tryDateGetDayCall(value) {
5614 try {
5615 getDay.call(value);
5616 return true;
5617 } catch (e) {
5618 return false;
5619 }
5620};
5621
5622var toStr$2 = Object.prototype.toString;
5623var dateClass = '[object Date]';
5624var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag;
5625
5626var isDateObject = function isDateObject(value) {
5627 if (typeof value !== 'object' || value === null) {
5628 return false;
5629 }
5630 return hasToStringTag ? tryDateObject(value) : toStr$2.call(value) === dateClass;
5631};
5632
5633var isSymbol$1 = {exports: {}};
5634
5635var toStr$1 = Object.prototype.toString;
5636var hasSymbols$1 = hasSymbols$4();
5637
5638if (hasSymbols$1) {
5639 var symToStr = Symbol.prototype.toString;
5640 var symStringRegex = /^Symbol\(.*\)$/;
5641 var isSymbolObject = function isRealSymbolObject(value) {
5642 if (typeof value.valueOf() !== 'symbol') {
5643 return false;
5644 }
5645 return symStringRegex.test(symToStr.call(value));
5646 };
5647
5648 isSymbol$1.exports = function isSymbol(value) {
5649 if (typeof value === 'symbol') {
5650 return true;
5651 }
5652 if (toStr$1.call(value) !== '[object Symbol]') {
5653 return false;
5654 }
5655 try {
5656 return isSymbolObject(value);
5657 } catch (e) {
5658 return false;
5659 }
5660 };
5661} else {
5662
5663 isSymbol$1.exports = function isSymbol(value) {
5664 // this environment does not support Symbols.
5665 return false ;
5666 };
5667}
5668
5669var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
5670
5671var isPrimitive$2 = isPrimitive$3;
5672var isCallable$1 = isCallable$2;
5673var isDate = isDateObject;
5674var isSymbol = isSymbol$1.exports;
5675
5676var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) {
5677 if (typeof O === 'undefined' || O === null) {
5678 throw new TypeError('Cannot call method on ' + O);
5679 }
5680 if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) {
5681 throw new TypeError('hint must be "string" or "number"');
5682 }
5683 var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
5684 var method, result, i;
5685 for (i = 0; i < methodNames.length; ++i) {
5686 method = O[methodNames[i]];
5687 if (isCallable$1(method)) {
5688 result = method.call(O);
5689 if (isPrimitive$2(result)) {
5690 return result;
5691 }
5692 }
5693 }
5694 throw new TypeError('No default value');
5695};
5696
5697var GetMethod = function GetMethod(O, P) {
5698 var func = O[P];
5699 if (func !== null && typeof func !== 'undefined') {
5700 if (!isCallable$1(func)) {
5701 throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function');
5702 }
5703 return func;
5704 }
5705 return void 0;
5706};
5707
5708// http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive
5709var es2015 = function ToPrimitive(input) {
5710 if (isPrimitive$2(input)) {
5711 return input;
5712 }
5713 var hint = 'default';
5714 if (arguments.length > 1) {
5715 if (arguments[1] === String) {
5716 hint = 'string';
5717 } else if (arguments[1] === Number) {
5718 hint = 'number';
5719 }
5720 }
5721
5722 var exoticToPrim;
5723 if (hasSymbols) {
5724 if (Symbol.toPrimitive) {
5725 exoticToPrim = GetMethod(input, Symbol.toPrimitive);
5726 } else if (isSymbol(input)) {
5727 exoticToPrim = Symbol.prototype.valueOf;
5728 }
5729 }
5730 if (typeof exoticToPrim !== 'undefined') {
5731 var result = exoticToPrim.call(input, hint);
5732 if (isPrimitive$2(result)) {
5733 return result;
5734 }
5735 throw new TypeError('unable to convert exotic object to primitive');
5736 }
5737 if (hint === 'default' && (isDate(input) || isSymbol(input))) {
5738 hint = 'string';
5739 }
5740 return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint);
5741};
5742
5743var toPrimitive = es2015;
5744
5745// https://ecma-international.org/ecma-262/6.0/#sec-toprimitive
5746
5747var ToPrimitive$3 = function ToPrimitive(input) {
5748 if (arguments.length > 1) {
5749 return toPrimitive(input, arguments[1]);
5750 }
5751 return toPrimitive(input);
5752};
5753
5754var GetIntrinsic$4 = getIntrinsic;
5755
5756var $TypeError$2 = GetIntrinsic$4('%TypeError%');
5757var $Number = GetIntrinsic$4('%Number%');
5758var $RegExp = GetIntrinsic$4('%RegExp%');
5759var $parseInteger = GetIntrinsic$4('%parseInt%');
5760
5761var callBound$3 = callBound$4;
5762var regexTester = regexTester$1;
5763var isPrimitive$1 = isPrimitive$4;
5764
5765var $strSlice = callBound$3('String.prototype.slice');
5766var isBinary = regexTester(/^0b[01]+$/i);
5767var isOctal = regexTester(/^0o[0-7]+$/i);
5768var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i);
5769var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
5770var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
5771var hasNonWS = regexTester(nonWSregex);
5772
5773// whitespace from: https://es5.github.io/#x15.5.4.20
5774// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
5775var ws = [
5776 '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
5777 '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
5778 '\u2029\uFEFF'
5779].join('');
5780var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
5781var $replace = callBound$3('String.prototype.replace');
5782var $trim = function (value) {
5783 return $replace(value, trimRegex, '');
5784};
5785
5786var ToPrimitive$2 = ToPrimitive$3;
5787
5788// https://ecma-international.org/ecma-262/6.0/#sec-tonumber
5789
5790var ToNumber$4 = function ToNumber(argument) {
5791 var value = isPrimitive$1(argument) ? argument : ToPrimitive$2(argument, $Number);
5792 if (typeof value === 'symbol') {
5793 throw new $TypeError$2('Cannot convert a Symbol value to a number');
5794 }
5795 if (typeof value === 'string') {
5796 if (isBinary(value)) {
5797 return ToNumber($parseInteger($strSlice(value, 2), 2));
5798 } else if (isOctal(value)) {
5799 return ToNumber($parseInteger($strSlice(value, 2), 8));
5800 } else if (hasNonWS(value) || isInvalidHexLiteral(value)) {
5801 return NaN;
5802 } else {
5803 var trimmed = $trim(value);
5804 if (trimmed !== value) {
5805 return ToNumber(trimmed);
5806 }
5807 }
5808 }
5809 return $Number(value);
5810};
5811
5812var GetIntrinsic$3 = getIntrinsic;
5813
5814var $abs$1 = GetIntrinsic$3('%Math.abs%');
5815
5816// http://262.ecma-international.org/5.1/#sec-5.2
5817
5818var abs$3 = function abs(x) {
5819 return $abs$1(x);
5820};
5821
5822// var modulo = require('./modulo');
5823var $floor$1 = Math.floor;
5824
5825// http://262.ecma-international.org/5.1/#sec-5.2
5826
5827var floor$3 = function floor(x) {
5828 // return x - modulo(x, 1);
5829 return $floor$1(x);
5830};
5831
5832var _isNaN = Number.isNaN || function isNaN(a) {
5833 return a !== a;
5834};
5835
5836var $isNaN$2 = Number.isNaN || function (a) { return a !== a; };
5837
5838var _isFinite = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN$2(x) && x !== Infinity && x !== -Infinity; };
5839
5840var abs$2 = abs$3;
5841var floor$2 = floor$3;
5842
5843var $isNaN$1 = _isNaN;
5844var $isFinite$1 = _isFinite;
5845
5846// https://ecma-international.org/ecma-262/6.0/#sec-isinteger
5847
5848var IsInteger$1 = function IsInteger(argument) {
5849 if (typeof argument !== 'number' || $isNaN$1(argument) || !$isFinite$1(argument)) {
5850 return false;
5851 }
5852 var absValue = abs$2(argument);
5853 return floor$2(absValue) === absValue;
5854};
5855
5856// TODO; semver-major: remove
5857
5858var callBound$2 = callBound$4;
5859
5860/*! https://mths.be/fromcodepoint v1.0.0 by @mathias */
5861
5862var ToNumber$3 = ToNumber$4;
5863var IsInteger = IsInteger$1;
5864var callBound$1 = callBound$2;
5865var callBind$2 = callBind$5;
5866
5867var ArrayPush = callBound$1('Array.prototype.push');
5868var StringFromCharCodeSpread = callBind$2.apply(String.fromCharCode, null);
5869
5870var implementation$5 = function fromCodePoint(_ /* fromCodePoint.length is 1 */) {
5871 var MAX_SIZE = 0x4000;
5872 var codeUnits = [];
5873 var highSurrogate;
5874 var lowSurrogate;
5875 var index = -1;
5876 var length = arguments.length;
5877 if (!length) {
5878 return '';
5879 }
5880 var result = '';
5881 while (++index < length) {
5882 var codePoint = ToNumber$3(arguments[index]);
5883 if (
5884 !IsInteger(codePoint) ||
5885 codePoint < 0 || codePoint > 0x10FFFF // not a valid Unicode code point
5886 ) {
5887 throw RangeError('Invalid code point: ' + codePoint);
5888 }
5889 if (codePoint <= 0xFFFF) { // BMP code point
5890 ArrayPush(codeUnits, codePoint);
5891 } else { // Astral code point; split in surrogate halves
5892 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
5893 codePoint -= 0x10000;
5894 highSurrogate = (codePoint >> 10) + 0xD800;
5895 lowSurrogate = (codePoint % 0x400) + 0xDC00;
5896 ArrayPush(codeUnits, highSurrogate, lowSurrogate);
5897 }
5898 if (index + 1 == length || codeUnits.length > MAX_SIZE) {
5899 result += StringFromCharCodeSpread(codeUnits);
5900 codeUnits.length = 0;
5901 }
5902 }
5903 return result;
5904};
5905
5906/*! https://mths.be/fromcodepoint v1.0.0 by @mathias */
5907
5908var implementation$4 = implementation$5;
5909
5910var polyfill$1 = function getPolyfill() {
5911 return String.fromCodePoint || implementation$4;
5912};
5913
5914/*! https://mths.be/fromcodepoint v1.0.0 by @mathias */
5915
5916var define$3 = defineProperties_1;
5917
5918var getPolyfill$3 = polyfill$1;
5919
5920var shim$3 = function shimFromCodePoint() {
5921 var polyfill = getPolyfill$3();
5922
5923 if (String.fromCodePoint !== polyfill) {
5924 define$3(String, { fromCodePoint: polyfill });
5925 }
5926
5927 return polyfill;
5928};
5929
5930/*! https://mths.be/fromcodepoint v1.0.0 by @mathias */
5931
5932var callBind$1 = callBind$5;
5933var define$2 = defineProperties_1;
5934
5935var implementation$3 = implementation$5;
5936var getPolyfill$2 = polyfill$1;
5937var shim$2 = shim$3;
5938
5939var boundFromCodePoint = callBind$1(getPolyfill$2(), String);
5940
5941define$2(boundFromCodePoint, {
5942 getPolyfill: getPolyfill$2,
5943 implementation: implementation$3,
5944 shim: shim$2
5945});
5946
5947var GetIntrinsic$2 = getIntrinsic;
5948
5949var $TypeError$1 = GetIntrinsic$2('%TypeError%');
5950
5951// http://262.ecma-international.org/5.1/#sec-9.10
5952
5953var CheckObjectCoercible = function CheckObjectCoercible(value, optMessage) {
5954 if (value == null) {
5955 throw new $TypeError$1(optMessage || ('Cannot call method on ' + value));
5956 }
5957 return value;
5958};
5959
5960var RequireObjectCoercible$1 = CheckObjectCoercible;
5961
5962var GetIntrinsic$1 = getIntrinsic;
5963
5964var $String = GetIntrinsic$1('%String%');
5965var $TypeError = GetIntrinsic$1('%TypeError%');
5966
5967// https://ecma-international.org/ecma-262/6.0/#sec-tostring
5968
5969var ToString$1 = function ToString(argument) {
5970 if (typeof argument === 'symbol') {
5971 throw new $TypeError('Cannot convert a Symbol value to a string');
5972 }
5973 return $String(argument);
5974};
5975
5976var GetIntrinsic = getIntrinsic;
5977
5978var $abs = GetIntrinsic('%Math.abs%');
5979
5980// http://262.ecma-international.org/5.1/#sec-5.2
5981
5982var abs$1 = function abs(x) {
5983 return $abs(x);
5984};
5985
5986// var modulo = require('./modulo');
5987var $floor = Math.floor;
5988
5989// http://262.ecma-international.org/5.1/#sec-5.2
5990
5991var floor$1 = function floor(x) {
5992 // return x - modulo(x, 1);
5993 return $floor(x);
5994};
5995
5996var toStr = Object.prototype.toString;
5997
5998var isPrimitive = isPrimitive$3;
5999
6000var isCallable = isCallable$2;
6001
6002// http://ecma-international.org/ecma-262/5.1/#sec-8.12.8
6003var ES5internalSlots = {
6004 '[[DefaultValue]]': function (O) {
6005 var actualHint;
6006 if (arguments.length > 1) {
6007 actualHint = arguments[1];
6008 } else {
6009 actualHint = toStr.call(O) === '[object Date]' ? String : Number;
6010 }
6011
6012 if (actualHint === String || actualHint === Number) {
6013 var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
6014 var value, i;
6015 for (i = 0; i < methods.length; ++i) {
6016 if (isCallable(O[methods[i]])) {
6017 value = O[methods[i]]();
6018 if (isPrimitive(value)) {
6019 return value;
6020 }
6021 }
6022 }
6023 throw new TypeError('No default value');
6024 }
6025 throw new TypeError('invalid [[DefaultValue]] hint supplied');
6026 }
6027};
6028
6029// http://ecma-international.org/ecma-262/5.1/#sec-9.1
6030var es5 = function ToPrimitive(input) {
6031 if (isPrimitive(input)) {
6032 return input;
6033 }
6034 if (arguments.length > 1) {
6035 return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]);
6036 }
6037 return ES5internalSlots['[[DefaultValue]]'](input);
6038};
6039
6040// http://262.ecma-international.org/5.1/#sec-9.1
6041
6042var ToPrimitive$1 = es5;
6043
6044var ToPrimitive = ToPrimitive$1;
6045
6046// http://262.ecma-international.org/5.1/#sec-9.3
6047
6048var ToNumber$2 = function ToNumber(value) {
6049 var prim = ToPrimitive(value, Number);
6050 if (typeof prim !== 'string') {
6051 return +prim; // eslint-disable-line no-implicit-coercion
6052 }
6053
6054 // eslint-disable-next-line no-control-regex
6055 var trimmed = prim.replace(/^[ \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u0085]+|[ \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u0085]+$/g, '');
6056 if ((/^0[ob]|^[+-]0x/).test(trimmed)) {
6057 return NaN;
6058 }
6059
6060 return +trimmed; // eslint-disable-line no-implicit-coercion
6061};
6062
6063var sign = function sign(number) {
6064 return number >= 0 ? 1 : -1;
6065};
6066
6067var abs = abs$1;
6068var floor = floor$1;
6069var ToNumber$1 = ToNumber$2;
6070
6071var $isNaN = _isNaN;
6072var $isFinite = _isFinite;
6073var $sign = sign;
6074
6075// http://262.ecma-international.org/5.1/#sec-9.4
6076
6077var ToInteger$2 = function ToInteger(value) {
6078 var number = ToNumber$1(value);
6079 if ($isNaN(number)) { return 0; }
6080 if (number === 0 || !$isFinite(number)) { return number; }
6081 return $sign(number) * floor(abs(number));
6082};
6083
6084var ES5ToInteger = ToInteger$2;
6085
6086var ToNumber = ToNumber$4;
6087
6088// https://ecma-international.org/ecma-262/6.0/#sec-tointeger
6089
6090var ToInteger$1 = function ToInteger(value) {
6091 var number = ToNumber(value);
6092 return ES5ToInteger(number);
6093};
6094
6095/*! https://mths.be/codepointat v1.0.0 by @mathias */
6096
6097var callBound = callBound$2;
6098var RequireObjectCoercible = RequireObjectCoercible$1;
6099var ToString = ToString$1;
6100var ToInteger = ToInteger$1;
6101var StringCharCodeAt = callBound('String.prototype.charCodeAt');
6102
6103var implementation$2 = function codePointAt(position) {
6104 var O = RequireObjectCoercible(this);
6105 var string = ToString(O);
6106 var size = string.length;
6107 var index = ToInteger(position);
6108 // Account for out-of-bounds indices:
6109 if (index < 0 || index >= size) {
6110 return undefined;
6111 }
6112 // Get the first code unit
6113 var first = StringCharCodeAt(string, index);
6114 var second;
6115 if ( // check if it’s the start of a surrogate pair
6116 first >= 0xD800 && first <= 0xDBFF && // high surrogate
6117 size > index + 1 // there is a next code unit
6118 ) {
6119 second = StringCharCodeAt(string, index + 1);
6120 if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
6121 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
6122 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
6123 }
6124 }
6125 return first;
6126};
6127
6128/*! https://mths.be/codepointat v1.0.0 by @mathias */
6129
6130var implementation$1 = implementation$2;
6131
6132var polyfill = function getPolyfill() {
6133 return String.prototype.codePointAt || implementation$1;
6134};
6135
6136/*! https://mths.be/codepointat v1.0.0 by @mathias */
6137
6138var define$1 = defineProperties_1;
6139
6140var getPolyfill$1 = polyfill;
6141
6142var shim$1 = function shimCodePointAt() {
6143 var polyfill = getPolyfill$1();
6144
6145 if (String.prototype.codePointAt !== polyfill) {
6146 define$1(String.prototype, { codePointAt: polyfill });
6147 }
6148
6149 return polyfill;
6150};
6151
6152/*! https://mths.be/codepointat v1.0.0 by @mathias */
6153
6154var callBind = callBind$5;
6155var define = defineProperties_1;
6156
6157var implementation = implementation$2;
6158var getPolyfill = polyfill;
6159var shim = shim$1;
6160
6161var boundCodePointAt = callBind(getPolyfill());
6162
6163define(boundCodePointAt, {
6164 getPolyfill: getPolyfill,
6165 implementation: implementation,
6166 shim: shim
6167});
6168
6169/* eslint-disable prefer-template,newline-per-chained-call,complexity */
6170
6171const path = path__default['default'];
6172const fs = fs__default['default'];
6173
6174
6175
6176
6177function getMetadataService(options = {}) {
6178 let usedUnicodes = [];
6179
6180 // Default options
6181 options.prependUnicode = !!options.prependUnicode;
6182 options.startUnicode =
6183 'number' === typeof options.startUnicode ? options.startUnicode : 0xea01;
6184 options.log = options.log || console.log; // eslint-disable-line
6185 options.err = options.err || console.err; // eslint-disable-line
6186
6187 // Throw on old options usage
6188 if ('undefined' !== typeof options.appendUnicode) {
6189 throw new Error(
6190 'The "appendUnicode" option was renamed "prependUnicode".' +
6191 ' See https://github.com/nfroidure/gulp-svgicons2svgfont/issues/33'
6192 );
6193 }
6194
6195 return function getMetadataFromFile(file, cb) {
6196 const basename = path.basename(file);
6197 const metadata = {
6198 path: file,
6199 name: '',
6200 unicode: [],
6201 renamed: false,
6202 };
6203 const matches = basename.match(/^(?:((?:u[0-9a-f]{4,6},?)+)-)?(.+)\.svg$/i);
6204
6205 metadata.name =
6206 matches && matches[2] ? matches[2] : 'icon' + options.startUnicode;
6207 if (matches && matches[1]) {
6208 metadata.unicode = matches[1].split(',').map((match) => {
6209 match = match.substr(1);
6210 return match
6211 .split('u')
6212 .map((code) => String.fromCodePoint(parseInt(code, 16)))
6213 .join('');
6214 });
6215 if (-1 !== usedUnicodes.indexOf(metadata.unicode[0])) {
6216 cb(
6217 new Error(
6218 'The unicode codepoint of the glyph ' +
6219 metadata.name +
6220 ' seems to be already used by another glyph.'
6221 )
6222 );
6223 return;
6224 }
6225 usedUnicodes.push(...metadata.unicode);
6226 } else {
6227 do {
6228 metadata.unicode[0] = String.fromCodePoint(options.startUnicode++);
6229 } while (usedUnicodes.includes(metadata.unicode[0]));
6230 usedUnicodes.push(metadata.unicode[0]);
6231 if (options.prependUnicode) {
6232 metadata.renamed = true;
6233 metadata.path = path.join(
6234 path.dirname(file),
6235 'u' +
6236 metadata.unicode[0].codePointAt(0).toString(16).toUpperCase() +
6237 '-' +
6238 basename
6239 );
6240 fs.rename(file, metadata.path, (err) => {
6241 if (err) {
6242 cb(
6243 new Error(
6244 'Could not save codepoint: ' +
6245 'u' +
6246 metadata.unicode[0]
6247 .codePointAt(0)
6248 .toString(16)
6249 .toUpperCase() +
6250 ' for ' +
6251 basename
6252 )
6253 );
6254 return;
6255 }
6256 cb(null, metadata);
6257 });
6258 }
6259 }
6260 if (!metadata.renamed) {
6261 setImmediate(() => cb(null, metadata));
6262 }
6263 };
6264}
6265
6266var metadata = getMetadataService;
6267
6268var buildConfig = function (options) { return __awaiter(void 0, void 0, void 0, function () {
6269 var searchPath, configPath, configExplorer, config;
6270 return __generator(this, function (_a) {
6271 switch (_a.label) {
6272 case 0:
6273 searchPath = process.cwd();
6274 configPath = null;
6275 if (options.configFile) {
6276 searchPath = null;
6277 configPath = path__default['default'].resolve(process.cwd(), options.configFile);
6278 }
6279 configExplorer = dist("webfont");
6280 return [4 /*yield*/, configExplorer.search(searchPath)];
6281 case 1:
6282 config = _a.sent();
6283 if (!configPath) return [3 /*break*/, 3];
6284 return [4 /*yield*/, configExplorer.load(configPath)];
6285 case 2:
6286 config = _a.sent();
6287 _a.label = 3;
6288 case 3:
6289 if (!config) {
6290 return [2 /*return*/, {}];
6291 }
6292 return [2 /*return*/, config];
6293 }
6294 });
6295}); };
6296var getGlyphsData = function (files, options) {
6297 var metadataProvider = options.metadataProvider ||
6298 metadata({
6299 prependUnicode: options.prependUnicode,
6300 startUnicode: options.startUnicode
6301 });
6302 var xmlParser = new xml2js__default['default'].Parser();
6303 var throttle = pLimit__default['default'](options.maxConcurrency);
6304 return Promise.all(files.map(function (srcPath) { return throttle(function () { return new Promise(function (resolve, reject) {
6305 var glyph = fs__default['default'].createReadStream(srcPath);
6306 var glyphContents = "";
6307 // eslint-disable-next-line no-promise-executor-return
6308 return glyph.
6309 on("error", function (glyphError) { return reject(glyphError); }).
6310 on("data", function (data) {
6311 glyphContents += data.toString();
6312 }).
6313 on("end", function () {
6314 // Maybe bug in xml2js
6315 if (glyphContents.length === 0) {
6316 return reject(new Error("Empty file " + srcPath));
6317 }
6318 return xmlParser.parseString(glyphContents, function (error) {
6319 if (error) {
6320 return reject(error);
6321 }
6322 var glyphData = {
6323 contents: glyphContents,
6324 srcPath: srcPath
6325 };
6326 return resolve(glyphData);
6327 });
6328 });
6329 }); }); })).then(function (glyphsData) {
6330 var sortedGlyphsData = glyphsData;
6331 if (options.sort) {
6332 var sortCallback = function (fileA, fileB) { return filesorter(fileA.srcPath, fileB.srcPath); };
6333 sortedGlyphsData = glyphsData.sort(sortCallback);
6334 }
6335 return Promise.all(sortedGlyphsData.map(function (glyphData) { return new Promise(function (resolve, reject) {
6336 metadataProvider(glyphData.srcPath, function (error, metadata) {
6337 if (error) {
6338 return reject(error);
6339 }
6340 metadata.unicode.push(metadata.name.replace(/-/gu, "_"));
6341 glyphData.metadata = metadata;
6342 return resolve(glyphData);
6343 });
6344 }); }));
6345 });
6346};
6347var toSvg = function (glyphsData, options) {
6348 var result = "";
6349 return new Promise(function (resolve, reject) {
6350 var log = function () {
6351 Function.prototype();
6352 };
6353 if (options.verbose) {
6354 // eslint-disable-next-line no-console
6355 log = console.log.bind(console);
6356 }
6357 var fontStream = new SVGIcons2SVGFontStream__default['default']({
6358 ascent: options.ascent,
6359 centerHorizontally: options.centerHorizontally,
6360 descent: options.descent,
6361 fixedWidth: options.fixedWidth,
6362 fontHeight: options.fontHeight,
6363 fontId: options.fontId,
6364 fontName: options.fontName,
6365 fontStyle: options.fontStyle,
6366 fontWeight: options.fontWeight,
6367 log: log,
6368 metadata: options.metadata,
6369 normalize: options.normalize,
6370 round: options.round
6371 }).
6372 on("finish", function () { return resolve(result); }).
6373 on("data", function (data) {
6374 result += data;
6375 }).
6376 on("error", function (error) { return reject(error); });
6377 glyphsData.forEach(function (glyphData) {
6378 var glyphStream = new stream.Readable();
6379 glyphStream.push(glyphData.contents);
6380 glyphStream.push(null);
6381 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
6382 // @ts-ignore
6383 glyphStream.metadata = glyphData.metadata;
6384 fontStream.write(glyphStream);
6385 });
6386 fontStream.end();
6387 });
6388};
6389var toTtf = function (buffer, options) { return Buffer.from(svg2ttf__default['default'](buffer, options).buffer); };
6390var toEot = function (buffer) { return Buffer.from(ttf2eot__default['default'](buffer).buffer); };
6391var toWoff = function (buffer, options) { return Buffer.from(ttf2woff__default['default'](buffer, options).buffer); };
6392var toWoff2 = function (buffer) { return wawoff2__default['default'].compress(buffer); };
6393var webfont = function (initialOptions) { return __awaiter(void 0, void 0, void 0, function () {
6394 var options, config, foundFiles, filteredFiles, glyphsData, ttfOptions, svg, ttf, result, _a, builtInTemplates, templateFilePath, builtInPath, resolvedTemplateFilePath, hashOption, nunjucksOptions;
6395 return __generator(this, function (_b) {
6396 switch (_b.label) {
6397 case 0:
6398 if (!initialOptions || !initialOptions.files) {
6399 throw new Error("You must pass webfont a `files` glob");
6400 }
6401 options = __assign({ centerHorizontally: false, descent: 0, fixedWidth: false, fontHeight: null, fontId: null, fontName: "webfont", fontStyle: "", fontWeight: "", formats: ["svg", "ttf", "eot", "woff", "woff2"], formatsOptions: {
6402 ttf: {
6403 copyright: null,
6404 ts: null,
6405 version: null
6406 }
6407 }, glyphTransformFn: null,
6408 /*
6409 * Maybe allow setup from CLI
6410 * This is usually less than file read maximums while staying performance
6411 */
6412 maxConcurrency: 100, metadata: null, metadataProvider: null, normalize: false, prependUnicode: false, round: 10e12, sort: true, startUnicode: 0xea01, template: null, templateCacheString: null, templateClassName: null, templateFontName: null, templateFontPath: "./", verbose: false }, initialOptions);
6413 return [4 /*yield*/, buildConfig({
6414 configFile: options.configFile
6415 })];
6416 case 1:
6417 config = _b.sent();
6418 if (Object.keys(config).length > 0) {
6419 // eslint-disable-next-line require-atomic-updates
6420 options = deepmerge__default['default'](options, config.config, {
6421 arrayMerge: function (_destinationArray, sourceArray) { return sourceArray; }
6422 });
6423 // eslint-disable-next-line require-atomic-updates
6424 options.filePath = config.filepath;
6425 }
6426 return [4 /*yield*/, globby__default['default']([].concat(options.files))];
6427 case 2:
6428 foundFiles = _b.sent();
6429 filteredFiles = foundFiles.filter(function (foundFile) { return path__default['default'].extname(foundFile) === ".svg"; });
6430 if (filteredFiles.length === 0) {
6431 throw new Error("Files glob patterns specified did not match any files");
6432 }
6433 return [4 /*yield*/, getGlyphsData(filteredFiles, options)];
6434 case 3:
6435 glyphsData = _b.sent();
6436 ttfOptions = {};
6437 if (options.formatsOptions && options.formatsOptions.ttf) {
6438 ttfOptions = options.formatsOptions.ttf;
6439 }
6440 return [4 /*yield*/, toSvg(glyphsData, options)];
6441 case 4:
6442 svg = _b.sent();
6443 ttf = toTtf(svg, ttfOptions);
6444 result = {
6445 glyphsData: glyphsData,
6446 hash: crypto__default['default'].createHash("md5").update(svg).
6447 digest("hex"),
6448 svg: svg,
6449 ttf: ttf
6450 };
6451 if (options.formats.includes("eot")) {
6452 result.eot = toEot(ttf);
6453 }
6454 if (options.formats.includes("woff")) {
6455 result.woff = toWoff(ttf, { metadata: options.metadata });
6456 }
6457 if (!options.formats.includes("woff2")) return [3 /*break*/, 6];
6458 _a = result;
6459 return [4 /*yield*/, toWoff2(ttf)];
6460 case 5:
6461 _a.woff2 = _b.sent();
6462 _b.label = 6;
6463 case 6:
6464 if (options.template) {
6465 builtInTemplates = getBuiltInTemplates();
6466 templateFilePath = void 0;
6467 if (Object.keys(builtInTemplates).includes(options.template)) {
6468 result.usedBuildInTemplate = true;
6469 builtInPath = path__default['default'].resolve(__dirname, "../..");
6470 nunjucks__default['default'].configure(builtInPath);
6471 templateFilePath = getTemplateFilePath(options.template);
6472 }
6473 else {
6474 resolvedTemplateFilePath = path__default['default'].resolve(options.template);
6475 nunjucks__default['default'].configure(path__default['default'].dirname(resolvedTemplateFilePath));
6476 templateFilePath = path__default['default'].resolve(resolvedTemplateFilePath);
6477 }
6478 hashOption = {};
6479 if (options.addHashInFontUrl) {
6480 hashOption = { hash: result.hash };
6481 }
6482 nunjucksOptions = deepmerge__default['default'].all([
6483 {
6484 glyphs: result.glyphsData.map(function (glyphData) {
6485 if (typeof options.glyphTransformFn === "function") {
6486 glyphData.metadata = options.glyphTransformFn(glyphData.metadata);
6487 }
6488 return glyphData.metadata;
6489 })
6490 },
6491 options,
6492 {
6493 cacheString: options.templateCacheString || Date.now(),
6494 className: options.templateClassName || options.fontName,
6495 fontName: options.templateFontName || options.fontName,
6496 fontPath: options.templateFontPath.replace(/\/?$/u, "/")
6497 },
6498 hashOption,
6499 {
6500 fonts: Object.fromEntries(new Map(options.formats.map(function (format) { return [
6501 format,
6502 function () {
6503 if (format === "woff2") {
6504 return Buffer.from(result.woff2).toString("base64");
6505 }
6506 return result[format].toString("base64");
6507 },
6508 ]; })))
6509 },
6510 ]);
6511 result.template = nunjucks__default['default'].render(templateFilePath, nunjucksOptions);
6512 }
6513 if (!options.formats.includes("svg")) {
6514 delete result.svg;
6515 }
6516 if (!options.formats.includes("ttf")) {
6517 delete result.ttf;
6518 }
6519 result.config = options;
6520 return [2 /*return*/, result];
6521 }
6522 });
6523}); };
6524
6525var optionsBase = {};
6526if (typeof meowCLI.flags.config === "string") {
6527 /*
6528 * Should check these possibilities:
6529 * a. name of a node_module
6530 * b. absolute path
6531 * c. relative path relative to `process.cwd()`.
6532 * If none of the above work, we'll try a relative path starting
6533 * in `process.cwd()`.
6534 */
6535 optionsBase.configFile =
6536 require$$1__default['default'](process.cwd(), meowCLI.flags.config) ||
6537 path__namespace.join(process.cwd(), meowCLI.flags.config);
6538}
6539if (meowCLI.flags.fontName) {
6540 optionsBase.fontName = meowCLI.flags.fontName;
6541}
6542if (meowCLI.flags.formats) {
6543 optionsBase.formats = meowCLI.flags.formats;
6544}
6545if (meowCLI.flags.dest) {
6546 optionsBase.dest = meowCLI.flags.dest;
6547}
6548if (meowCLI.flags.destCreate) {
6549 optionsBase.destCreate = meowCLI.flags.destCreate;
6550}
6551if (meowCLI.flags.template) {
6552 optionsBase.template = meowCLI.flags.template;
6553}
6554if (meowCLI.flags.templateClassName) {
6555 optionsBase.templateClassName = meowCLI.flags.templateClassName;
6556}
6557if (meowCLI.flags.templateFontPath) {
6558 optionsBase.templateFontPath = meowCLI.flags.templateFontPath;
6559}
6560if (meowCLI.flags.templateFontName) {
6561 optionsBase.templateFontName = meowCLI.flags.templateFontName;
6562}
6563if (meowCLI.flags.templateCacheString) {
6564 optionsBase.templateCacheString = meowCLI.flags.templateCacheString;
6565}
6566if (meowCLI.flags.destTemplate) {
6567 optionsBase.destTemplate = meowCLI.flags.destTemplate;
6568}
6569if (meowCLI.flags.verbose) {
6570 optionsBase.verbose = meowCLI.flags.verbose;
6571}
6572if (meowCLI.flags.fontId) {
6573 optionsBase.fontId = meowCLI.flags.fontId;
6574}
6575if (meowCLI.flags.fontStyle) {
6576 optionsBase.fontStyle = meowCLI.flags.fontStyle;
6577}
6578if (meowCLI.flags.fontWeight) {
6579 optionsBase.fontWeight = meowCLI.flags.fontWeight;
6580}
6581if (meowCLI.flags.fixedWidth) {
6582 optionsBase.fixedWidth = meowCLI.flags.fixedWidth;
6583}
6584if (meowCLI.flags.centerHorizontally) {
6585 optionsBase.centerHorizontally = meowCLI.flags.centerHorizontally;
6586}
6587if (meowCLI.flags.normalize) {
6588 optionsBase.normalize = meowCLI.flags.normalize;
6589}
6590if (meowCLI.flags.fontHeight) {
6591 optionsBase.fontHeight = meowCLI.flags.fontHeight;
6592}
6593if (meowCLI.flags.round) {
6594 optionsBase.round = meowCLI.flags.round;
6595}
6596if (meowCLI.flags.descent) {
6597 optionsBase.descent = meowCLI.flags.descent;
6598}
6599if (meowCLI.flags.ascent) {
6600 optionsBase.ascent = meowCLI.flags.ascent;
6601}
6602if (meowCLI.flags.startUnicode) {
6603 optionsBase.startUnicode = meowCLI.flags.startUnicode;
6604}
6605if (meowCLI.flags.prependUnicode) {
6606 optionsBase.prependUnicode = meowCLI.flags.prependUnicode;
6607}
6608if (meowCLI.flags.metadata) {
6609 optionsBase.metadata = meowCLI.flags.metadata;
6610}
6611if (meowCLI.flags.sort === false) {
6612 optionsBase.sort = meowCLI.flags.sort;
6613}
6614if (meowCLI.flags.addHashInFontUrl) {
6615 optionsBase.addHashInFontUrl = meowCLI.flags.addHashInFontUrl;
6616}
6617if (meowCLI.flags.help || meowCLI.flags.h) {
6618 meowCLI.showHelp();
6619}
6620if (meowCLI.flags.version || meowCLI.flags.v) {
6621 meowCLI.showVersion();
6622}
6623Promise.resolve().
6624 then(function () {
6625 var options = __assign(__assign({}, optionsBase), { files: meowCLI.input });
6626 if (options.files.length === 0) {
6627 meowCLI.showHelp();
6628 }
6629 return webfont(options).then(function (result) {
6630 result.config = __assign({ dest: options.dest, destTemplate: options.destTemplate }, result.config);
6631 return result;
6632 });
6633}).
6634 then(function (result) {
6635 var _a = result.config, fontName = _a.fontName, dest = _a.dest, destCreate = _a.destCreate;
6636 var destTemplate = null;
6637 if (result.template) {
6638 (destTemplate = result.config.destTemplate);
6639 if (!destTemplate) {
6640 destTemplate = dest;
6641 }
6642 if (result.usedBuildInTemplate) {
6643 destTemplate = path__namespace.join(destTemplate, result.config.fontName + "." + result.config.template);
6644 }
6645 else {
6646 destTemplate = path__namespace.join(destTemplate, path__namespace.basename(result.config.template).replace(".njk", ""));
6647 }
6648 delete result.hash;
6649 }
6650 return Promise.resolve().
6651 then(function () { return new Promise(function (resolve, reject) {
6652 fs__namespace.access(dest, fs__namespace.constants.F_OK, function (err) { return reject(err); });
6653 }); })["catch"](function (error) {
6654 if (error && destCreate) {
6655 return new Promise(function (resolve) {
6656 fs__namespace.mkdir(dest, { recursive: true }, function () { return resolve(destCreate); });
6657 });
6658 }
6659 return error;
6660 })["finally"](function () { return Promise.all(Object.keys(result).map(function (type) {
6661 if (type === "config" || type === "usedBuildInTemplate" || type === "glyphsData") {
6662 return null;
6663 }
6664 var content = result[type];
6665 // eslint-disable-next-line init-declarations
6666 var file;
6667 if (type === "template") {
6668 file = path__namespace.resolve(destTemplate);
6669 }
6670 else {
6671 file = path__namespace.resolve(path__namespace.join(dest, fontName + "." + type));
6672 }
6673 return fs__namespace.writeFile(file, content, function () {
6674 Function.prototype();
6675 });
6676 })); }).
6677 then(function () { return Promise.resolve(result); });
6678})["catch"](function (error) {
6679 // eslint-disable-next-line no-console
6680 console.log(error.stack);
6681 var exitCode = 1;
6682 if (typeof error.code === "number") {
6683 exitCode = error.code;
6684 }
6685 process.exit(exitCode);
6686});