'use strict'; // Don't change this file manually, // it is generated from tools/node-lint-md-cli-rollup var stream = require('stream'); var path$2 = require('path'); var module$1 = require('module'); var util$2 = require('util'); var os = require('os'); var tty = require('tty'); var fs$1 = require('fs'); var events = require('events'); var assert = require('assert'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var stream__default = /*#__PURE__*/_interopDefaultLegacy(stream); var path__default = /*#__PURE__*/_interopDefaultLegacy(path$2); var module__default = /*#__PURE__*/_interopDefaultLegacy(module$1); var util__default = /*#__PURE__*/_interopDefaultLegacy(util$2); var os__default = /*#__PURE__*/_interopDefaultLegacy(os); var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty); var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1); var events__default = /*#__PURE__*/_interopDefaultLegacy(events); var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert); var vfileStatistics = statistics; // Get stats for a file, list of files, or list of messages. function statistics(files) { var result = {true: 0, false: 0, null: 0}; count(files); return { fatal: result.true, nonfatal: result.false + result.null, warn: result.false, info: result.null, total: result.true + result.false + result.null } function count(value) { if (value) { if (value[0] && value[0].messages) { // Multiple vfiles countInAll(value); } else { // One vfile / messages countAll(value.messages || value); } } } function countInAll(files) { var length = files.length; var index = -1; while (++index < length) { count(files[index].messages); } } function countAll(messages) { var length = messages.length; var index = -1; var fatal; while (++index < length) { fatal = messages[index].fatal; result[fatal === null || fatal === undefined ? null : Boolean(fatal)]++; } } } var slice = [].slice; var wrap_1 = wrap; // Wrap `fn`. // Can be sync or async; return a promise, receive a completion handler, return // new values and errors. function wrap(fn, callback) { var invoked; return wrapped function wrapped() { var params = slice.call(arguments, 0); var callback = fn.length > params.length; var result; if (callback) { params.push(done); } try { result = fn.apply(null, params); } catch (error) { // Well, this is quite the pickle. // `fn` received a callback and invoked it (thus continuing the pipeline), // but later also threw an error. // We’re not about to restart the pipeline again, so the only thing left // to do is to throw the thing instead. if (callback && invoked) { throw error } return done(error) } if (!callback) { if (result && typeof result.then === 'function') { result.then(then, done); } else if (result instanceof Error) { done(result); } else { then(result); } } } // Invoke `next`, only once. function done() { if (!invoked) { invoked = true; callback.apply(null, arguments); } } // Invoke `done` with one value. // Tracks if an error is passed, too. function then(value) { done(null, value); } } var trough_1 = trough; trough.wrap = wrap_1; var slice$1 = [].slice; // Create new middleware. function trough() { var fns = []; var middleware = {}; middleware.run = run; middleware.use = use; return middleware // Run `fns`. Last argument must be a completion handler. function run() { var index = -1; var input = slice$1.call(arguments, 0, -1); var done = arguments[arguments.length - 1]; if (typeof done !== 'function') { throw new Error('Expected function as last argument, not ' + done) } next.apply(null, [null].concat(input)); // Run the next `fn`, if any. function next(err) { var fn = fns[++index]; var params = slice$1.call(arguments, 0); var values = params.slice(1); var length = input.length; var pos = -1; if (err) { done(err); return } // Copy non-nully input into values. while (++pos < length) { if (values[pos] === null || values[pos] === undefined) { values[pos] = input[pos]; } } input = values; // Next or done. if (fn) { wrap_1(fn, next).apply(null, input); } else { done.apply(null, [null].concat(input)); } } } // Add `fn` to the list. function use(fn) { if (typeof fn !== 'function') { throw new Error('Expected `fn` to be a function, not ' + fn) } fns.push(fn); return middleware } } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } function getCjsExportFromNamespace (n) { return n && n['default'] || n; } function commonjsRequire () { throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); } function isNothing(subject) { return (typeof subject === 'undefined') || (subject === null); } function isObject(subject) { return (typeof subject === 'object') && (subject !== null); } function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [ sequence ]; } function extend(target, source) { var index, length, key, sourceKeys; if (source) { sourceKeys = Object.keys(source); for (index = 0, length = sourceKeys.length; index < length; index += 1) { key = sourceKeys[index]; target[key] = source[key]; } } return target; } function repeat(string, count) { var result = '', cycle; for (cycle = 0; cycle < count; cycle += 1) { result += string; } return result; } function isNegativeZero(number) { return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); } var isNothing_1 = isNothing; var isObject_1 = isObject; var toArray_1 = toArray; var repeat_1 = repeat; var isNegativeZero_1 = isNegativeZero; var extend_1 = extend; var common = { isNothing: isNothing_1, isObject: isObject_1, toArray: toArray_1, repeat: repeat_1, isNegativeZero: isNegativeZero_1, extend: extend_1 }; // YAML error class. http://stackoverflow.com/questions/8458984 function YAMLException(reason, mark) { // Super constructor Error.call(this); this.name = 'YAMLException'; this.reason = reason; this.mark = mark; this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); // Include stack trace in error object if (Error.captureStackTrace) { // Chrome and NodeJS Error.captureStackTrace(this, this.constructor); } else { // FF, IE 10+ and Safari 6+. Fallback for others this.stack = (new Error()).stack || ''; } } // Inherit from Error YAMLException.prototype = Object.create(Error.prototype); YAMLException.prototype.constructor = YAMLException; YAMLException.prototype.toString = function toString(compact) { var result = this.name + ': '; result += this.reason || '(unknown reason)'; if (!compact && this.mark) { result += ' ' + this.mark.toString(); } return result; }; var exception = YAMLException; function Mark(name, buffer, position, line, column) { this.name = name; this.buffer = buffer; this.position = position; this.line = line; this.column = column; } Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { var head, start, tail, end, snippet; if (!this.buffer) return null; indent = indent || 4; maxLength = maxLength || 75; head = ''; start = this.position; while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { start -= 1; if (this.position - start > (maxLength / 2 - 1)) { head = ' ... '; start += 5; break; } } tail = ''; end = this.position; while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { end += 1; if (end - this.position > (maxLength / 2 - 1)) { tail = ' ... '; end -= 5; break; } } snippet = this.buffer.slice(start, end); return common.repeat(' ', indent) + head + snippet + tail + '\n' + common.repeat(' ', indent + this.position - start + head.length) + '^'; }; Mark.prototype.toString = function toString(compact) { var snippet, where = ''; if (this.name) { where += 'in "' + this.name + '" '; } where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); if (!compact) { snippet = this.getSnippet(); if (snippet) { where += ':\n' + snippet; } } return where; }; var mark = Mark; var TYPE_CONSTRUCTOR_OPTIONS = [ 'kind', 'resolve', 'construct', 'instanceOf', 'predicate', 'represent', 'defaultStyle', 'styleAliases' ]; var YAML_NODE_KINDS = [ 'scalar', 'sequence', 'mapping' ]; function compileStyleAliases(map) { var result = {}; if (map !== null) { Object.keys(map).forEach(function (style) { map[style].forEach(function (alias) { result[String(alias)] = style; }); }); } return result; } function Type(tag, options) { options = options || {}; Object.keys(options).forEach(function (name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); } }); // TODO: Add tag format check. this.tag = tag; this.kind = options['kind'] || null; this.resolve = options['resolve'] || function () { return true; }; this.construct = options['construct'] || function (data) { return data; }; this.instanceOf = options['instanceOf'] || null; this.predicate = options['predicate'] || null; this.represent = options['represent'] || null; this.defaultStyle = options['defaultStyle'] || null; this.styleAliases = compileStyleAliases(options['styleAliases'] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } } var type = Type; /*eslint-disable max-len*/ function compileList(schema, name, result) { var exclude = []; schema.include.forEach(function (includedSchema) { result = compileList(includedSchema, name, result); }); schema[name].forEach(function (currentType) { result.forEach(function (previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { exclude.push(previousIndex); } }); result.push(currentType); }); return result.filter(function (type, index) { return exclude.indexOf(index) === -1; }); } function compileMap(/* lists... */) { var result = { scalar: {}, sequence: {}, mapping: {}, fallback: {} }, index, length; function collectType(type) { result[type.kind][type.tag] = result['fallback'][type.tag] = type; } for (index = 0, length = arguments.length; index < length; index += 1) { arguments[index].forEach(collectType); } return result; } function Schema(definition) { this.include = definition.include || []; this.implicit = definition.implicit || []; this.explicit = definition.explicit || []; this.implicit.forEach(function (type) { if (type.loadKind && type.loadKind !== 'scalar') { throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); } }); this.compiledImplicit = compileList(this, 'implicit', []); this.compiledExplicit = compileList(this, 'explicit', []); this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); } Schema.DEFAULT = null; Schema.create = function createSchema() { var schemas, types; switch (arguments.length) { case 1: schemas = Schema.DEFAULT; types = arguments[0]; break; case 2: schemas = arguments[0]; types = arguments[1]; break; default: throw new exception('Wrong number of arguments for Schema.create function'); } schemas = common.toArray(schemas); types = common.toArray(types); if (!schemas.every(function (schema) { return schema instanceof Schema; })) { throw new exception('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); } if (!types.every(function (type$1) { return type$1 instanceof type; })) { throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } return new Schema({ include: schemas, explicit: types }); }; var schema = Schema; var str = new type('tag:yaml.org,2002:str', { kind: 'scalar', construct: function (data) { return data !== null ? data : ''; } }); var seq = new type('tag:yaml.org,2002:seq', { kind: 'sequence', construct: function (data) { return data !== null ? data : []; } }); var map = new type('tag:yaml.org,2002:map', { kind: 'mapping', construct: function (data) { return data !== null ? data : {}; } }); var failsafe = new schema({ explicit: [ str, seq, map ] }); function resolveYamlNull(data) { if (data === null) return true; var max = data.length; return (max === 1 && data === '~') || (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); } function constructYamlNull() { return null; } function isNull(object) { return object === null; } var _null = new type('tag:yaml.org,2002:null', { kind: 'scalar', resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function () { return '~'; }, lowercase: function () { return 'null'; }, uppercase: function () { return 'NULL'; }, camelcase: function () { return 'Null'; } }, defaultStyle: 'lowercase' }); function resolveYamlBoolean(data) { if (data === null) return false; var max = data.length; return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } function constructYamlBoolean(data) { return data === 'true' || data === 'True' || data === 'TRUE'; } function isBoolean(object) { return Object.prototype.toString.call(object) === '[object Boolean]'; } var bool = new type('tag:yaml.org,2002:bool', { kind: 'scalar', resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function (object) { return object ? 'true' : 'false'; }, uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, camelcase: function (object) { return object ? 'True' : 'False'; } }, defaultStyle: 'lowercase' }); function isHexCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || ((0x61/* a */ <= c) && (c <= 0x66/* f */)); } function isOctCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); } function isDecCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); } function resolveYamlInteger(data) { if (data === null) return false; var max = data.length, index = 0, hasDigits = false, ch; if (!max) return false; ch = data[index]; // sign if (ch === '-' || ch === '+') { ch = data[++index]; } if (ch === '0') { // 0 if (index + 1 === max) return true; ch = data[++index]; // base 2, base 8, base 16 if (ch === 'b') { // base 2 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (ch !== '0' && ch !== '1') return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'x') { // base 16 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isHexCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } // base 8 for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isOctCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } // base 10 (except 0) or base 60 // value should not start with `_`; if (ch === '_') return false; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (ch === ':') break; if (!isDecCode(data.charCodeAt(index))) { return false; } hasDigits = true; } // Should have digits and should not end with `_` if (!hasDigits || ch === '_') return false; // if !base60 - done; if (ch !== ':') return true; // base60 almost not used, no needs to optimize return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); } function constructYamlInteger(data) { var value = data, sign = 1, ch, base, digits = []; if (value.indexOf('_') !== -1) { value = value.replace(/_/g, ''); } ch = value[0]; if (ch === '-' || ch === '+') { if (ch === '-') sign = -1; value = value.slice(1); ch = value[0]; } if (value === '0') return 0; if (ch === '0') { if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); if (value[1] === 'x') return sign * parseInt(value, 16); return sign * parseInt(value, 8); } if (value.indexOf(':') !== -1) { value.split(':').forEach(function (v) { digits.unshift(parseInt(v, 10)); }); value = 0; base = 1; digits.forEach(function (d) { value += (d * base); base *= 60; }); return sign * value; } return sign * parseInt(value, 10); } function isInteger(object) { return (Object.prototype.toString.call(object)) === '[object Number]' && (object % 1 === 0 && !common.isNegativeZero(object)); } var int_1 = new type('tag:yaml.org,2002:int', { kind: 'scalar', resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, decimal: function (obj) { return obj.toString(10); }, /* eslint-disable max-len */ hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } }, defaultStyle: 'decimal', styleAliases: { binary: [ 2, 'bin' ], octal: [ 8, 'oct' ], decimal: [ 10, 'dec' ], hexadecimal: [ 16, 'hex' ] } }); var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + // .2e4, .2 // special case, seems not from spec '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + // 20:59 '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + // .inf '|[-+]?\\.(?:inf|Inf|INF)' + // .nan '|\\.(?:nan|NaN|NAN))$'); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` // Probably should update regexp & check speed data[data.length - 1] === '_') { return false; } return true; } function constructYamlFloat(data) { var value, sign, base, digits; value = data.replace(/_/g, '').toLowerCase(); sign = value[0] === '-' ? -1 : 1; digits = []; if ('+-'.indexOf(value[0]) >= 0) { value = value.slice(1); } if (value === '.inf') { return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; } else if (value === '.nan') { return NaN; } else if (value.indexOf(':') >= 0) { value.split(':').forEach(function (v) { digits.unshift(parseFloat(v, 10)); }); value = 0.0; base = 1; digits.forEach(function (d) { value += d * base; base *= 60; }); return sign * value; } return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { var res; if (isNaN(object)) { switch (style) { case 'lowercase': return '.nan'; case 'uppercase': return '.NAN'; case 'camelcase': return '.NaN'; } } else if (Number.POSITIVE_INFINITY === object) { switch (style) { case 'lowercase': return '.inf'; case 'uppercase': return '.INF'; case 'camelcase': return '.Inf'; } } else if (Number.NEGATIVE_INFINITY === object) { switch (style) { case 'lowercase': return '-.inf'; case 'uppercase': return '-.INF'; case 'camelcase': return '-.Inf'; } } else if (common.isNegativeZero(object)) { return '-0.0'; } res = object.toString(10); // JS stringifier can build scientific format without dots: 5e-100, // while YAML requres dot: 5.e-100. Fix it with simple hack return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; } function isFloat(object) { return (Object.prototype.toString.call(object) === '[object Number]') && (object % 1 !== 0 || common.isNegativeZero(object)); } var float_1 = new type('tag:yaml.org,2002:float', { kind: 'scalar', resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: 'lowercase' }); var json = new schema({ include: [ failsafe ], implicit: [ _null, bool, int_1, float_1 ] }); var core = new schema({ include: [ json ] }); var YAML_DATE_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9])' + // [2] month '-([0-9][0-9])$'); // [3] day var YAML_TIMESTAMP_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9]?)' + // [2] month '-([0-9][0-9]?)' + // [3] day '(?:[Tt]|[ \\t]+)' + // ... '([0-9][0-9]?)' + // [4] hour ':([0-9][0-9])' + // [5] minute ':([0-9][0-9])' + // [6] second '(?:\\.([0-9]*))?' + // [7] fraction '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour '(?::([0-9][0-9]))?))?$'); // [11] tz_minute function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } function constructYamlTimestamp(data) { var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date; match = YAML_DATE_REGEXP.exec(data); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); if (match === null) throw new Error('Date resolve error'); // match: [1] year [2] month [3] day year = +(match[1]); month = +(match[2]) - 1; // JS month starts with 0 day = +(match[3]); if (!match[4]) { // no hour return new Date(Date.UTC(year, month, day)); } // match: [4] hour [5] minute [6] second [7] fraction hour = +(match[4]); minute = +(match[5]); second = +(match[6]); if (match[7]) { fraction = match[7].slice(0, 3); while (fraction.length < 3) { // milli-seconds fraction += '0'; } fraction = +fraction; } // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute if (match[9]) { tz_hour = +(match[10]); tz_minute = +(match[11] || 0); delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds if (match[9] === '-') delta = -delta; } date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } function representYamlTimestamp(object /*, style*/) { return object.toISOString(); } var timestamp = new type('tag:yaml.org,2002:timestamp', { kind: 'scalar', resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); function resolveYamlMerge(data) { return data === '<<' || data === null; } var merge = new type('tag:yaml.org,2002:merge', { kind: 'scalar', resolve: resolveYamlMerge }); /*eslint-disable no-bitwise*/ var NodeBuffer; try { // A trick for browserified version, to not include `Buffer` shim var _require = commonjsRequire; NodeBuffer = _require('buffer').Buffer; } catch (__) {} // [ 64, 65, 66 ] -> [ padding, CR, LF ] var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; function resolveYamlBinary(data) { if (data === null) return false; var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; // Convert one by one. for (idx = 0; idx < max; idx++) { code = map.indexOf(data.charAt(idx)); // Skip CR/LF if (code > 64) continue; // Fail on illegal characters if (code < 0) return false; bitlen += 6; } // If there are any bits left, source was corrupted return (bitlen % 8) === 0; } function constructYamlBinary(data) { var idx, tailbits, input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan max = input.length, map = BASE64_MAP, bits = 0, result = []; // Collect by 6*4 bits (3 bytes) for (idx = 0; idx < max; idx++) { if ((idx % 4 === 0) && idx) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } bits = (bits << 6) | map.indexOf(input.charAt(idx)); } // Dump tail tailbits = (max % 4) * 6; if (tailbits === 0) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } else if (tailbits === 18) { result.push((bits >> 10) & 0xFF); result.push((bits >> 2) & 0xFF); } else if (tailbits === 12) { result.push((bits >> 4) & 0xFF); } // Wrap into Buffer for NodeJS and leave Array for browser if (NodeBuffer) { // Support node 6.+ Buffer API when available return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); } return result; } function representYamlBinary(object /*, style*/) { var result = '', bits = 0, idx, tail, max = object.length, map = BASE64_MAP; // Convert every three bytes to 4 ASCII characters. for (idx = 0; idx < max; idx++) { if ((idx % 3 === 0) && idx) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } bits = (bits << 8) + object[idx]; } // Dump tail tail = max % 3; if (tail === 0) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } else if (tail === 2) { result += map[(bits >> 10) & 0x3F]; result += map[(bits >> 4) & 0x3F]; result += map[(bits << 2) & 0x3F]; result += map[64]; } else if (tail === 1) { result += map[(bits >> 2) & 0x3F]; result += map[(bits << 4) & 0x3F]; result += map[64]; result += map[64]; } return result; } function isBinary(object) { return NodeBuffer && NodeBuffer.isBuffer(object); } var binary = new type('tag:yaml.org,2002:binary', { kind: 'scalar', resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); var _hasOwnProperty = Object.prototype.hasOwnProperty; var _toString = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data; for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; pairHasKey = false; if (_toString.call(pair) !== '[object Object]') return false; for (pairKey in pair) { if (_hasOwnProperty.call(pair, pairKey)) { if (!pairHasKey) pairHasKey = true; else return false; } } if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } function constructYamlOmap(data) { return data !== null ? data : []; } var omap = new type('tag:yaml.org,2002:omap', { kind: 'sequence', resolve: resolveYamlOmap, construct: constructYamlOmap }); var _toString$1 = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; if (_toString$1.call(pair) !== '[object Object]') return false; keys = Object.keys(pair); if (keys.length !== 1) return false; result[index] = [ keys[0], pair[keys[0]] ]; } return true; } function constructYamlPairs(data) { if (data === null) return []; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; keys = Object.keys(pair); result[index] = [ keys[0], pair[keys[0]] ]; } return result; } var pairs = new type('tag:yaml.org,2002:pairs', { kind: 'sequence', resolve: resolveYamlPairs, construct: constructYamlPairs }); var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; var key, object = data; for (key in object) { if (_hasOwnProperty$1.call(object, key)) { if (object[key] !== null) return false; } } return true; } function constructYamlSet(data) { return data !== null ? data : {}; } var set = new type('tag:yaml.org,2002:set', { kind: 'mapping', resolve: resolveYamlSet, construct: constructYamlSet }); var default_safe = new schema({ include: [ core ], implicit: [ timestamp, merge ], explicit: [ binary, omap, pairs, set ] }); function resolveJavascriptUndefined() { return true; } function constructJavascriptUndefined() { /*eslint-disable no-undefined*/ return undefined; } function representJavascriptUndefined() { return ''; } function isUndefined(object) { return typeof object === 'undefined'; } var _undefined = new type('tag:yaml.org,2002:js/undefined', { kind: 'scalar', resolve: resolveJavascriptUndefined, construct: constructJavascriptUndefined, predicate: isUndefined, represent: representJavascriptUndefined }); function resolveJavascriptRegExp(data) { if (data === null) return false; if (data.length === 0) return false; var regexp = data, tail = /\/([gim]*)$/.exec(data), modifiers = ''; // if regexp starts with '/' it can have modifiers and must be properly closed // `/foo/gim` - modifiers tail can be maximum 3 chars if (regexp[0] === '/') { if (tail) modifiers = tail[1]; if (modifiers.length > 3) return false; // if expression starts with /, is should be properly terminated if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; } return true; } function constructJavascriptRegExp(data) { var regexp = data, tail = /\/([gim]*)$/.exec(data), modifiers = ''; // `/foo/gim` - tail can be maximum 4 chars if (regexp[0] === '/') { if (tail) modifiers = tail[1]; regexp = regexp.slice(1, regexp.length - modifiers.length - 1); } return new RegExp(regexp, modifiers); } function representJavascriptRegExp(object /*, style*/) { var result = '/' + object.source + '/'; if (object.global) result += 'g'; if (object.multiline) result += 'm'; if (object.ignoreCase) result += 'i'; return result; } function isRegExp(object) { return Object.prototype.toString.call(object) === '[object RegExp]'; } var regexp = new type('tag:yaml.org,2002:js/regexp', { kind: 'scalar', resolve: resolveJavascriptRegExp, construct: constructJavascriptRegExp, predicate: isRegExp, represent: representJavascriptRegExp }); var esprima; // Browserified version does not have esprima // // 1. For node.js just require module as deps // 2. For browser try to require mudule via external AMD system. // If not found - try to fallback to window.esprima. If not // found too - then fail to parse. // try { // workaround to exclude package from browserify list. var _require$1 = commonjsRequire; esprima = _require$1('esprima'); } catch (_) { /* eslint-disable no-redeclare */ /* global window */ if (typeof window !== 'undefined') esprima = window.esprima; } function resolveJavascriptFunction(data) { if (data === null) return false; try { var source = '(' + data + ')', ast = esprima.parse(source, { range: true }); if (ast.type !== 'Program' || ast.body.length !== 1 || ast.body[0].type !== 'ExpressionStatement' || (ast.body[0].expression.type !== 'ArrowFunctionExpression' && ast.body[0].expression.type !== 'FunctionExpression')) { return false; } return true; } catch (err) { return false; } } function constructJavascriptFunction(data) { /*jslint evil:true*/ var source = '(' + data + ')', ast = esprima.parse(source, { range: true }), params = [], body; if (ast.type !== 'Program' || ast.body.length !== 1 || ast.body[0].type !== 'ExpressionStatement' || (ast.body[0].expression.type !== 'ArrowFunctionExpression' && ast.body[0].expression.type !== 'FunctionExpression')) { throw new Error('Failed to resolve function'); } ast.body[0].expression.params.forEach(function (param) { params.push(param.name); }); body = ast.body[0].expression.body.range; // Esprima's ranges include the first '{' and the last '}' characters on // function expressions. So cut them out. if (ast.body[0].expression.body.type === 'BlockStatement') { /*eslint-disable no-new-func*/ return new Function(params, source.slice(body[0] + 1, body[1] - 1)); } // ES6 arrow functions can omit the BlockStatement. In that case, just return // the body. /*eslint-disable no-new-func*/ return new Function(params, 'return ' + source.slice(body[0], body[1])); } function representJavascriptFunction(object /*, style*/) { return object.toString(); } function isFunction(object) { return Object.prototype.toString.call(object) === '[object Function]'; } var _function = new type('tag:yaml.org,2002:js/function', { kind: 'scalar', resolve: resolveJavascriptFunction, construct: constructJavascriptFunction, predicate: isFunction, represent: representJavascriptFunction }); var default_full = schema.DEFAULT = new schema({ include: [ default_safe ], explicit: [ _undefined, regexp, _function ] }); /*eslint-disable max-len,no-use-before-define*/ var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } function is_EOL(c) { return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_WHITE_SPACE(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */); } function is_WS_OR_EOL(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */) || (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_FLOW_INDICATOR(c) { return c === 0x2C/* , */ || c === 0x5B/* [ */ || c === 0x5D/* ] */ || c === 0x7B/* { */ || c === 0x7D/* } */; } function fromHexCode(c) { var lc; if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } /*eslint-disable no-bitwise*/ lc = c | 0x20; if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { return lc - 0x61 + 10; } return -1; } function escapedHexLen(c) { if (c === 0x78/* x */) { return 2; } if (c === 0x75/* u */) { return 4; } if (c === 0x55/* U */) { return 8; } return 0; } function fromDecimalCode(c) { if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } return -1; } function simpleEscapeSequence(c) { /* eslint-disable indent */ return (c === 0x30/* 0 */) ? '\x00' : (c === 0x61/* a */) ? '\x07' : (c === 0x62/* b */) ? '\x08' : (c === 0x74/* t */) ? '\x09' : (c === 0x09/* Tab */) ? '\x09' : (c === 0x6E/* n */) ? '\x0A' : (c === 0x76/* v */) ? '\x0B' : (c === 0x66/* f */) ? '\x0C' : (c === 0x72/* r */) ? '\x0D' : (c === 0x65/* e */) ? '\x1B' : (c === 0x20/* Space */) ? ' ' : (c === 0x22/* " */) ? '\x22' : (c === 0x2F/* / */) ? '/' : (c === 0x5C/* \ */) ? '\x5C' : (c === 0x4E/* N */) ? '\x85' : (c === 0x5F/* _ */) ? '\xA0' : (c === 0x4C/* L */) ? '\u2028' : (c === 0x50/* P */) ? '\u2029' : ''; } function charFromCodepoint(c) { if (c <= 0xFFFF) { return String.fromCharCode(c); } // Encode UTF-16 surrogate pair // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF return String.fromCharCode( ((c - 0x010000) >> 10) + 0xD800, ((c - 0x010000) & 0x03FF) + 0xDC00 ); } var simpleEscapeCheck = new Array(256); // integer, for fast access var simpleEscapeMap = new Array(256); for (var i = 0; i < 256; i++) { simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; simpleEscapeMap[i] = simpleEscapeSequence(i); } function State(input, options) { this.input = input; this.filename = options['filename'] || null; this.schema = options['schema'] || default_full; this.onWarning = options['onWarning'] || null; this.legacy = options['legacy'] || false; this.json = options['json'] || false; this.listener = options['listener'] || null; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; this.documents = []; /* this.version; this.checkLineBreaks; this.tagMap; this.anchorMap; this.tag; this.anchor; this.kind; this.result;*/ } function generateError(state, message) { return new exception( message, new mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); } function throwError(state, message) { throw generateError(state, message); } function throwWarning(state, message) { if (state.onWarning) { state.onWarning.call(null, generateError(state, message)); } } var directiveHandlers = { YAML: function handleYamlDirective(state, name, args) { var match, major, minor; if (state.version !== null) { throwError(state, 'duplication of %YAML directive'); } if (args.length !== 1) { throwError(state, 'YAML directive accepts exactly one argument'); } match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) { throwError(state, 'ill-formed argument of the YAML directive'); } major = parseInt(match[1], 10); minor = parseInt(match[2], 10); if (major !== 1) { throwError(state, 'unacceptable YAML version of the document'); } state.version = args[0]; state.checkLineBreaks = (minor < 2); if (minor !== 1 && minor !== 2) { throwWarning(state, 'unsupported YAML version of the document'); } }, TAG: function handleTagDirective(state, name, args) { var handle, prefix; if (args.length !== 2) { throwError(state, 'TAG directive accepts exactly two arguments'); } handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) { throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); } if (_hasOwnProperty$2.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } if (!PATTERN_TAG_URI.test(prefix)) { throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); } state.tagMap[handle] = prefix; } }; function captureSegment(state, start, end, checkJson) { var _position, _length, _character, _result; if (start < end) { _result = state.input.slice(start, end); if (checkJson) { for (_position = 0, _length = _result.length; _position < _length; _position += 1) { _character = _result.charCodeAt(_position); if (!(_character === 0x09 || (0x20 <= _character && _character <= 0x10FFFF))) { throwError(state, 'expected valid JSON character'); } } } else if (PATTERN_NON_PRINTABLE.test(_result)) { throwError(state, 'the stream contains non-printable characters'); } state.result += _result; } } function mergeMappings(state, destination, source, overridableKeys) { var sourceKeys, key, index, quantity; if (!common.isObject(source)) { throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); } sourceKeys = Object.keys(source); for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { key = sourceKeys[index]; if (!_hasOwnProperty$2.call(destination, key)) { destination[key] = source[key]; overridableKeys[key] = true; } } } function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { var index, quantity; // The output is a plain object here, so keys can only be strings. // We need to convert keyNode to a string, but doing so can hang the process // (deeply nested arrays that explode exponentially using aliases). if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) { throwError(state, 'nested arrays are not supported inside keys'); } if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { keyNode[index] = '[object Object]'; } } } // Avoid code execution in load() via toString property // (still use its own toString for arrays, timestamps, // and whatever user schema extensions happen to have @@toStringTag) if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { keyNode = '[object Object]'; } keyNode = String(keyNode); if (_result === null) { _result = {}; } if (keyTag === 'tag:yaml.org,2002:merge') { if (Array.isArray(valueNode)) { for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { mergeMappings(state, _result, valueNode[index], overridableKeys); } } else { mergeMappings(state, _result, valueNode, overridableKeys); } } else { if (!state.json && !_hasOwnProperty$2.call(overridableKeys, keyNode) && _hasOwnProperty$2.call(_result, keyNode)) { state.line = startLine || state.line; state.position = startPos || state.position; throwError(state, 'duplicated mapping key'); } _result[keyNode] = valueNode; delete overridableKeys[keyNode]; } return _result; } function readLineBreak(state) { var ch; ch = state.input.charCodeAt(state.position); if (ch === 0x0A/* LF */) { state.position++; } else if (ch === 0x0D/* CR */) { state.position++; if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { state.position++; } } else { throwError(state, 'a line break is expected'); } state.line += 1; state.lineStart = state.position; } function skipSeparationSpace(state, allowComments, checkIndent) { var lineBreaks = 0, ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); } if (is_EOL(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 0x20/* Space */) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else { break; } } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { throwWarning(state, 'deficient indentation'); } return lineBreaks; } function testDocumentSeparator(state) { var _position = state.position, ch; ch = state.input.charCodeAt(_position); // Condition state.position === state.lineStart is tested // in parent on each call, for efficiency. No needs to test here again. if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || is_WS_OR_EOL(ch)) { return true; } } return false; } function writeFoldedLines(state, count) { if (count === 1) { state.result += ' '; } else if (count > 1) { state.result += common.repeat('\n', count - 1); } } function readPlainScalar(state, nodeIndent, withinFlowCollection) { var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; ch = state.input.charCodeAt(state.position); if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 0x23/* # */ || ch === 0x26/* & */ || ch === 0x2A/* * */ || ch === 0x21/* ! */ || ch === 0x7C/* | */ || ch === 0x3E/* > */ || ch === 0x27/* ' */ || ch === 0x22/* " */ || ch === 0x25/* % */ || ch === 0x40/* @ */ || ch === 0x60/* ` */) { return false; } if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { return false; } } state.kind = 'scalar'; state.result = ''; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 0x3A/* : */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { break; } } else if (ch === 0x23/* # */) { preceding = state.input.charCodeAt(state.position - 1); if (is_WS_OR_EOL(preceding)) { break; } } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || withinFlowCollection && is_FLOW_INDICATOR(ch)) { break; } else if (is_EOL(ch)) { _line = state.line; _lineStart = state.lineStart; _lineIndent = state.lineIndent; skipSeparationSpace(state, false, -1); if (state.lineIndent >= nodeIndent) { hasPendingContent = true; ch = state.input.charCodeAt(state.position); continue; } else { state.position = captureEnd; state.line = _line; state.lineStart = _lineStart; state.lineIndent = _lineIndent; break; } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false); writeFoldedLines(state, state.line - _line); captureStart = captureEnd = state.position; hasPendingContent = false; } if (!is_WHITE_SPACE(ch)) { captureEnd = state.position + 1; } ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, captureEnd, false); if (state.result) { return true; } state.kind = _kind; state.result = _result; return false; } function readSingleQuotedScalar(state, nodeIndent) { var ch, captureStart, captureEnd; ch = state.input.charCodeAt(state.position); if (ch !== 0x27/* ' */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x27/* ' */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (ch === 0x27/* ' */) { captureStart = state.position; state.position++; captureEnd = state.position; } else { return true; } } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a single quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a single quoted scalar'); } function readDoubleQuotedScalar(state, nodeIndent) { var captureStart, captureEnd, hexLength, hexResult, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x22/* " */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x22/* " */) { captureSegment(state, captureStart, state.position, true); state.position++; return true; } else if (ch === 0x5C/* \ */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (is_EOL(ch)) { skipSeparationSpace(state, false, nodeIndent); // TODO: rework to inline fn with no type cast? } else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch]; state.position++; } else if ((tmp = escapedHexLen(ch)) > 0) { hexLength = tmp; hexResult = 0; for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position); if ((tmp = fromHexCode(ch)) >= 0) { hexResult = (hexResult << 4) + tmp; } else { throwError(state, 'expected hexadecimal character'); } } state.result += charFromCodepoint(hexResult); state.position++; } else { throwError(state, 'unknown escape sequence'); } captureStart = captureEnd = state.position; } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a double quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a double quoted scalar'); } function readFlowCollection(state, nodeIndent) { var readNext = true, _line, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = {}, keyNode, keyTag, valueNode, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x5B/* [ */) { terminator = 0x5D;/* ] */ isMapping = false; _result = []; } else if (ch === 0x7B/* { */) { terminator = 0x7D;/* } */ isMapping = true; _result = {}; } else { return false; } if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(++state.position); while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === terminator) { state.position++; state.tag = _tag; state.anchor = _anchor; state.kind = isMapping ? 'mapping' : 'sequence'; state.result = _result; return true; } else if (!readNext) { throwError(state, 'missed comma between flow collection entries'); } keyTag = keyNode = valueNode = null; isPair = isExplicitPair = false; if (ch === 0x3F/* ? */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following)) { isPair = isExplicitPair = true; state.position++; skipSeparationSpace(state, true, nodeIndent); } } _line = state.line; composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); keyTag = state.tag; keyNode = state.result; skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { isPair = true; ch = state.input.charCodeAt(++state.position); skipSeparationSpace(state, true, nodeIndent); composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); valueNode = state.result; } if (isMapping) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); } else if (isPair) { _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); } else { _result.push(keyNode); } skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === 0x2C/* , */) { readNext = true; ch = state.input.charCodeAt(++state.position); } else { readNext = false; } } throwError(state, 'unexpected end of the stream within a flow collection'); } function readBlockScalar(state, nodeIndent) { var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x7C/* | */) { folding = false; } else if (ch === 0x3E/* > */) { folding = true; } else { return false; } state.kind = 'scalar'; state.result = ''; while (ch !== 0) { ch = state.input.charCodeAt(++state.position); if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { if (CHOMPING_CLIP === chomping) { chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; } else { throwError(state, 'repeat of a chomping mode identifier'); } } else if ((tmp = fromDecimalCode(ch)) >= 0) { if (tmp === 0) { throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); } else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; detectedIndent = true; } else { throwError(state, 'repeat of an indentation width identifier'); } } else { break; } } if (is_WHITE_SPACE(ch)) { do { ch = state.input.charCodeAt(++state.position); } while (is_WHITE_SPACE(ch)); if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (!is_EOL(ch) && (ch !== 0)); } } while (ch !== 0) { readLineBreak(state); state.lineIndent = 0; ch = state.input.charCodeAt(state.position); while ((!detectedIndent || state.lineIndent < textIndent) && (ch === 0x20/* Space */)) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } if (!detectedIndent && state.lineIndent > textIndent) { textIndent = state.lineIndent; } if (is_EOL(ch)) { emptyLines++; continue; } // End of the scalar. if (state.lineIndent < textIndent) { // Perform the chomping. if (chomping === CHOMPING_KEEP) { state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } else if (chomping === CHOMPING_CLIP) { if (didReadContent) { // i.e. only if the scalar is not empty. state.result += '\n'; } } // Break this `while` cycle and go to the funciton's epilogue. break; } // Folded style: use fancy rules to handle line breaks. if (folding) { // Lines starting with white space characters (more-indented lines) are not folded. if (is_WHITE_SPACE(ch)) { atMoreIndented = true; // except for the first content line (cf. Example 8.1) state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); // End of more-indented block. } else if (atMoreIndented) { atMoreIndented = false; state.result += common.repeat('\n', emptyLines + 1); // Just one line break - perceive as the same line. } else if (emptyLines === 0) { if (didReadContent) { // i.e. only if we have already read some scalar content. state.result += ' '; } // Several line breaks - perceive as different lines. } else { state.result += common.repeat('\n', emptyLines); } // Literal style: just add exact number of line breaks between content lines. } else { // Keep all line breaks except the header line break. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } didReadContent = true; detectedIndent = true; emptyLines = 0; captureStart = state.position; while (!is_EOL(ch) && (ch !== 0)) { ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, state.position, false); } return true; } function readBlockSequence(state, nodeIndent) { var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (ch !== 0x2D/* - */) { break; } following = state.input.charCodeAt(state.position + 1); if (!is_WS_OR_EOL(following)) { break; } detected = true; state.position++; if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null); ch = state.input.charCodeAt(state.position); continue; } } _line = state.line; composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); _result.push(state.result); skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a sequence entry'); } else if (state.lineIndent < nodeIndent) { break; } } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'sequence'; state.result = _result; return true; } return false; } function readBlockMapping(state, nodeIndent, flowIndent) { var following, allowCompact, _line, _pos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = {}, keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { following = state.input.charCodeAt(state.position + 1); _line = state.line; // Save the current line. _pos = state.position; // // Explicit notation case. There are two separate blocks: // first for the key (denoted by "?") and second for the value (denoted by ":") // if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { if (ch === 0x3F/* ? */) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = true; allowCompact = true; } else if (atExplicitKey) { // i.e. 0x3A/* : */ === character after the explicit key. atExplicitKey = false; allowCompact = true; } else { throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); } state.position += 1; ch = following; // // Implicit notation case. Flow-style node as the key first, then ":", and the value. // } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { if (state.line === _line) { ch = state.input.charCodeAt(state.position); while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x3A/* : */) { ch = state.input.charCodeAt(++state.position); if (!is_WS_OR_EOL(ch)) { throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = false; allowCompact = false; keyTag = state.tag; keyNode = state.result; } else if (detected) { throwError(state, 'can not read an implicit mapping pair; a colon is missed'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } else if (detected) { throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } else { break; // Reading is done. Go to the epilogue. } // // Common reading code for both explicit and implicit notations. // if (state.line === _line || state.lineIndent > nodeIndent) { if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { if (atExplicitKey) { keyNode = state.result; } else { valueNode = state.result; } } if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); keyTag = keyNode = valueNode = null; } skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); } if (state.lineIndent > nodeIndent && (ch !== 0)) { throwError(state, 'bad indentation of a mapping entry'); } else if (state.lineIndent < nodeIndent) { break; } } // // Epilogue. // // Special case: last mapping's node contains only the key in explicit notation. if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); } // Expose the resulting mapping. if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'mapping'; state.result = _result; } return detected; } function readTagProperty(state) { var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x21/* ! */) return false; if (state.tag !== null) { throwError(state, 'duplication of a tag property'); } ch = state.input.charCodeAt(++state.position); if (ch === 0x3C/* < */) { isVerbatim = true; ch = state.input.charCodeAt(++state.position); } else if (ch === 0x21/* ! */) { isNamed = true; tagHandle = '!!'; ch = state.input.charCodeAt(++state.position); } else { tagHandle = '!'; } _position = state.position; if (isVerbatim) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && ch !== 0x3E/* > */); if (state.position < state.length) { tagName = state.input.slice(_position, state.position); ch = state.input.charCodeAt(++state.position); } else { throwError(state, 'unexpected end of the stream within a verbatim tag'); } } else { while (ch !== 0 && !is_WS_OR_EOL(ch)) { if (ch === 0x21/* ! */) { if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) { throwError(state, 'named tag handle cannot contain such characters'); } isNamed = true; _position = state.position + 1; } else { throwError(state, 'tag suffix cannot contain exclamation marks'); } } ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(_position, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) { throwError(state, 'tag suffix cannot contain flow indicator characters'); } } if (tagName && !PATTERN_TAG_URI.test(tagName)) { throwError(state, 'tag name cannot contain such characters: ' + tagName); } if (isVerbatim) { state.tag = tagName; } else if (_hasOwnProperty$2.call(state.tagMap, tagHandle)) { state.tag = state.tagMap[tagHandle] + tagName; } else if (tagHandle === '!') { state.tag = '!' + tagName; } else if (tagHandle === '!!') { state.tag = 'tag:yaml.org,2002:' + tagName; } else { throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } return true; } function readAnchorProperty(state) { var _position, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x26/* & */) return false; if (state.anchor !== null) { throwError(state, 'duplication of an anchor property'); } ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an anchor node must contain at least one character'); } state.anchor = state.input.slice(_position, state.position); return true; } function readAlias(state) { var _position, alias, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x2A/* * */) return false; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an alias node must contain at least one character'); } alias = state.input.slice(_position, state.position); if (!state.anchorMap.hasOwnProperty(alias)) { throwError(state, 'unidentified alias "' + alias + '"'); } state.result = state.anchorMap[alias]; skipSeparationSpace(state, true, -1); return true; } function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } } if (indentStatus === 1) { while (readTagProperty(state) || readAnchorProperty(state)) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } else { allowBlockCollections = false; } } } if (allowBlockCollections) { allowBlockCollections = atNewLine || allowCompact; } if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { flowIndent = parentIndent; } else { flowIndent = parentIndent + 1; } blockIndent = state.position - state.lineStart; if (indentStatus === 1) { if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) { hasContent = true; } else { if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { hasContent = true; } else if (readAlias(state)) { hasContent = true; if (state.tag !== null || state.anchor !== null) { throwError(state, 'alias node should not have any properties'); } } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true; if (state.tag === null) { state.tag = '?'; } } if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } else if (indentStatus === 0) { // Special case: block sequences are allowed to have same indentation level as the parent. // http://www.yaml.org/spec/1.2/spec.html#id2799784 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } if (state.tag !== null && state.tag !== '!') { if (state.tag === '?') { // Implicit resolving is not allowed for non-scalar types, and '?' // non-specific tag is only automatically assigned to plain scalars. // // We only need to check kind conformity in case user explicitly assigns '?' // tag, for example like this: "! [0]" // if (state.result !== null && state.kind !== 'scalar') { throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); } for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type = state.implicitTypes[typeIndex]; if (type.resolve(state.result)) { // `state.result` updated in resolver if matched state.result = type.construct(state.result); state.tag = type.tag; if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } break; } } } else if (_hasOwnProperty$2.call(state.typeMap[state.kind || 'fallback'], state.tag)) { type = state.typeMap[state.kind || 'fallback'][state.tag]; if (state.result !== null && type.kind !== state.kind) { throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); } if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); } else { state.result = type.construct(state.result); if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } else { throwError(state, 'unknown tag !<' + state.tag + '>'); } } if (state.listener !== null) { state.listener('close', state); } return state.tag !== null || state.anchor !== null || hasContent; } function readDocument(state) { var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch; state.version = null; state.checkLineBreaks = state.legacy; state.tagMap = {}; state.anchorMap = {}; while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if (state.lineIndent > 0 || ch !== 0x25/* % */) { break; } hasDirectives = true; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveName = state.input.slice(_position, state.position); directiveArgs = []; if (directiveName.length < 1) { throwError(state, 'directive name must not be less than one character in length'); } while (ch !== 0) { while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && !is_EOL(ch)); break; } if (is_EOL(ch)) break; _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveArgs.push(state.input.slice(_position, state.position)); } if (ch !== 0) readLineBreak(state); if (_hasOwnProperty$2.call(directiveHandlers, directiveName)) { directiveHandlers[directiveName](state, directiveName, directiveArgs); } else { throwWarning(state, 'unknown document directive "' + directiveName + '"'); } } skipSeparationSpace(state, true, -1); if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2D/* - */ && state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { state.position += 3; skipSeparationSpace(state, true, -1); } else if (hasDirectives) { throwError(state, 'directives end mark is expected'); } composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); skipSeparationSpace(state, true, -1); if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { throwWarning(state, 'non-ASCII line breaks are interpreted as content'); } state.documents.push(state.result); if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 0x2E/* . */) { state.position += 3; skipSeparationSpace(state, true, -1); } return; } if (state.position < (state.length - 1)) { throwError(state, 'end of the stream or a document separator is expected'); } else { return; } } function loadDocuments(input, options) { input = String(input); options = options || {}; if (input.length !== 0) { // Add tailing `\n` if not exists if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { input += '\n'; } // Strip BOM if (input.charCodeAt(0) === 0xFEFF) { input = input.slice(1); } } var state = new State(input, options); var nullpos = input.indexOf('\0'); if (nullpos !== -1) { state.position = nullpos; throwError(state, 'null byte is not allowed in input'); } // Use 0 as string terminator. That significantly simplifies bounds check. state.input += '\0'; while (state.input.charCodeAt(state.position) === 0x20/* Space */) { state.lineIndent += 1; state.position += 1; } while (state.position < (state.length - 1)) { readDocument(state); } return state.documents; } function loadAll(input, iterator, options) { if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { options = iterator; iterator = null; } var documents = loadDocuments(input, options); if (typeof iterator !== 'function') { return documents; } for (var index = 0, length = documents.length; index < length; index += 1) { iterator(documents[index]); } } function load(input, options) { var documents = loadDocuments(input, options); if (documents.length === 0) { /*eslint-disable no-undefined*/ return undefined; } else if (documents.length === 1) { return documents[0]; } throw new exception('expected a single document in the stream, but found more'); } function safeLoadAll(input, iterator, options) { if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { options = iterator; iterator = null; } return loadAll(input, iterator, common.extend({ schema: default_safe }, options)); } function safeLoad(input, options) { return load(input, common.extend({ schema: default_safe }, options)); } var loadAll_1 = loadAll; var load_1 = load; var safeLoadAll_1 = safeLoadAll; var safeLoad_1 = safeLoad; var loader = { loadAll: loadAll_1, load: load_1, safeLoadAll: safeLoadAll_1, safeLoad: safeLoad_1 }; /*eslint-disable no-use-before-define*/ var _toString$2 = Object.prototype.toString; var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; var CHAR_TAB = 0x09; /* Tab */ var CHAR_LINE_FEED = 0x0A; /* LF */ var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ var CHAR_SPACE = 0x20; /* Space */ var CHAR_EXCLAMATION = 0x21; /* ! */ var CHAR_DOUBLE_QUOTE = 0x22; /* " */ var CHAR_SHARP = 0x23; /* # */ var CHAR_PERCENT = 0x25; /* % */ var CHAR_AMPERSAND = 0x26; /* & */ var CHAR_SINGLE_QUOTE = 0x27; /* ' */ var CHAR_ASTERISK = 0x2A; /* * */ var CHAR_COMMA = 0x2C; /* , */ var CHAR_MINUS = 0x2D; /* - */ var CHAR_COLON = 0x3A; /* : */ var CHAR_EQUALS = 0x3D; /* = */ var CHAR_GREATER_THAN = 0x3E; /* > */ var CHAR_QUESTION = 0x3F; /* ? */ var CHAR_COMMERCIAL_AT = 0x40; /* @ */ var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ var CHAR_GRAVE_ACCENT = 0x60; /* ` */ var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ var CHAR_VERTICAL_LINE = 0x7C; /* | */ var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0x00] = '\\0'; ESCAPE_SEQUENCES[0x07] = '\\a'; ESCAPE_SEQUENCES[0x08] = '\\b'; ESCAPE_SEQUENCES[0x09] = '\\t'; ESCAPE_SEQUENCES[0x0A] = '\\n'; ESCAPE_SEQUENCES[0x0B] = '\\v'; ESCAPE_SEQUENCES[0x0C] = '\\f'; ESCAPE_SEQUENCES[0x0D] = '\\r'; ESCAPE_SEQUENCES[0x1B] = '\\e'; ESCAPE_SEQUENCES[0x22] = '\\"'; ESCAPE_SEQUENCES[0x5C] = '\\\\'; ESCAPE_SEQUENCES[0x85] = '\\N'; ESCAPE_SEQUENCES[0xA0] = '\\_'; ESCAPE_SEQUENCES[0x2028] = '\\L'; ESCAPE_SEQUENCES[0x2029] = '\\P'; var DEPRECATED_BOOLEANS_SYNTAX = [ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' ]; function compileStyleMap(schema, map) { var result, keys, index, length, tag, style, type; if (map === null) return {}; result = {}; keys = Object.keys(map); for (index = 0, length = keys.length; index < length; index += 1) { tag = keys[index]; style = String(map[tag]); if (tag.slice(0, 2) === '!!') { tag = 'tag:yaml.org,2002:' + tag.slice(2); } type = schema.compiledTypeMap['fallback'][tag]; if (type && _hasOwnProperty$3.call(type.styleAliases, style)) { style = type.styleAliases[style]; } result[tag] = style; } return result; } function encodeHex(character) { var string, handle, length; string = character.toString(16).toUpperCase(); if (character <= 0xFF) { handle = 'x'; length = 2; } else if (character <= 0xFFFF) { handle = 'u'; length = 4; } else if (character <= 0xFFFFFFFF) { handle = 'U'; length = 8; } else { throw new exception('code point within a string may not be greater than 0xFFFFFFFF'); } return '\\' + handle + common.repeat('0', length - string.length) + string; } function State$1(options) { this.schema = options['schema'] || default_full; this.indent = Math.max(1, (options['indent'] || 2)); this.noArrayIndent = options['noArrayIndent'] || false; this.skipInvalid = options['skipInvalid'] || false; this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); this.styleMap = compileStyleMap(this.schema, options['styles'] || null); this.sortKeys = options['sortKeys'] || false; this.lineWidth = options['lineWidth'] || 80; this.noRefs = options['noRefs'] || false; this.noCompatMode = options['noCompatMode'] || false; this.condenseFlow = options['condenseFlow'] || false; this.implicitTypes = this.schema.compiledImplicit; this.explicitTypes = this.schema.compiledExplicit; this.tag = null; this.result = ''; this.duplicates = []; this.usedDuplicates = null; } // Indents every line in a string. Empty lines (\n only) are not indented. function indentString(string, spaces) { var ind = common.repeat(' ', spaces), position = 0, next = -1, result = '', line, length = string.length; while (position < length) { next = string.indexOf('\n', position); if (next === -1) { line = string.slice(position); position = length; } else { line = string.slice(position, next + 1); position = next + 1; } if (line.length && line !== '\n') result += ind; result += line; } return result; } function generateNextLine(state, level) { return '\n' + common.repeat(' ', state.indent * level); } function testImplicitResolving(state, str) { var index, length, type; for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { type = state.implicitTypes[index]; if (type.resolve(str)) { return true; } } return false; } // [33] s-white ::= s-space | s-tab function isWhitespace(c) { return c === CHAR_SPACE || c === CHAR_TAB; } // Returns true if the character can be printed without escaping. // From YAML 1.2: "any allowed characters known to be non-printable // should also be escaped. [However,] This isn’t mandatory" // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. function isPrintable(c) { return (0x00020 <= c && c <= 0x00007E) || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) || (0x10000 <= c && c <= 0x10FFFF); } // [34] ns-char ::= nb-char - s-white // [27] nb-char ::= c-printable - b-char - c-byte-order-mark // [26] b-char ::= b-line-feed | b-carriage-return // [24] b-line-feed ::= #xA /* LF */ // [25] b-carriage-return ::= #xD /* CR */ // [3] c-byte-order-mark ::= #xFEFF function isNsChar(c) { return isPrintable(c) && !isWhitespace(c) // byte-order-mark && c !== 0xFEFF // b-char && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; } // Simplified test for values allowed after the first character in plain style. function isPlainSafe(c, prev) { // Uses a subset of nb-char - c-flow-indicator - ":" - "#" // where nb-char ::= c-printable - b-char - c-byte-order-mark. return isPrintable(c) && c !== 0xFEFF // - c-flow-indicator && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // - ":" - "#" // /* An ns-char preceding */ "#" && c !== CHAR_COLON && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); } // Simplified test for values allowed as the first character in plain style. function isPlainSafeFirst(c) { // Uses a subset of ns-char - c-indicator // where ns-char = nb-char - s-white. return isPrintable(c) && c !== 0xFEFF && !isWhitespace(c) // - s-white // - (c-indicator ::= // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE // | “%” | “@” | “`”) && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; } // Determines whether block indentation indicator is required. function needIndentIndicator(string) { var leadingSpaceRe = /^\n* /; return leadingSpaceRe.test(string); } var STYLE_PLAIN = 1, STYLE_SINGLE = 2, STYLE_LITERAL = 3, STYLE_FOLDED = 4, STYLE_DOUBLE = 5; // Determines which scalar styles are possible and returns the preferred style. // lineWidth = -1 => no limit. // Pre-conditions: str.length > 0. // Post-conditions: // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { var i; var char, prev_char; var hasLineBreak = false; var hasFoldableLine = false; // only checked if shouldTrackWidth var shouldTrackWidth = lineWidth !== -1; var previousLineBreak = -1; // count the first line correctly var plain = isPlainSafeFirst(string.charCodeAt(0)) && !isWhitespace(string.charCodeAt(string.length - 1)); if (singleLineOnly) { // Case: no block styles. // Check for disallowed characters to rule out plain and single. for (i = 0; i < string.length; i++) { char = string.charCodeAt(i); if (!isPrintable(char)) { return STYLE_DOUBLE; } prev_char = i > 0 ? string.charCodeAt(i - 1) : null; plain = plain && isPlainSafe(char, prev_char); } } else { // Case: block styles permitted. for (i = 0; i < string.length; i++) { char = string.charCodeAt(i); if (char === CHAR_LINE_FEED) { hasLineBreak = true; // Check if any line can be folded. if (shouldTrackWidth) { hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' '); previousLineBreak = i; } } else if (!isPrintable(char)) { return STYLE_DOUBLE; } prev_char = i > 0 ? string.charCodeAt(i - 1) : null; plain = plain && isPlainSafe(char, prev_char); } // in case the end is missing a \n hasFoldableLine = hasFoldableLine || (shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ')); } // Although every style can represent \n without escaping, prefer block styles // for multiline, since they're more readable and they don't add empty lines. // Also prefer folding a super-long line. if (!hasLineBreak && !hasFoldableLine) { // Strings interpretable as another type have to be quoted; // e.g. the string 'true' vs. the boolean true. return plain && !testAmbiguousType(string) ? STYLE_PLAIN : STYLE_SINGLE; } // Edge case: block indentation indicator can only have one digit. if (indentPerLevel > 9 && needIndentIndicator(string)) { return STYLE_DOUBLE; } // At this point we know block styles are valid. // Prefer literal style unless we want to fold. return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; } // Note: line breaking/folding is implemented for only the folded style. // NB. We drop the last trailing newline (if any) of a returned block scalar // since the dumper adds its own newline. This always works: // • No ending newline => unaffected; already using strip "-" chomping. // • Ending newline => removed then restored. // Importantly, this keeps the "+" chomp indicator from gaining an extra line. function writeScalar(state, string, level, iskey) { state.dump = (function () { if (string.length === 0) { return "''"; } if (!state.noCompatMode && DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { return "'" + string + "'"; } var indent = state.indent * Math.max(1, level); // no 0-indent scalars // As indentation gets deeper, let the width decrease monotonically // to the lower bound min(state.lineWidth, 40). // Note that this implies // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. // state.lineWidth > 40 + state.indent: width decreases until the lower bound. // This behaves better than a constant minimum width which disallows narrower options, // or an indent threshold which causes the width to suddenly increase. var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); // Without knowing if keys are implicit/explicit, assume implicit for safety. var singleLineOnly = iskey // No block styles in flow mode. || (state.flowLevel > -1 && level >= state.flowLevel); function testAmbiguity(string) { return testImplicitResolving(state, string); } switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { case STYLE_PLAIN: return string; case STYLE_SINGLE: return "'" + string.replace(/'/g, "''") + "'"; case STYLE_LITERAL: return '|' + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent)); case STYLE_FOLDED: return '>' + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); case STYLE_DOUBLE: return '"' + escapeString(string) + '"'; default: throw new exception('impossible error: invalid scalar style'); } }()); } // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. function blockHeader(string, indentPerLevel) { var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; // note the special case: the string '\n' counts as a "trailing" empty line. var clip = string[string.length - 1] === '\n'; var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); var chomp = keep ? '+' : (clip ? '' : '-'); return indentIndicator + chomp + '\n'; } // (See the note for writeScalar.) function dropEndingNewline(string) { return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; } // Note: a long line without a suitable break point will exceed the width limit. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. function foldString(string, width) { // In folded style, $k$ consecutive newlines output as $k+1$ newlines— // unless they're before or after a more-indented line, or at the very // beginning or end, in which case $k$ maps to $k$. // Therefore, parse each chunk as newline(s) followed by a content line. var lineRe = /(\n+)([^\n]*)/g; // first line (possibly an empty line) var result = (function () { var nextLF = string.indexOf('\n'); nextLF = nextLF !== -1 ? nextLF : string.length; lineRe.lastIndex = nextLF; return foldLine(string.slice(0, nextLF), width); }()); // If we haven't reached the first content line yet, don't add an extra \n. var prevMoreIndented = string[0] === '\n' || string[0] === ' '; var moreIndented; // rest of the lines var match; while ((match = lineRe.exec(string))) { var prefix = match[1], line = match[2]; moreIndented = (line[0] === ' '); result += prefix + (!prevMoreIndented && !moreIndented && line !== '' ? '\n' : '') + foldLine(line, width); prevMoreIndented = moreIndented; } return result; } // Greedy line breaking. // Picks the longest line under the limit each time, // otherwise settles for the shortest line over the limit. // NB. More-indented lines *cannot* be folded, as that would add an extra \n. function foldLine(line, width) { if (line === '' || line[0] === ' ') return line; // Since a more-indented line adds a \n, breaks can't be followed by a space. var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. var match; // start is an inclusive index. end, curr, and next are exclusive. var start = 0, end, curr = 0, next = 0; var result = ''; // Invariants: 0 <= start <= length-1. // 0 <= curr <= next <= max(0, length-2). curr - start <= width. // Inside the loop: // A match implies length >= 2, so curr and next are <= length-2. while ((match = breakRe.exec(line))) { next = match.index; // maintain invariant: curr - start <= width if (next - start > width) { end = (curr > start) ? curr : next; // derive end <= length-2 result += '\n' + line.slice(start, end); // skip the space that was output as \n start = end + 1; // derive start <= length-1 } curr = next; } // By the invariants, start <= length-1, so there is something left over. // It is either the whole string or a part starting from non-whitespace. result += '\n'; // Insert a break if the remainder is too long and there is a break available. if (line.length - start > width && curr > start) { result += line.slice(start, curr) + '\n' + line.slice(curr + 1); } else { result += line.slice(start); } return result.slice(1); // drop extra \n joiner } // Escapes a double-quoted string. function escapeString(string) { var result = ''; var char, nextChar; var escapeSeq; for (var i = 0; i < string.length; i++) { char = string.charCodeAt(i); // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { nextChar = string.charCodeAt(i + 1); if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { // Combine the surrogate pair and store it escaped. result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); // Advance index one extra since we already used that char here. i++; continue; } } escapeSeq = ESCAPE_SEQUENCES[char]; result += !escapeSeq && isPrintable(char) ? string[i] : escapeSeq || encodeHex(char); } return result; } function writeFlowSequence(state, level, object) { var _result = '', _tag = state.tag, index, length; for (index = 0, length = object.length; index < length; index += 1) { // Write only valid elements. if (writeNode(state, level, object[index], false, false)) { if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); _result += state.dump; } } state.tag = _tag; state.dump = '[' + _result + ']'; } function writeBlockSequence(state, level, object, compact) { var _result = '', _tag = state.tag, index, length; for (index = 0, length = object.length; index < length; index += 1) { // Write only valid elements. if (writeNode(state, level + 1, object[index], true, true)) { if (!compact || index !== 0) { _result += generateNextLine(state, level); } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { _result += '-'; } else { _result += '- '; } _result += state.dump; } } state.tag = _tag; state.dump = _result || '[]'; // Empty sequence if no valid values. } function writeFlowMapping(state, level, object) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer; for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (index !== 0) pairBuffer += ', '; if (state.condenseFlow) pairBuffer += '"'; objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (!writeNode(state, level, objectKey, false, false)) { continue; // Skip this pair because of invalid key; } if (state.dump.length > 1024) pairBuffer += '? '; pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); if (!writeNode(state, level, objectValue, false, false)) { continue; // Skip this pair because of invalid value. } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = '{' + _result + '}'; } function writeBlockMapping(state, level, object, compact) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer; // Allow sorting keys so that the output file is deterministic if (state.sortKeys === true) { // Default sorting objectKeyList.sort(); } else if (typeof state.sortKeys === 'function') { // Custom sort function objectKeyList.sort(state.sortKeys); } else if (state.sortKeys) { // Something is wrong throw new exception('sortKeys must be a boolean or a function'); } for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (!compact || index !== 0) { pairBuffer += generateNextLine(state, level); } objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (!writeNode(state, level + 1, objectKey, true, true, true)) { continue; // Skip this pair because of invalid key. } explicitPair = (state.tag !== null && state.tag !== '?') || (state.dump && state.dump.length > 1024); if (explicitPair) { if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += '?'; } else { pairBuffer += '? '; } } pairBuffer += state.dump; if (explicitPair) { pairBuffer += generateNextLine(state, level); } if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { continue; // Skip this pair because of invalid value. } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += ':'; } else { pairBuffer += ': '; } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = _result || '{}'; // Empty mapping if no valid pairs. } function detectType(state, object, explicit) { var _result, typeList, index, length, type, style; typeList = explicit ? state.explicitTypes : state.implicitTypes; for (index = 0, length = typeList.length; index < length; index += 1) { type = typeList[index]; if ((type.instanceOf || type.predicate) && (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && (!type.predicate || type.predicate(object))) { state.tag = explicit ? type.tag : '?'; if (type.represent) { style = state.styleMap[type.tag] || type.defaultStyle; if (_toString$2.call(type.represent) === '[object Function]') { _result = type.represent(object, style); } else if (_hasOwnProperty$3.call(type.represent, style)) { _result = type.represent[style](object, style); } else { throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); } state.dump = _result; } return true; } } return false; } // Serializes `object` and writes it to global `result`. // Returns true on success, or false on invalid object. // function writeNode(state, level, object, block, compact, iskey) { state.tag = null; state.dump = object; if (!detectType(state, object, false)) { detectType(state, object, true); } var type = _toString$2.call(state.dump); if (block) { block = (state.flowLevel < 0 || state.flowLevel > level); } var objectOrArray = type === '[object Object]' || type === '[object Array]', duplicateIndex, duplicate; if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object); duplicate = duplicateIndex !== -1; } if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { compact = false; } if (duplicate && state.usedDuplicates[duplicateIndex]) { state.dump = '*ref_' + duplicateIndex; } else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { state.usedDuplicates[duplicateIndex] = true; } if (type === '[object Object]') { if (block && (Object.keys(state.dump).length !== 0)) { writeBlockMapping(state, level, state.dump, compact); if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { writeFlowMapping(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if (type === '[object Array]') { var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; if (block && (state.dump.length !== 0)) { writeBlockSequence(state, arrayLevel, state.dump, compact); if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { writeFlowSequence(state, arrayLevel, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if (type === '[object String]') { if (state.tag !== '?') { writeScalar(state, state.dump, level, iskey); } } else { if (state.skipInvalid) return false; throw new exception('unacceptable kind of an object to dump ' + type); } if (state.tag !== null && state.tag !== '?') { state.dump = '!<' + state.tag + '> ' + state.dump; } } return true; } function getDuplicateReferences(object, state) { var objects = [], duplicatesIndexes = [], index, length; inspectNode(object, objects, duplicatesIndexes); for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { state.duplicates.push(objects[duplicatesIndexes[index]]); } state.usedDuplicates = new Array(length); } function inspectNode(object, objects, duplicatesIndexes) { var objectKeyList, index, length; if (object !== null && typeof object === 'object') { index = objects.indexOf(object); if (index !== -1) { if (duplicatesIndexes.indexOf(index) === -1) { duplicatesIndexes.push(index); } } else { objects.push(object); if (Array.isArray(object)) { for (index = 0, length = object.length; index < length; index += 1) { inspectNode(object[index], objects, duplicatesIndexes); } } else { objectKeyList = Object.keys(object); for (index = 0, length = objectKeyList.length; index < length; index += 1) { inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); } } } } } function dump(input, options) { options = options || {}; var state = new State$1(options); if (!state.noRefs) getDuplicateReferences(input, state); if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; return ''; } function safeDump(input, options) { return dump(input, common.extend({ schema: default_safe }, options)); } var dump_1 = dump; var safeDump_1 = safeDump; var dumper = { dump: dump_1, safeDump: safeDump_1 }; function deprecated(name) { return function () { throw new Error('Function ' + name + ' is deprecated and cannot be used.'); }; } var Type$1 = type; var Schema$1 = schema; var FAILSAFE_SCHEMA = failsafe; var JSON_SCHEMA = json; var CORE_SCHEMA = core; var DEFAULT_SAFE_SCHEMA = default_safe; var DEFAULT_FULL_SCHEMA = default_full; var load$1 = loader.load; var loadAll$1 = loader.loadAll; var safeLoad$1 = loader.safeLoad; var safeLoadAll$1 = loader.safeLoadAll; var dump$1 = dumper.dump; var safeDump$1 = dumper.safeDump; var YAMLException$1 = exception; // Deprecated schema names from JS-YAML 2.0.x var MINIMAL_SCHEMA = failsafe; var SAFE_SCHEMA = default_safe; var DEFAULT_SCHEMA = default_full; // Deprecated functions from JS-YAML 1.x.x var scan = deprecated('scan'); var parse = deprecated('parse'); var compose = deprecated('compose'); var addConstructor = deprecated('addConstructor'); var jsYaml = { Type: Type$1, Schema: Schema$1, FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, JSON_SCHEMA: JSON_SCHEMA, CORE_SCHEMA: CORE_SCHEMA, DEFAULT_SAFE_SCHEMA: DEFAULT_SAFE_SCHEMA, DEFAULT_FULL_SCHEMA: DEFAULT_FULL_SCHEMA, load: load$1, loadAll: loadAll$1, safeLoad: safeLoad$1, safeLoadAll: safeLoadAll$1, dump: dump$1, safeDump: safeDump$1, YAMLException: YAMLException$1, MINIMAL_SCHEMA: MINIMAL_SCHEMA, SAFE_SCHEMA: SAFE_SCHEMA, DEFAULT_SCHEMA: DEFAULT_SCHEMA, scan: scan, parse: parse, compose: compose, addConstructor: addConstructor }; var jsYaml$1 = jsYaml; var isArrayish = function isArrayish(obj) { if (!obj) { return false; } return obj instanceof Array || Array.isArray(obj) || (obj.length >= 0 && obj.splice instanceof Function); }; var errorEx = function errorEx(name, properties) { if (!name || name.constructor !== String) { properties = name || {}; name = Error.name; } var errorExError = function ErrorEXError(message) { if (!this) { return new ErrorEXError(message); } message = message instanceof Error ? message.message : (message || this.message); Error.call(this, message); Error.captureStackTrace(this, errorExError); this.name = name; Object.defineProperty(this, 'message', { configurable: true, enumerable: false, get: function () { var newMessage = message.split(/\r?\n/g); for (var key in properties) { if (!properties.hasOwnProperty(key)) { continue; } var modifier = properties[key]; if ('message' in modifier) { newMessage = modifier.message(this[key], newMessage) || newMessage; if (!isArrayish(newMessage)) { newMessage = [newMessage]; } } } return newMessage.join('\n'); }, set: function (v) { message = v; } }); var overwrittenStack = null; var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); var stackGetter = stackDescriptor.get; var stackValue = stackDescriptor.value; delete stackDescriptor.value; delete stackDescriptor.writable; stackDescriptor.set = function (newstack) { overwrittenStack = newstack; }; stackDescriptor.get = function () { var stack = (overwrittenStack || ((stackGetter) ? stackGetter.call(this) : stackValue)).split(/\r?\n+/g); // starting in Node 7, the stack builder caches the message. // just replace it. if (!overwrittenStack) { stack[0] = this.name + ': ' + this.message; } var lineCount = 1; for (var key in properties) { if (!properties.hasOwnProperty(key)) { continue; } var modifier = properties[key]; if ('line' in modifier) { var line = modifier.line(this[key]); if (line) { stack.splice(lineCount++, 0, ' ' + line); } } if ('stack' in modifier) { modifier.stack(this[key], stack); } } return stack.join('\n'); }; Object.defineProperty(this, 'stack', stackDescriptor); }; if (Object.setPrototypeOf) { Object.setPrototypeOf(errorExError.prototype, Error.prototype); Object.setPrototypeOf(errorExError, Error); } else { util__default['default'].inherits(errorExError, Error); } return errorExError; }; errorEx.append = function (str, def) { return { message: function (v, message) { v = v || def; if (v) { message[0] += ' ' + str.replace('%s', v.toString()); } return message; } }; }; errorEx.line = function (str, def) { return { line: function (v) { v = v || def; if (v) { return str.replace('%s', v.toString()); } return null; } }; }; var errorEx_1 = errorEx; const hexify = char => { const h = char.charCodeAt(0).toString(16).toUpperCase(); return '0x' + (h.length % 2 ? '0' : '') + h }; const parseError = (e, txt, context) => { if (!txt) { return { message: e.message + ' while parsing empty string', position: 0, } } const badToken = e.message.match(/^Unexpected token (.) .*position\s+(\d+)/i); const errIdx = badToken ? +badToken[2] : e.message.match(/^Unexpected end of JSON.*/i) ? txt.length - 1 : null; const msg = badToken ? e.message.replace(/^Unexpected token ./, `Unexpected token ${ JSON.stringify(badToken[1]) } (${hexify(badToken[1])})`) : e.message; if (errIdx !== null && errIdx !== undefined) { const start = errIdx <= context ? 0 : errIdx - context; const end = errIdx + context >= txt.length ? txt.length : errIdx + context; const slice = (start === 0 ? '' : '...') + txt.slice(start, end) + (end === txt.length ? '' : '...'); const near = txt === slice ? '' : 'near '; return { message: msg + ` while parsing ${near}${JSON.stringify(slice)}`, position: errIdx, } } else { return { message: msg + ` while parsing '${txt.slice(0, context * 2)}'`, position: 0, } } }; class JSONParseError extends SyntaxError { constructor (er, txt, context, caller) { context = context || 20; const metadata = parseError(er, txt, context); super(metadata.message); Object.assign(this, metadata); this.code = 'EJSONPARSE'; this.systemError = er; Error.captureStackTrace(this, caller || this.constructor); } get name () { return this.constructor.name } set name (n) {} get [Symbol.toStringTag] () { return this.constructor.name } } const kIndent = Symbol.for('indent'); const kNewline = Symbol.for('newline'); // only respect indentation if we got a line break, otherwise squash it // things other than objects and arrays aren't indented, so ignore those // Important: in both of these regexps, the $1 capture group is the newline // or undefined, and the $2 capture group is the indent, or undefined. const formatRE = /^\s*[{\[]((?:\r?\n)+)([\s\t]*)/; const emptyRE = /^(?:\{\}|\[\])((?:\r?\n)+)?$/; const parseJson = (txt, reviver, context) => { const parseText = stripBOM(txt); context = context || 20; try { // get the indentation so that we can save it back nicely // if the file starts with {" then we have an indent of '', ie, none // otherwise, pick the indentation of the next line after the first \n // If the pattern doesn't match, then it means no indentation. // JSON.stringify ignores symbols, so this is reasonably safe. // if the string is '{}' or '[]', then use the default 2-space indent. const [, newline = '\n', indent = ' '] = parseText.match(emptyRE) || parseText.match(formatRE) || [, '', '']; const result = JSON.parse(parseText, reviver); if (result && typeof result === 'object') { result[kNewline] = newline; result[kIndent] = indent; } return result } catch (e) { if (typeof txt !== 'string' && !Buffer.isBuffer(txt)) { const isEmptyArray = Array.isArray(txt) && txt.length === 0; throw Object.assign(new TypeError( `Cannot parse ${isEmptyArray ? 'an empty array' : String(txt)}` ), { code: 'EJSONPARSE', systemError: e, }) } throw new JSONParseError(e, parseText, context, parseJson) } }; // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) // because the buffer-to-string conversion in `fs.readFileSync()` // translates it to FEFF, the UTF-16 BOM. const stripBOM = txt => String(txt).replace(/^\uFEFF/, ''); var jsonParseEvenBetterErrors = parseJson; parseJson.JSONParseError = JSONParseError; parseJson.noExceptions = (txt, reviver) => { try { return JSON.parse(stripBOM(txt), reviver) } catch (e) {} }; var LF = '\n'; var CR = '\r'; var LinesAndColumns = (function () { function LinesAndColumns(string) { this.string = string; var offsets = [0]; for (var offset = 0; offset < string.length;) { switch (string[offset]) { case LF: offset += LF.length; offsets.push(offset); break; case CR: offset += CR.length; if (string[offset] === LF) { offset += LF.length; } offsets.push(offset); break; default: offset++; break; } } this.offsets = offsets; } LinesAndColumns.prototype.locationForIndex = function (index) { if (index < 0 || index > this.string.length) { return null; } var line = 0; var offsets = this.offsets; while (offsets[line + 1] <= index) { line++; } var column = index - offsets[line]; return { line: line, column: column }; }; LinesAndColumns.prototype.indexForLocation = function (location) { var line = location.line, column = location.column; if (line < 0 || line >= this.offsets.length) { return null; } if (column < 0 || column > this.lengthOfLine(line)) { return null; } return this.offsets[line] + column; }; LinesAndColumns.prototype.lengthOfLine = function (line) { var offset = this.offsets[line]; var nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1]; return nextOffset - offset; }; return LinesAndColumns; }()); var dist = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': LinesAndColumns }); var jsTokens = createCommonjsModule(function (module, exports) { // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell // License: MIT. (See LICENSE.) Object.defineProperty(exports, "__esModule", { value: true }); // This regex comes from regex.coffee, and is inserted here by generate-index.js // (run `npm run build`). exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; exports.matchToToken = function(match) { var token = {type: "invalid", value: match[0], closed: undefined}; if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]); else if (match[ 5]) token.type = "comment"; else if (match[ 6]) token.type = "comment", token.closed = !!match[7]; else if (match[ 8]) token.type = "regex"; else if (match[ 9]) token.type = "number"; else if (match[10]) token.type = "name"; else if (match[11]) token.type = "punctuator"; else if (match[12]) token.type = "whitespace"; return token }; }); unwrapExports(jsTokens); var jsTokens_1 = jsTokens.matchToToken; var identifier = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.isIdentifierStart = isIdentifierStart; exports.isIdentifierChar = isIdentifierChar; exports.isIdentifierName = isIdentifierName; let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; function isInAstralSet(code, set) { let pos = 0x10000; for (let i = 0, length = set.length; i < length; i += 2) { pos += set[i]; if (pos > code) return false; pos += set[i + 1]; if (pos >= code) return true; } return false; } function isIdentifierStart(code) { if (code < 65) return code === 36; if (code <= 90) return true; if (code < 97) return code === 95; if (code <= 122) return true; if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); } return isInAstralSet(code, astralIdentifierStartCodes); } function isIdentifierChar(code) { if (code < 48) return code === 36; if (code < 58) return true; if (code < 65) return false; if (code <= 90) return true; if (code < 97) return code === 95; if (code <= 122) return true; if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); } return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); } function isIdentifierName(name) { let isFirst = true; for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) { const char = _Array$from[_i]; const cp = char.codePointAt(0); if (isFirst) { if (!isIdentifierStart(cp)) { return false; } isFirst = false; } else if (!isIdentifierChar(cp)) { return false; } } return !isFirst; } }); unwrapExports(identifier); var identifier_1 = identifier.isIdentifierStart; var identifier_2 = identifier.isIdentifierChar; var identifier_3 = identifier.isIdentifierName; var keyword = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.isReservedWord = isReservedWord; exports.isStrictReservedWord = isStrictReservedWord; exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; exports.isStrictBindReservedWord = isStrictBindReservedWord; exports.isKeyword = isKeyword; const reservedWords = { keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], strictBind: ["eval", "arguments"] }; const keywords = new Set(reservedWords.keyword); const reservedWordsStrictSet = new Set(reservedWords.strict); const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); function isReservedWord(word, inModule) { return inModule && word === "await" || word === "enum"; } function isStrictReservedWord(word, inModule) { return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); } function isStrictBindOnlyReservedWord(word) { return reservedWordsStrictBindSet.has(word); } function isStrictBindReservedWord(word, inModule) { return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); } function isKeyword(word) { return keywords.has(word); } }); unwrapExports(keyword); var keyword_1 = keyword.isReservedWord; var keyword_2 = keyword.isStrictReservedWord; var keyword_3 = keyword.isStrictBindOnlyReservedWord; var keyword_4 = keyword.isStrictBindReservedWord; var keyword_5 = keyword.isKeyword; var lib = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "isIdentifierName", { enumerable: true, get: function () { return identifier.isIdentifierName; } }); Object.defineProperty(exports, "isIdentifierChar", { enumerable: true, get: function () { return identifier.isIdentifierChar; } }); Object.defineProperty(exports, "isIdentifierStart", { enumerable: true, get: function () { return identifier.isIdentifierStart; } }); Object.defineProperty(exports, "isReservedWord", { enumerable: true, get: function () { return keyword.isReservedWord; } }); Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { enumerable: true, get: function () { return keyword.isStrictBindOnlyReservedWord; } }); Object.defineProperty(exports, "isStrictBindReservedWord", { enumerable: true, get: function () { return keyword.isStrictBindReservedWord; } }); Object.defineProperty(exports, "isStrictReservedWord", { enumerable: true, get: function () { return keyword.isStrictReservedWord; } }); Object.defineProperty(exports, "isKeyword", { enumerable: true, get: function () { return keyword.isKeyword; } }); }); unwrapExports(lib); var lib_1 = lib.isIdentifierName; var lib_2 = lib.isIdentifierChar; var lib_3 = lib.isIdentifierStart; var lib_4 = lib.isReservedWord; var lib_5 = lib.isStrictBindOnlyReservedWord; var lib_6 = lib.isStrictBindReservedWord; var lib_7 = lib.isStrictReservedWord; var lib_8 = lib.isKeyword; var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp = function (str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); }; var colorName = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; var conversions = createCommonjsModule(function (module) { /* MIT license */ // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) var reverseKeywords = {}; for (var key in colorName) { if (colorName.hasOwnProperty(key)) { reverseKeywords[colorName[key]] = key; } } var convert = module.exports = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; // hide .channels and .labels properties for (var model in convert) { if (convert.hasOwnProperty(model)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } var channels = convert[model].channels; var labels = convert[model].labels; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', {value: channels}); Object.defineProperty(convert[model], 'labels', {value: labels}); } } convert.rgb.hsl = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var delta = max - min; var h; var s; var l; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { var rdif; var gdif; var bdif; var h; var s; var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var v = Math.max(r, g, b); var diff = v - Math.min(r, g, b); var diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert.rgb.hwb = function (rgb) { var r = rgb[0]; var g = rgb[1]; var b = rgb[2]; var h = convert.rgb.hsl(rgb)[0]; var w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var c; var m; var y; var k; k = Math.min(1 - r, 1 - g, 1 - b); c = (1 - r - k) / (1 - k) || 0; m = (1 - g - k) / (1 - k) || 0; y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; /** * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance * */ function comparativeDistance(x, y) { return ( Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2) ); } convert.rgb.keyword = function (rgb) { var reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } var currentClosestDistance = Infinity; var currentClosestKeyword; for (var keyword in colorName) { if (colorName.hasOwnProperty(keyword)) { var value = colorName[keyword]; // Compute comparative distance var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return colorName[keyword]; }; convert.rgb.xyz = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; // assume sRGB r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { var xyz = convert.rgb.xyz(rgb); var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { var h = hsl[0] / 360; var s = hsl[1] / 100; var l = hsl[2] / 100; var t1; var t2; var t3; var rgb; var val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { var h = hsl[0]; var s = hsl[1] / 100; var l = hsl[2] / 100; var smin = s; var lmin = Math.max(l, 0.01); var sv; var v; l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; v = (l + s) / 2; sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { var h = hsv[0] / 60; var s = hsv[1] / 100; var v = hsv[2] / 100; var hi = Math.floor(h) % 6; var f = h - Math.floor(h); var p = 255 * v * (1 - s); var q = 255 * v * (1 - (s * f)); var t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { var h = hsv[0]; var s = hsv[1] / 100; var v = hsv[2] / 100; var vmin = Math.max(v, 0.01); var lmin; var sl; var l; l = (2 - s) * v; lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { var h = hwb[0] / 360; var wh = hwb[1] / 100; var bl = hwb[2] / 100; var ratio = wh + bl; var i; var v; var f; var n; // wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } i = Math.floor(6 * h); v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } n = wh + f * (v - wh); // linear interpolation var r; var g; var b; switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { var c = cmyk[0] / 100; var m = cmyk[1] / 100; var y = cmyk[2] / 100; var k = cmyk[3] / 100; var r; var g; var b; r = 1 - Math.min(1, c * (1 - k) + k); g = 1 - Math.min(1, m * (1 - k) + k); b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { var x = xyz[0] / 100; var y = xyz[1] / 100; var z = xyz[2] / 100; var r; var g; var b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // assume sRGB r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var x; var y; var z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; var y2 = Math.pow(y, 3); var x2 = Math.pow(x, 3); var z2 = Math.pow(z, 3); y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var hr; var h; var c; hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { var l = lch[0]; var c = lch[1]; var h = lch[2]; var a; var b; var hr; hr = h / 360 * 2 * Math.PI; a = c * Math.cos(hr); b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } var ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; // we use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } var ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { var color = args % 10; // handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } var mult = (~~(args > 50) + 1) * 0.5; var r = ((color & 1) * mult) * 255; var g = (((color >> 1) & 1) * mult) * 255; var b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // handle greyscale if (args >= 232) { var c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; var rem; var r = Math.floor(args / 36) / 5 * 255; var g = Math.floor((rem = args % 36) / 6) / 5 * 255; var b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } var colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(function (char) { return char + char; }).join(''); } var integer = parseInt(colorString, 16); var r = (integer >> 16) & 0xFF; var g = (integer >> 8) & 0xFF; var b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var max = Math.max(Math.max(r, g), b); var min = Math.min(Math.min(r, g), b); var chroma = (max - min); var grayscale; var hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma + 4; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { var s = hsl[1] / 100; var l = hsl[2] / 100; var c = 1; var f = 0; if (l < 0.5) { c = 2.0 * s * l; } else { c = 2.0 * s * (1.0 - l); } if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { var s = hsv[1] / 100; var v = hsv[2] / 100; var c = s * v; var f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { var h = hcg[0] / 360; var c = hcg[1] / 100; var g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } var pure = [0, 0, 0]; var hi = (h % 1) * 6; var v = hi % 1; var w = 1 - v; var mg = 0; switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert.hcg.hsv = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); var f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var l = g * (1.0 - c) + 0.5 * c; var s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { var w = hwb[1] / 100; var b = hwb[2] / 100; var v = 1 - b; var c = v - w; var g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = convert.gray.hsv = function (args) { return [0, 0, args[0]]; }; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { var val = Math.round(gray[0] / 100 * 255) & 0xFF; var integer = (val << 16) + (val << 8) + val; var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { var val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; }); var conversions_1 = conversions.rgb; var conversions_2 = conversions.hsl; var conversions_3 = conversions.hsv; var conversions_4 = conversions.hwb; var conversions_5 = conversions.cmyk; var conversions_6 = conversions.xyz; var conversions_7 = conversions.lab; var conversions_8 = conversions.lch; var conversions_9 = conversions.hex; var conversions_10 = conversions.keyword; var conversions_11 = conversions.ansi16; var conversions_12 = conversions.ansi256; var conversions_13 = conversions.hcg; var conversions_14 = conversions.apple; var conversions_15 = conversions.gray; /* this function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 var models = Object.keys(conversions); for (var len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { var graph = buildGraph(); var queue = [fromModel]; // unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { var current = queue.pop(); var adjacents = Object.keys(conversions[current]); for (var len = adjacents.length, i = 0; i < len; i++) { var adjacent = adjacents[i]; var node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { var path = [graph[toModel].parent, toModel]; var fn = conversions[graph[toModel].parent][toModel]; var cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route = function (fromModel) { var graph = deriveBFS(fromModel); var conversion = {}; var models = Object.keys(graph); for (var len = models.length, i = 0; i < len; i++) { var toModel = models[i]; var node = graph[toModel]; if (node.parent === null) { // no possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; var convert = {}; var models = Object.keys(conversions); function wrapRaw(fn) { var wrappedFn = function (args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } return fn(args); }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { var wrappedFn = function (args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } var result = fn(args); // we're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (var len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(function (fromModel) { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); var routes = route(fromModel); var routeModels = Object.keys(routes); routeModels.forEach(function (toModel) { var fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); var colorConvert = convert; var ansiStyles = createCommonjsModule(function (module) { const wrapAnsi16 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => function () { const rgb = fn.apply(colorConvert, arguments); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], // Bright color redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Fix humans styles.color.grey = styles.color.gray; for (const groupName of Object.keys(styles)) { const group = styles[groupName]; for (const styleName of Object.keys(group)) { const style = group[styleName]; styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); } const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = { ansi: wrapAnsi16(ansi2ansi, 0) }; styles.color.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 0) }; styles.color.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 0) }; styles.bgColor.ansi = { ansi: wrapAnsi16(ansi2ansi, 10) }; styles.bgColor.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 10) }; styles.bgColor.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 10) }; for (let key of Object.keys(colorConvert)) { if (typeof colorConvert[key] !== 'object') { continue; } const suite = colorConvert[key]; if (key === 'ansi16') { key = 'ansi'; } if ('ansi16' in suite) { styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); } if ('ansi256' in suite) { styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); } if ('rgb' in suite) { styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); } } return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }); var hasFlag = (flag, argv) => { argv = argv || process.argv; const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const pos = argv.indexOf(prefix + flag); const terminatorPos = argv.indexOf('--'); return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); }; const env = process.env; let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { forceColor = false; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor = true; } if ('FORCE_COLOR' in env) { forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(stream) { if (forceColor === false) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (stream && !stream.isTTY && forceColor !== true) { return 0; } const min = forceColor ? 1 : 0; if (process.platform === 'win32') { // Node.js 7.5.0 is the first version of Node.js to include a patch to // libuv that enables 256 color output on Windows. Anything earlier and it // won't work. However, here we target Node.js 8 at minimum as it is an LTS // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows // release that supports 256 colors. Windows 10 build 14931 is the first release // that supports 16m/TrueColor. const osRelease = os__default['default'].release().split('.'); if ( Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env) { const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } if (env.TERM === 'dumb') { return min; } return min; } function getSupportLevel(stream) { const level = supportsColor(stream); return translateLevel(level); } var supportsColor_1 = { supportsColor: getSupportLevel, stdout: getSupportLevel(process.stdout), stderr: getSupportLevel(process.stderr) }; const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES = new Map([ ['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007'] ]); function unescape(c) { if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { return String.fromCharCode(parseInt(c.slice(1), 16)); } return ESCAPES.get(c) || c; } function parseArguments(name, args) { const results = []; const chunks = args.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { if (!isNaN(chunk)) { results.push(Number(chunk)); } else if ((matches = chunk.match(STRING_REGEX))) { results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } } return results; } function parseStyle(style) { STYLE_REGEX.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const styleName of Object.keys(enabled)) { if (Array.isArray(enabled[styleName])) { if (!(styleName in current)) { throw new Error(`Unknown Chalk style: ${styleName}`); } if (enabled[styleName].length > 0) { current = current[styleName].apply(current, enabled[styleName]); } else { current = current[styleName]; } } } return current; } var templates = (chalk, tmp) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { if (escapeChar) { chunk.push(unescape(escapeChar)); } else if (style) { const str = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); styles.push({inverse, styles: parseStyle(style)}); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(chr); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; throw new Error(errMsg); } return chunks.join(''); }; var chalk = createCommonjsModule(function (module) { const stdoutColor = supportsColor_1.stdout; const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such const skipModels = new Set(['gray']); const styles = Object.create(null); function applyOptions(obj, options) { options = options || {}; // Detect level if not set manually const scLevel = stdoutColor ? stdoutColor.level : 0; obj.level = options.level === undefined ? scLevel : options.level; obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; } function Chalk(options) { // We check for this.template here since calling `chalk.constructor()` // by itself will have a `this` of a previously constructed chalk object if (!this || !(this instanceof Chalk) || this.template) { const chalk = {}; applyOptions(chalk, options); chalk.template = function () { const args = [].slice.call(arguments); return chalkTag.apply(null, [chalk.template].concat(args)); }; Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = Chalk; return chalk.template; } applyOptions(this, options); } // Use bright blue on Windows as the normal blue color is illegible if (isSimpleWindowsTerm) { ansiStyles.blue.open = '\u001B[94m'; } for (const key of Object.keys(ansiStyles)) { ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); styles[key] = { get() { const codes = ansiStyles[key]; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); } }; } styles.visible = { get() { return build.call(this, this._styles || [], true, 'visible'); } }; ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); for (const model of Object.keys(ansiStyles.color.ansi)) { if (skipModels.has(model)) { continue; } styles[model] = { get() { const level = this.level; return function () { const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles.color.close, closeRe: ansiStyles.color.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); for (const model of Object.keys(ansiStyles.bgColor.ansi)) { if (skipModels.has(model)) { continue; } const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const level = this.level; return function () { const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles.bgColor.close, closeRe: ansiStyles.bgColor.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } const proto = Object.defineProperties(() => {}, styles); function build(_styles, _empty, key) { const builder = function () { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; builder._empty = _empty; const self = this; Object.defineProperty(builder, 'level', { enumerable: true, get() { return self.level; }, set(level) { self.level = level; } }); Object.defineProperty(builder, 'enabled', { enumerable: true, get() { return self.enabled; }, set(enabled) { self.enabled = enabled; } }); // See below for fix regarding invisible grey/dim combination on Windows builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto; // eslint-disable-line no-proto return builder; } function applyStyle() { // Support varags, but simply cast to string in case there's only one arg const args = arguments; const argsLen = args.length; let str = String(arguments[0]); if (argsLen === 0) { return ''; } if (argsLen > 1) { // Don't slice `arguments`, it prevents V8 optimizations for (let a = 1; a < argsLen; a++) { str += ' ' + args[a]; } } if (!this.enabled || this.level <= 0 || !str) { return this._empty ? '' : str; } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, // see https://github.com/chalk/chalk/issues/58 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. const originalDim = ansiStyles.dim.open; if (isSimpleWindowsTerm && this.hasGrey) { ansiStyles.dim.open = ''; } for (const code of this._styles.slice().reverse()) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS // https://github.com/chalk/chalk/pull/92 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue ansiStyles.dim.open = originalDim; return str; } function chalkTag(chalk, strings) { if (!Array.isArray(strings)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return [].slice.call(arguments, 1).join(' '); } const args = [].slice.call(arguments, 2); const parts = [strings.raw[0]]; for (let i = 1; i < strings.length; i++) { parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); parts.push(String(strings.raw[i])); } return templates(chalk, parts.join('')); } Object.defineProperties(Chalk.prototype, styles); module.exports = Chalk(); // eslint-disable-line new-cap module.exports.supportsColor = stdoutColor; module.exports.default = module.exports; // For TypeScript }); var chalk_1 = chalk.supportsColor; var lib$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldHighlight = shouldHighlight; exports.getChalk = getChalk; exports.default = highlight; var _jsTokens = _interopRequireWildcard(jsTokens); var _chalk = _interopRequireDefault(chalk); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function getDefs(chalk) { return { keyword: chalk.cyan, capitalized: chalk.yellow, jsx_tag: chalk.yellow, punctuator: chalk.yellow, number: chalk.magenta, string: chalk.green, regex: chalk.magenta, comment: chalk.grey, invalid: chalk.white.bgRed.bold }; } const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; const JSX_TAG = /^[a-z][\w-]*$/i; const BRACKET = /^[()[\]{}]$/; function getTokenType(match) { const [offset, text] = match.slice(-2); const token = (0, _jsTokens.matchToToken)(match); if (token.type === "name") { if ((0, lib.isKeyword)(token.value) || (0, lib.isReservedWord)(token.value)) { return "keyword"; } if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " colorize(str)).join("\n"); } else { return args[0]; } }); } function shouldHighlight(options) { return _chalk.default.supportsColor || options.forceColor; } function getChalk(options) { let chalk = _chalk.default; if (options.forceColor) { chalk = new _chalk.default.constructor({ enabled: true, level: 1 }); } return chalk; } function highlight(code, options = {}) { if (shouldHighlight(options)) { const chalk = getChalk(options); const defs = getDefs(chalk); return highlightTokens(defs, code); } else { return code; } } }); unwrapExports(lib$1); var lib_1$1 = lib$1.shouldHighlight; var lib_2$1 = lib$1.getChalk; var lib$2 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.codeFrameColumns = codeFrameColumns; exports.default = _default; var _highlight = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } let deprecationWarningShown = false; function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold }; } const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; function getMarkerLines(loc, source, opts) { const startLoc = Object.assign({ column: 0, line: -1 }, loc.start); const endLoc = Object.assign({}, startLoc, loc.end); const { linesAbove = 2, linesBelow = 3 } = opts || {}; const startLine = startLoc.line; const startColumn = startLoc.column; const endLine = endLoc.line; const endColumn = endLoc.column; let start = Math.max(startLine - (linesAbove + 1), 0); let end = Math.min(source.length, endLine + linesBelow); if (startLine === -1) { start = 0; } if (endLine === -1) { end = source.length; } const lineDiff = endLine - startLine; const markerLines = {}; if (lineDiff) { for (let i = 0; i <= lineDiff; i++) { const lineNumber = i + startLine; if (!startColumn) { markerLines[lineNumber] = true; } else if (i === 0) { const sourceLength = source[lineNumber - 1].length; markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; } else if (i === lineDiff) { markerLines[lineNumber] = [0, endColumn]; } else { const sourceLength = source[lineNumber - i].length; markerLines[lineNumber] = [0, sourceLength]; } } } else { if (startColumn === endColumn) { if (startColumn) { markerLines[startLine] = [startColumn, 0]; } else { markerLines[startLine] = true; } } else { markerLines[startLine] = [startColumn, endColumn - startColumn]; } } return { start, end, markerLines }; } function codeFrameColumns(rawLines, loc, opts = {}) { const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); const chalk = (0, _highlight.getChalk)(opts); const defs = getDefs(chalk); const maybeHighlight = (chalkFn, string) => { return highlighted ? chalkFn(string) : string; }; const lines = rawLines.split(NEWLINE); const { start, end, markerLines } = getMarkerLines(loc, lines, opts); const hasColumns = loc.start && typeof loc.start.column === "number"; const numberMaxWidth = String(end).length; const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => { const number = start + 1 + index; const paddedNumber = ` ${number}`.slice(-numberMaxWidth); const gutter = ` ${paddedNumber} | `; const hasMarker = markerLines[number]; const lastMarkerLine = !markerLines[number + 1]; if (hasMarker) { let markerLine = ""; if (Array.isArray(hasMarker)) { const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); const numberOfMarkers = hasMarker[1] || 1; markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); if (lastMarkerLine && opts.message) { markerLine += " " + maybeHighlight(defs.message, opts.message); } } return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); } else { return ` ${maybeHighlight(defs.gutter, gutter)}${line}`; } }).join("\n"); if (opts.message && !hasColumns) { frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; } if (highlighted) { return chalk.reset(frame); } else { return frame; } } function _default(rawLines, lineNumber, colNumber, opts = {}) { if (!deprecationWarningShown) { deprecationWarningShown = true; const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; if (process.emitWarning) { process.emitWarning(message, "DeprecationWarning"); } else { const deprecationError = new Error(message); deprecationError.name = "DeprecationWarning"; console.warn(new Error(message)); } } colNumber = Math.max(colNumber, 0); const location = { start: { column: colNumber, line: lineNumber } }; return codeFrameColumns(rawLines, location, opts); } }); unwrapExports(lib$2); var lib_1$2 = lib$2.codeFrameColumns; var require$$0 = getCjsExportFromNamespace(dist); const {default: LinesAndColumns$1} = require$$0; const {codeFrameColumns} = lib$2; const JSONError = errorEx_1('JSONError', { fileName: errorEx_1.append('in %s'), codeFrame: errorEx_1.append('\n\n%s\n') }); var parseJson$1 = (string, reviver, filename) => { if (typeof reviver === 'string') { filename = reviver; reviver = null; } try { try { return JSON.parse(string, reviver); } catch (error) { jsonParseEvenBetterErrors(string, reviver); throw error; } } catch (error) { error.message = error.message.replace(/\n/g, ''); const indexMatch = error.message.match(/in JSON at position (\d+) while parsing/); const jsonError = new JSONError(error); if (filename) { jsonError.fileName = filename; } if (indexMatch && indexMatch.length > 0) { const lines = new LinesAndColumns$1(string); const index = Number(indexMatch[1]); const location = lines.locationForIndex(index); const codeFrame = codeFrameColumns( string, {start: {line: location.line + 1, column: location.column + 1}}, {highlightCode: true} ); jsonError.codeFrame = codeFrame; } throw jsonError; } }; /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ var ms = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse$1(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse$1(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = ms; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * Active `debug` instances. */ createDebug.instances = []; /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return match; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = createDebug.enabled(namespace); debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.destroy = destroy; debug.extend = extend; // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } createDebug.instances.push(debug); return debug; } function destroy() { const index = createDebug.instances.indexOf(this); if (index !== -1) { createDebug.instances.splice(index, 1); return true; } return false; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } for (i = 0; i < createDebug.instances.length; i++) { const instance = createDebug.instances[i]; instance.enabled = createDebug.enabled(instance.namespace); } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } createDebug.enable(createDebug.load()); return createDebug; } var common$1 = setup; var browser = createCommonjsModule(function (module, exports) { /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = common$1(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; }); var browser_1 = browser.formatArgs; var browser_2 = browser.save; var browser_3 = browser.load; var browser_4 = browser.useColors; var browser_5 = browser.storage; var browser_6 = browser.colors; var browser_7 = browser.log; var hasFlag$1 = (flag, argv = process.argv) => { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; const {env: env$1} = process; let forceColor$1; if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) { forceColor$1 = 0; } else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) { forceColor$1 = 1; } if ('FORCE_COLOR' in env$1) { if (env$1.FORCE_COLOR === 'true') { forceColor$1 = 1; } else if (env$1.FORCE_COLOR === 'false') { forceColor$1 = 0; } else { forceColor$1 = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3); } } function translateLevel$1(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor$1(haveStream, streamIsTTY) { if (forceColor$1 === 0) { return 0; } if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) { return 3; } if (hasFlag$1('color=256')) { return 2; } if (haveStream && !streamIsTTY && forceColor$1 === undefined) { return 0; } const min = forceColor$1 || 0; if (env$1.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os__default['default'].release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env$1) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env$1) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; } if (env$1.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env$1) { const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env$1.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env$1.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { return 1; } if ('COLORTERM' in env$1) { return 1; } return min; } function getSupportLevel$1(stream) { const level = supportsColor$1(stream, stream && stream.isTTY); return translateLevel$1(level); } var supportsColor_1$1 = { supportsColor: getSupportLevel$1, stdout: translateLevel$1(supportsColor$1(true, tty__default['default'].isatty(1))), stderr: translateLevel$1(supportsColor$1(true, tty__default['default'].isatty(2))) }; var node = createCommonjsModule(function (module, exports) { /** * Module dependencies. */ /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = supportsColor_1$1; if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty__default['default'].isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util__default['default'].format(...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = common$1(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util__default['default'].inspect(v, this.inspectOpts) .replace(/\s*\n\s*/g, ' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util__default['default'].inspect(v, this.inspectOpts); }; }); var node_1 = node.init; var node_2 = node.log; var node_3 = node.formatArgs; var node_4 = node.save; var node_5 = node.load; var node_6 = node.useColors; var node_7 = node.colors; var node_8 = node.inspectOpts; var src = createCommonjsModule(function (module) { /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { module.exports = browser; } else { module.exports = node; } }); const resolveFrom = (fromDirectory, moduleId, silent) => { if (typeof fromDirectory !== 'string') { throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``); } if (typeof moduleId !== 'string') { throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``); } try { fromDirectory = fs__default['default'].realpathSync(fromDirectory); } catch (error) { if (error.code === 'ENOENT') { fromDirectory = path__default['default'].resolve(fromDirectory); } else if (silent) { return; } else { throw error; } } const fromFile = path__default['default'].join(fromDirectory, 'noop.js'); const resolveFileName = () => module__default['default']._resolveFilename(moduleId, { id: fromFile, filename: fromFile, paths: module__default['default']._nodeModulePaths(fromDirectory) }); if (silent) { try { return resolveFileName(); } catch (error) { return; } } return resolveFileName(); }; var resolveFrom_1 = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId); var silent = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId, true); resolveFrom_1.silent = silent; class FiggyPudding { constructor (specs, opts, providers) { this.__specs = specs || {}; Object.keys(this.__specs).forEach(alias => { if (typeof this.__specs[alias] === 'string') { const key = this.__specs[alias]; const realSpec = this.__specs[key]; if (realSpec) { const aliasArr = realSpec.aliases || []; aliasArr.push(alias, key); realSpec.aliases = [...(new Set(aliasArr))]; this.__specs[alias] = realSpec; } else { throw new Error(`Alias refers to invalid key: ${key} -> ${alias}`) } } }); this.__opts = opts || {}; this.__providers = reverse((providers).filter( x => x != null && typeof x === 'object' )); this.__isFiggyPudding = true; } get (key) { return pudGet(this, key, true) } get [Symbol.toStringTag] () { return 'FiggyPudding' } forEach (fn, thisArg = this) { for (let [key, value] of this.entries()) { fn.call(thisArg, value, key, this); } } toJSON () { const obj = {}; this.forEach((val, key) => { obj[key] = val; }); return obj } * entries (_matcher) { for (let key of Object.keys(this.__specs)) { yield [key, this.get(key)]; } const matcher = _matcher || this.__opts.other; if (matcher) { const seen = new Set(); for (let p of this.__providers) { const iter = p.entries ? p.entries(matcher) : entries(p); for (let [key, val] of iter) { if (matcher(key) && !seen.has(key)) { seen.add(key); yield [key, val]; } } } } } * [Symbol.iterator] () { for (let [key, value] of this.entries()) { yield [key, value]; } } * keys () { for (let [key] of this.entries()) { yield key; } } * values () { for (let [, value] of this.entries()) { yield value; } } concat (...moreConfig) { return new Proxy(new FiggyPudding( this.__specs, this.__opts, reverse(this.__providers).concat(moreConfig) ), proxyHandler) } } try { const util = util__default['default']; FiggyPudding.prototype[util.inspect.custom] = function (depth, opts) { return ( this[Symbol.toStringTag] + ' ' ) + util.inspect(this.toJSON(), opts) }; } catch (e) {} function BadKeyError (key) { throw Object.assign(new Error( `invalid config key requested: ${key}` ), {code: 'EBADKEY'}) } function pudGet (pud, key, validate) { let spec = pud.__specs[key]; if (validate && !spec && (!pud.__opts.other || !pud.__opts.other(key))) { BadKeyError(key); } else { if (!spec) { spec = {}; } let ret; for (let p of pud.__providers) { ret = tryGet(key, p); if (ret === undefined && spec.aliases && spec.aliases.length) { for (let alias of spec.aliases) { if (alias === key) { continue } ret = tryGet(alias, p); if (ret !== undefined) { break } } } if (ret !== undefined) { break } } if (ret === undefined && spec.default !== undefined) { if (typeof spec.default === 'function') { return spec.default(pud) } else { return spec.default } } else { return ret } } } function tryGet (key, p) { let ret; if (p.__isFiggyPudding) { ret = pudGet(p, key, false); } else if (typeof p.get === 'function') { ret = p.get(key); } else { ret = p[key]; } return ret } const proxyHandler = { has (obj, prop) { return prop in obj.__specs && pudGet(obj, prop, false) !== undefined }, ownKeys (obj) { return Object.keys(obj.__specs) }, get (obj, prop) { if ( typeof prop === 'symbol' || prop.slice(0, 2) === '__' || prop in FiggyPudding.prototype ) { return obj[prop] } return obj.get(prop) }, set (obj, prop, value) { if ( typeof prop === 'symbol' || prop.slice(0, 2) === '__' ) { obj[prop] = value; return true } else { throw new Error('figgyPudding options cannot be modified. Use .concat() instead.') } }, deleteProperty () { throw new Error('figgyPudding options cannot be deleted. Use .concat() and shadow them instead.') } }; var figgyPudding_1 = figgyPudding; function figgyPudding (specs, opts) { function factory (...providers) { return new Proxy(new FiggyPudding( specs, opts, providers ), proxyHandler) } return factory } function reverse (arr) { const ret = []; arr.forEach(x => ret.unshift(x)); return ret } function entries (obj) { return Object.keys(obj).map(k => [k, obj[k]]) } var pathExists = fp => new Promise(resolve => { fs__default['default'].access(fp, err => { resolve(!err); }); }); var sync = fp => { try { fs__default['default'].accessSync(fp); return true; } catch (err) { return false; } }; pathExists.sync = sync; const pTry = (fn, ...arguments_) => new Promise(resolve => { resolve(fn(...arguments_)); }); var pTry_1 = pTry; // TODO: remove this in the next major version var _default = pTry; pTry_1.default = _default; const pLimit = concurrency => { if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up')); } const queue = []; let activeCount = 0; const next = () => { activeCount--; if (queue.length > 0) { queue.shift()(); } }; const run = (fn, resolve, ...args) => { activeCount++; const result = pTry_1(fn, ...args); resolve(result); result.then(next, next); }; const enqueue = (fn, resolve, ...args) => { if (activeCount < concurrency) { run(fn, resolve, ...args); } else { queue.push(run.bind(null, fn, resolve, ...args)); } }; const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args)); Object.defineProperties(generator, { activeCount: { get: () => activeCount }, pendingCount: { get: () => queue.length }, clearQueue: { value: () => { queue.length = 0; } } }); return generator; }; var pLimit_1 = pLimit; var _default$1 = pLimit; pLimit_1.default = _default$1; class EndError extends Error { constructor(value) { super(); this.value = value; } } // The input can also be a promise, so we `Promise.resolve()` it const testElement = (el, tester) => Promise.resolve(el).then(tester); // The input can also be a promise, so we `Promise.all()` them both const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0]))); var pLocate = (iterable, tester, opts) => { opts = Object.assign({ concurrency: Infinity, preserveOrder: true }, opts); const limit = pLimit_1(opts.concurrency); // Start all the promises concurrently with optional limit const items = [...iterable].map(el => [el, limit(testElement, el, tester)]); // Check the promises either serially or concurrently const checkLimit = pLimit_1(opts.preserveOrder ? 1 : Infinity); return Promise.all(items.map(el => checkLimit(finder, el))) .then(() => {}) .catch(err => err instanceof EndError ? err.value : Promise.reject(err)); }; var locatePath = (iterable, options) => { options = Object.assign({ cwd: process.cwd() }, options); return pLocate(iterable, el => pathExists(path__default['default'].resolve(options.cwd, el)), options); }; var sync$1 = (iterable, options) => { options = Object.assign({ cwd: process.cwd() }, options); for (const el of iterable) { if (pathExists.sync(path__default['default'].resolve(options.cwd, el))) { return el; } } }; locatePath.sync = sync$1; var findUp = (filename, opts = {}) => { const startDir = path__default['default'].resolve(opts.cwd || ''); const {root} = path__default['default'].parse(startDir); const filenames = [].concat(filename); return new Promise(resolve => { (function find(dir) { locatePath(filenames, {cwd: dir}).then(file => { if (file) { resolve(path__default['default'].join(dir, file)); } else if (dir === root) { resolve(null); } else { find(path__default['default'].dirname(dir)); } }); })(startDir); }); }; var sync$2 = (filename, opts = {}) => { let dir = path__default['default'].resolve(opts.cwd || ''); const {root} = path__default['default'].parse(dir); const filenames = [].concat(filename); // eslint-disable-next-line no-constant-condition while (true) { const file = locatePath.sync(filenames, {cwd: dir}); if (file) { return path__default['default'].join(dir, file); } if (dir === root) { return null; } dir = path__default['default'].dirname(dir); } }; findUp.sync = sync$2; var ini = createCommonjsModule(function (module, exports) { exports.parse = exports.decode = decode; exports.stringify = exports.encode = encode; exports.safe = safe; exports.unsafe = unsafe; var eol = typeof process !== 'undefined' && process.platform === 'win32' ? '\r\n' : '\n'; function encode (obj, opt) { var children = []; var out = ''; if (typeof opt === 'string') { opt = { section: opt, whitespace: false, }; } else { opt = opt || Object.create(null); opt.whitespace = opt.whitespace === true; } var separator = opt.whitespace ? ' = ' : '='; Object.keys(obj).forEach(function (k, _, __) { var val = obj[k]; if (val && Array.isArray(val)) { val.forEach(function (item) { out += safe(k + '[]') + separator + safe(item) + '\n'; }); } else if (val && typeof val === 'object') children.push(k); else out += safe(k) + separator + safe(val) + eol; }); if (opt.section && out.length) out = '[' + safe(opt.section) + ']' + eol + out; children.forEach(function (k, _, __) { var nk = dotSplit(k).join('\\.'); var section = (opt.section ? opt.section + '.' : '') + nk; var child = encode(obj[k], { section: section, whitespace: opt.whitespace, }); if (out.length && child.length) out += eol; out += child; }); return out } function dotSplit (str) { return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') .replace(/\\\./g, '\u0001') .split(/\./).map(function (part) { return part.replace(/\1/g, '\\.') .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001') }) } function decode (str) { var out = Object.create(null); var p = out; var section = null; // section |key = value var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i; var lines = str.split(/[\r\n]+/g); lines.forEach(function (line, _, __) { if (!line || line.match(/^\s*[;#]/)) return var match = line.match(re); if (!match) return if (match[1] !== undefined) { section = unsafe(match[1]); if (section === '__proto__') { // not allowed // keep parsing the section, but don't attach it. p = Object.create(null); return } p = out[section] = out[section] || Object.create(null); return } var key = unsafe(match[2]); if (key === '__proto__') return var value = match[3] ? unsafe(match[4]) : true; switch (value) { case 'true': case 'false': case 'null': value = JSON.parse(value); } // Convert keys with '[]' suffix to an array if (key.length > 2 && key.slice(-2) === '[]') { key = key.substring(0, key.length - 2); if (key === '__proto__') return if (!p[key]) p[key] = []; else if (!Array.isArray(p[key])) p[key] = [p[key]]; } // safeguard against resetting a previously defined // array by accidentally forgetting the brackets if (Array.isArray(p[key])) p[key].push(value); else p[key] = value; }); // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} // use a filter to return the keys that have to be deleted. Object.keys(out).filter(function (k, _, __) { if (!out[k] || typeof out[k] !== 'object' || Array.isArray(out[k])) return false // see if the parent section is also an object. // if so, add it to that, and mark this one for deletion var parts = dotSplit(k); var p = out; var l = parts.pop(); var nl = l.replace(/\\\./g, '.'); parts.forEach(function (part, _, __) { if (part === '__proto__') return if (!p[part] || typeof p[part] !== 'object') p[part] = Object.create(null); p = p[part]; }); if (p === out && nl === l) return false p[nl] = out[k]; return true }).forEach(function (del, _, __) { delete out[del]; }); return out } function isQuoted (val) { return (val.charAt(0) === '"' && val.slice(-1) === '"') || (val.charAt(0) === "'" && val.slice(-1) === "'") } function safe (val) { return (typeof val !== 'string' || val.match(/[=\r\n]/) || val.match(/^\[/) || (val.length > 1 && isQuoted(val)) || val !== val.trim()) ? JSON.stringify(val) : val.replace(/;/g, '\\;').replace(/#/g, '\\#') } function unsafe (val, doUnesc) { val = (val || '').trim(); if (isQuoted(val)) { // remove the single quotes before calling JSON.parse if (val.charAt(0) === "'") val = val.substr(1, val.length - 2); try { val = JSON.parse(val); } catch (_) {} } else { // walk the val to find the first not-escaped ; character var esc = false; var unesc = ''; for (var i = 0, l = val.length; i < l; i++) { var c = val.charAt(i); if (esc) { if ('\\;#'.indexOf(c) !== -1) unesc += c; else unesc += '\\' + c; esc = false; } else if (';#'.indexOf(c) !== -1) break else if (c === '\\') esc = true; else unesc += c; } if (esc) unesc += '\\'; return unesc.trim() } return val } }); var ini_1 = ini.parse; var ini_2 = ini.decode; var ini_3 = ini.stringify; var ini_4 = ini.encode; var ini_5 = ini.safe; var ini_6 = ini.unsafe; const NpmConfig = figgyPudding_1({}, { // Open up the pudding object. other () { return true } }); const ConfigOpts = figgyPudding_1({ cache: { default: path__default['default'].join(os__default['default'].homedir(), '.npm') }, configNames: { default: ['npmrc', '.npmrc'] }, envPrefix: { default: /^npm_config_/i }, cwd: { default: () => process.cwd() }, globalconfig: { default: () => path__default['default'].join(getGlobalPrefix(), 'etc', 'npmrc') }, userconfig: { default: path__default['default'].join(os__default['default'].homedir(), '.npmrc') } }); var read = getNpmConfig; function getNpmConfig (_opts, _builtin) { const builtin = ConfigOpts(_builtin); const env = {}; for (let key of Object.keys(process.env)) { if (!key.match(builtin.envPrefix)) continue const newKey = key.toLowerCase() .replace(builtin.envPrefix, '') .replace(/(?!^)_/g, '-'); env[newKey] = process.env[key]; } const cli = NpmConfig(_opts); const userConfPath = ( builtin.userconfig || cli.userconfig || env.userconfig ); const user = userConfPath && maybeReadIni(userConfPath); const globalConfPath = ( builtin.globalconfig || cli.globalconfig || env.globalconfig ); const global = globalConfPath && maybeReadIni(globalConfPath); const projConfPath = findUp.sync(builtin.configNames, { cwd: builtin.cwd }); let proj = {}; if (projConfPath && projConfPath !== userConfPath) { proj = maybeReadIni(projConfPath); } const newOpts = NpmConfig(builtin, global, user, proj, env, cli); if (newOpts.cache) { return newOpts.concat({ cache: path__default['default'].resolve( ( (cli.cache || env.cache) ? builtin.cwd : proj.cache ? path__default['default'].dirname(projConfPath) : user.cache ? path__default['default'].dirname(userConfPath) : global.cache ? path__default['default'].dirname(globalConfPath) : path__default['default'].dirname(userConfPath) ), newOpts.cache ) }) } else { return newOpts } } function maybeReadIni (f) { let txt; try { txt = fs__default['default'].readFileSync(f, 'utf8'); } catch (err) { if (err.code === 'ENOENT') { return '' } else { throw err } } return ini.parse(txt) } function getGlobalPrefix () { if (process.env.PREFIX) { return process.env.PREFIX } else if (process.platform === 'win32') { // c:\node\node.exe --> prefix=c:\node\ return path__default['default'].dirname(process.execPath) } else { // /usr/local/bin/node --> prefix=/usr/local let pref = path__default['default'].dirname(path__default['default'].dirname(process.execPath)); // destdir only is respected on Unix if (process.env.DESTDIR) { pref = path__default['default'].join(process.env.DESTDIR, pref); } return pref } } var libnpmconfig = { read: read }; var resolve = resolveFrom_1.silent; var readNpmConfig = libnpmconfig.read; var loadPlugin_1 = loadPlugin; loadPlugin.resolve = resolvePlugin; var electron = process.versions.electron !== undefined; var windows = process.platform === 'win32'; var argv = process.argv[1] || /* istanbul ignore next */ ''; var nvm = process.env.NVM_BIN; var appData = process.env.APPDATA; /* istanbul ignore next */ var globalsLibrary = windows ? '' : 'lib'; var builtinNpmConfig; // The prefix config defaults to the location where node is installed. // On Windows, this is in a place called `%AppData%`, which we have to // pass to `libnpmconfig` explicitly: /* istanbul ignore next */ if (windows && appData) { builtinNpmConfig = {prefix: path__default['default'].join(appData, 'npm')}; } var npmPrefix = readNpmConfig(null, builtinNpmConfig).prefix; // If there is no prefix defined, use the defaults // See: /* istanbul ignore next */ if (!npmPrefix) { npmPrefix = windows ? path__default['default'].dirname(process.execPath) : path__default['default'].resolve(process.execPath, '../..'); } var globally = electron || argv.indexOf(npmPrefix) === 0; var globals = path__default['default'].resolve(npmPrefix, globalsLibrary, 'node_modules'); // If we’re in Electron, we’re running in a modified Node that cannot really // install global node modules. // To find the actual modules, the user has to set `prefix` somewhere in an // `.npmrc` (which is picked up by `libnpmconfig`). // Most people don’t do that, and some use NVM instead to manage different // versions of Node. // Luckily NVM leaks some environment variables that we can pick up on to try // and detect the actual modules. /* istanbul ignore next */ if (electron && nvm && !fs__default['default'].existsSync(globals)) { globals = path__default['default'].resolve(nvm, '..', globalsLibrary, 'node_modules'); } // Load the plugin found using `resolvePlugin`. function loadPlugin(name, options) { return commonjsRequire(resolvePlugin(name, options) || name) } // Find a plugin. // // See also: // // // // Uses the standard node module loading strategy to find $name in each given // `cwd` (and optionally the global `node_modules` directory). // // If a prefix is given and $name is not a path, `$prefix-$name` is also // searched (preferring these over non-prefixed modules). function resolvePlugin(name, options) { var settings = options || {}; var prefix = settings.prefix; var cwd = settings.cwd; var global = settings.global; var filePath; var sources; var length; var index; var plugin; var slash; var scope = ''; if (global === null || global === undefined) { global = globally; } if (cwd && typeof cwd === 'object') { sources = cwd.concat(); } else { sources = [cwd || process.cwd()]; } // Non-path. if (name.charAt(0) !== '.') { if (global) { sources.push(globals); } // Unprefix module. if (prefix) { prefix = prefix.charAt(prefix.length - 1) === '-' ? prefix : prefix + '-'; // Scope? if (name.charAt(0) === '@') { slash = name.indexOf('/'); // Let’s keep the algorithm simple. // No need to care if this is a “valid” scope (I think?). // But we do check for the slash. if (slash !== -1) { scope = name.slice(0, slash + 1); name = name.slice(slash + 1); } } if (name.slice(0, prefix.length) !== prefix) { plugin = scope + prefix + name; } name = scope + name; } } length = sources.length; index = -1; while (++index < length) { cwd = sources[index]; filePath = (plugin && resolve(cwd, plugin)) || resolve(cwd, name); if (filePath) { return filePath } } return null } var isPlainObj = value => { if (Object.prototype.toString.call(value) !== '[object Object]') { return false; } const prototype = Object.getPrototypeOf(value); return prototype === null || prototype === Object.prototype; }; var format = createCommonjsModule(function (module) { (function() { //// Export the API var namespace; // CommonJS / Node module { namespace = module.exports = format; } namespace.format = format; namespace.vsprintf = vsprintf; if (typeof console !== 'undefined' && typeof console.log === 'function') { namespace.printf = printf; } function printf(/* ... */) { console.log(format.apply(null, arguments)); } function vsprintf(fmt, replacements) { return format.apply(null, [fmt].concat(replacements)); } function format(fmt) { var argIndex = 1 // skip initial format argument , args = [].slice.call(arguments) , i = 0 , n = fmt.length , result = '' , c , escaped = false , arg , tmp , leadingZero = false , precision , nextArg = function() { return args[argIndex++]; } , slurpNumber = function() { var digits = ''; while (/\d/.test(fmt[i])) { digits += fmt[i++]; c = fmt[i]; } return digits.length > 0 ? parseInt(digits) : null; } ; for (; i < n; ++i) { c = fmt[i]; if (escaped) { escaped = false; if (c == '.') { leadingZero = false; c = fmt[++i]; } else if (c == '0' && fmt[i + 1] == '.') { leadingZero = true; i += 2; c = fmt[i]; } else { leadingZero = true; } precision = slurpNumber(); switch (c) { case 'b': // number in binary result += parseInt(nextArg(), 10).toString(2); break; case 'c': // character arg = nextArg(); if (typeof arg === 'string' || arg instanceof String) result += arg; else result += String.fromCharCode(parseInt(arg, 10)); break; case 'd': // number in decimal result += parseInt(nextArg(), 10); break; case 'f': // floating point number tmp = String(parseFloat(nextArg()).toFixed(precision || 6)); result += leadingZero ? tmp : tmp.replace(/^0/, ''); break; case 'j': // JSON result += JSON.stringify(nextArg()); break; case 'o': // number in octal result += '0' + parseInt(nextArg(), 10).toString(8); break; case 's': // string result += nextArg(); break; case 'x': // lowercase hexadecimal result += '0x' + parseInt(nextArg(), 10).toString(16); break; case 'X': // uppercase hexadecimal result += '0x' + parseInt(nextArg(), 10).toString(16).toUpperCase(); break; default: result += c; break; } } else if (c === '%') { escaped = true; } else { result += c; } } return result; } }()); }); var fault = create(Error); var fault_1 = fault; fault.eval = create(EvalError); fault.range = create(RangeError); fault.reference = create(ReferenceError); fault.syntax = create(SyntaxError); fault.type = create(TypeError); fault.uri = create(URIError); fault.create = create; // Create a new `EConstructor`, with the formatted `format` as a first argument. function create(EConstructor) { FormattedError.displayName = EConstructor.displayName || EConstructor.name; return FormattedError function FormattedError(format$1) { if (format$1) { format$1 = format.apply(null, arguments); } return new EConstructor(format$1) } } var debug = src('unified-engine:find-up'); var findUp$1 = FindUp; var read$1 = fs__default['default'].readFile; var resolve$1 = path__default['default'].resolve; var relative = path__default['default'].relative; var join = path__default['default'].join; var dirname = path__default['default'].dirname; FindUp.prototype.load = load$2; function FindUp(options) { var self = this; var fp = options.filePath; self.cache = {}; self.cwd = options.cwd; self.detect = options.detect; self.names = options.names; self.create = options.create; if (fp) { self.givenFilePath = resolve$1(options.cwd, fp); } } function load$2(filePath, callback) { var self = this; var cache = self.cache; var givenFilePath = self.givenFilePath; var givenFile = self.givenFile; var names = self.names; var create = self.create; var cwd = self.cwd; var parent; if (givenFilePath) { if (givenFile) { apply(callback, givenFile); } else { givenFile = [callback]; self.givenFile = givenFile; debug('Checking given file `%s`', givenFilePath); read$1(givenFilePath, loadGiven); } return } if (!self.detect) { return callback() } filePath = resolve$1(cwd, filePath); parent = dirname(filePath); if (parent in cache) { apply(callback, cache[parent]); } else { cache[parent] = [callback]; find(parent); } function loadGiven(error, buf) { var cbs = self.givenFile; var result; if (error) { result = fault_1( 'Cannot read given file `%s`\n%s', relative(cwd, givenFilePath), error.stack ); result.code = 'ENOENT'; result.path = error.path; result.syscall = error.syscall; } else { try { result = create(buf, givenFilePath); debug('Read given file `%s`', givenFilePath); } catch (error_) { result = fault_1( 'Cannot parse given file `%s`\n%s', relative(cwd, givenFilePath), error_.stack ); debug(error_.message); } } givenFile = result; self.givenFile = result; applyAll(cbs, result); } function find(directory) { var index = -1; var length = names.length; next(); function next() { var parent; // Try to read the next file. // We do not use `readdir` because on huge directories, that could be // *very* slow. if (++index < length) { read$1(join(directory, names[index]), done); } else { parent = dirname(directory); if (directory === parent) { debug('No files found for `%s`', filePath); found(); } else if (parent in cache) { apply(found, cache[parent]); } else { cache[parent] = [found]; find(parent); } } } function done(error, buf) { var name = names[index]; var fp = join(directory, name); var contents; /* istanbul ignore if - Hard to test. */ if (error) { if (error.code === 'ENOENT') { return next() } error = fault_1( 'Cannot read file `%s`\n%s', relative(cwd, fp), error.message ); debug(error.message); return found(error) } try { contents = create(buf, fp); } catch (error_) { return found( fault_1('Cannot parse file `%s`\n%s', relative(cwd, fp), error_.message) ) } /* istanbul ignore else - maybe used in the future. */ if (contents) { debug('Read file `%s`', fp); found(null, contents); } else { next(); } } function found(error, result) { var cbs = cache[directory]; cache[directory] = error || result; applyAll(cbs, error || result); } } function applyAll(cbs, result) { var index = cbs.length; while (index--) { apply(cbs[index], result); } } function apply(cb, result) { if ( result !== null && typeof result === 'object' && typeof result[0] === 'function' ) { result.push(cb); } else if (result instanceof Error) { cb(result); } else { cb(null, result); } } } var configuration = createCommonjsModule(function (module) { var debug = src('unified-engine:configuration'); var resolve = loadPlugin_1.resolve; module.exports = Config; var own = {}.hasOwnProperty; var extname = path__default['default'].extname; var basename = path__default['default'].basename; var dirname = path__default['default'].dirname; var relative = path__default['default'].relative; var loaders = { '.json': loadJson, '.js': loadScript, '.yaml': loadYaml, '.yml': loadYaml }; var defaultLoader = loadJson; Config.prototype.load = load; function Config(options) { var rcName = options.rcName; var packageField = options.packageField; var names = []; this.cwd = options.cwd; this.packageField = options.packageField; this.pluginPrefix = options.pluginPrefix; this.configTransform = options.configTransform; this.defaultConfig = options.defaultConfig; if (rcName) { names.push(rcName, rcName + '.js', rcName + '.yml', rcName + '.yaml'); debug('Looking for `%s` configuration files', names); } if (packageField) { names.push('package.json'); debug('Looking for `%s` fields in `package.json` files', packageField); } this.given = {settings: options.settings, plugins: options.plugins}; this.create = create.bind(this); this.findUp = new findUp$1({ filePath: options.rcPath, cwd: options.cwd, detect: options.detectConfig, names: names, create: this.create }); } function load(filePath, callback) { var self = this; var searchPath = filePath || path__default['default'].resolve(this.cwd, 'stdin.js'); self.findUp.load(searchPath, done); function done(error, file) { if (error || file) { return callback(error, file) } callback(null, self.create()); } } function create(buf, filePath) { var self = this; var transform = self.configTransform; var defaults = self.defaultConfig; var fn = (filePath && loaders[extname(filePath)]) || defaultLoader; var options = {prefix: self.pluginPrefix, cwd: self.cwd}; var result = {settings: {}, plugins: []}; var contents = buf ? fn.apply(self, arguments) : undefined; if (transform && contents !== undefined) { contents = transform(contents, filePath); } // Exit if we did find a `package.json`, but it does not have configuration. if (buf && contents === undefined && basename(filePath) === 'package.json') { return } if (contents === undefined) { if (defaults) { merge(result, defaults, Object.assign({}, options, {root: self.cwd})); } } else { merge( result, contents, Object.assign({}, options, {root: dirname(filePath)}) ); } merge(result, self.given, Object.assign({}, options, {root: self.cwd})); return result } // Basically `Module.prototype.load`, but for a buffer instead of a file path. function loadScript(buf, filePath) { var submodule = module__default['default']._cache[filePath]; if (!submodule) { submodule = new module__default['default'](filePath, module); submodule.filename = filePath; submodule.paths = module__default['default']._nodeModulePaths(dirname(filePath)); submodule._compile(String(buf), filePath); submodule.loaded = true; module__default['default']._cache[filePath] = submodule; } return submodule.exports } function loadYaml(buf, filePath) { return jsYaml$1.safeLoad(buf, {filename: basename(filePath)}) } function loadJson(buf, filePath) { var result = parseJson$1(buf, filePath); if (basename(filePath) === 'package.json') { result = result[this.packageField]; } return result } function merge(target, raw, options) { var root = options.root; var cwd = options.cwd; var prefix = options.prefix; if (typeof raw === 'object' && raw !== null) { addPreset(raw); } else { throw new Error('Expected preset, not `' + raw + '`') } return target function addPreset(result) { var plugins = result.plugins; if (plugins === null || plugins === undefined) ; else if (typeof plugins === 'object' && plugins !== null) { if ('length' in plugins) { addEach(plugins); } else { addIn(plugins); } } else { throw new Error( 'Expected a list or object of plugins, not `' + plugins + '`' ) } target.settings = Object.assign({}, target.settings, result.settings); } function addEach(result) { var length = result.length; var index = -1; var value; while (++index < length) { value = result[index]; if (value !== null && typeof value === 'object' && 'length' in value) { use.apply(null, value); } else { use(value); } } } function addIn(result) { var key; for (key in result) { use(key, result[key]); } } function use(usable, value) { if (typeof usable === 'string') { addModule(usable, value); } else if (typeof usable === 'function') { addPlugin(usable, value); } else { merge(target, usable, options); } } function addModule(id, value) { var fp = resolve(id, {cwd: root, prefix: prefix}); var result; if (fp) { try { result = commonjsRequire(fp); } catch (error) { throw fault_1( 'Cannot parse script `%s`\n%s', relative(root, fp), error.stack ) } try { if (typeof result === 'function') { addPlugin(result, value); } else { merge(target, result, Object.assign({}, options, {root: dirname(fp)})); } } catch (_) { throw fault_1( 'Error: Expected preset or plugin, not %s, at `%s`', result, relative(root, fp) ) } } else { fp = relative(cwd, path__default['default'].resolve(root, id)); addPlugin( failingModule(fp, new Error('Could not find module `' + id + '`')), value ); } } function addPlugin(result, value) { var entry = find(target.plugins, result); if (entry) { reconfigure(entry, value); } else { target.plugins.push([result, value]); } } } function reconfigure(entry, value) { if (isPlainObj(entry[1]) && isPlainObj(value)) { value = Object.assign({}, entry[1], value); } entry[1] = value; } function find(entries, plugin) { var length = entries.length; var index = -1; var entry; while (++index < length) { entry = entries[index]; if (entry[0] === plugin) { return entry } } } function failingModule(id, error) { var cache = failingModule.cache || (failingModule.cache = {}); var submodule = own.call(cache, id) ? cache[id] : (cache[id] = fail); return submodule function fail() { throw error } } }); var configure_1 = configure; function configure(context, settings) { context.configuration = new configuration(settings); } // A simple implementation of make-array function makeArray (subject) { return Array.isArray(subject) ? subject : [subject] } const EMPTY = ''; const SPACE = ' '; const ESCAPE = '\\'; const REGEX_TEST_BLANK_LINE = /^\s+$/; const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; const REGEX_SPLITALL_CRLF = /\r?\n/g; // /foo, // ./foo, // ../foo, // . // .. const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; const SLASH = '/'; const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore') /* istanbul ignore next */ : 'node-ignore'; const define = (object, key, value) => Object.defineProperty(object, key, {value}); const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression // The cases are complicated, see test cases for details const sanitizeRange = range => range.replace( REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but // fatal for JavaScript regular expression, so eliminate it. : EMPTY ); // See fixtures #59 const cleanRangeBackSlash = slashes => { const {length} = slashes; return slashes.slice(0, length - length % 2) }; // > If the pattern ends with a slash, // > it is removed for the purpose of the following description, // > but it would only find a match with a directory. // > In other words, foo/ will match a directory foo and paths underneath it, // > but will not match a regular file or a symbolic link foo // > (this is consistent with the way how pathspec works in general in Git). // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call // you could use option `mark: true` with `glob` // '`foo/`' should not continue with the '`..`' const REPLACERS = [ // > Trailing spaces are ignored unless they are quoted with backslash ("\") [ // (a\ ) -> (a ) // (a ) -> (a) // (a \ ) -> (a ) /\\?\s+$/, match => match.indexOf('\\') === 0 ? SPACE : EMPTY ], // replace (\ ) with ' ' [ /\\\s/g, () => SPACE ], // Escape metacharacters // which is written down by users but means special for regular expressions. // > There are 12 characters with special meanings: // > - the backslash \, // > - the caret ^, // > - the dollar sign $, // > - the period or dot ., // > - the vertical bar or pipe symbol |, // > - the question mark ?, // > - the asterisk or star *, // > - the plus sign +, // > - the opening parenthesis (, // > - the closing parenthesis ), // > - and the opening square bracket [, // > - the opening curly brace {, // > These special characters are often called "metacharacters". [ /[\\$.|*+(){^]/g, match => `\\${match}` ], [ // > a question mark (?) matches a single character /(?!\\)\?/g, () => '[^/]' ], // leading slash [ // > A leading slash matches the beginning of the pathname. // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". // A leading slash matches the beginning of the pathname /^\//, () => '^' ], // replace special metacharacter slash after the leading slash [ /\//g, () => '\\/' ], [ // > A leading "**" followed by a slash means match in all directories. // > For example, "**/foo" matches file or directory "foo" anywhere, // > the same as pattern "foo". // > "**/foo/bar" matches file or directory "bar" anywhere that is directly // > under directory "foo". // Notice that the '*'s have been replaced as '\\*' /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo' () => '^(?:.*\\/)?' ], // starting [ // there will be no leading '/' // (which has been replaced by section "leading slash") // If starts with '**', adding a '^' to the regular expression also works /^(?=[^^])/, function startingReplacer () { // If has a slash `/` at the beginning or middle return !/\/(?!$)/.test(this) // > Prior to 2.22.1 // > If the pattern does not contain a slash /, // > Git treats it as a shell glob pattern // Actually, if there is only a trailing slash, // git also treats it as a shell glob pattern // After 2.22.1 (compatible but clearer) // > If there is a separator at the beginning or middle (or both) // > of the pattern, then the pattern is relative to the directory // > level of the particular .gitignore file itself. // > Otherwise the pattern may also match at any level below // > the .gitignore level. ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for // > consumption by fnmatch(3) : '^' } ], // two globstars [ // Use lookahead assertions so that we could match more than one `'/**'` /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories // should not use '*', or it will be replaced by the next replacer // Check if it is not the last `'/**'` (_, index, str) => index + 6 < str.length // case: /**/ // > A slash followed by two consecutive asterisks then a slash matches // > zero or more directories. // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. // '/**/' ? '(?:\\/[^\\/]+)*' // case: /** // > A trailing `"/**"` matches everything inside. // #21: everything inside but it should not include the current folder : '\\/.+' ], // intermediate wildcards [ // Never replace escaped '*' // ignore rule '\*' will match the path '*' // 'abc.*/' -> go // 'abc.*' -> skip this rule /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js' // '*.js' doesn't match 'abc' (_, p1) => `${p1}[^\\/]*` ], [ // unescape, revert step 3 except for back slash // For example, if a user escape a '\\*', // after step 3, the result will be '\\\\\\*' /\\\\\\(?=[$.|*+(){^])/g, () => ESCAPE ], [ // '\\\\' -> '\\' /\\\\/g, () => ESCAPE ], [ // > The range notation, e.g. [a-zA-Z], // > can be used to match one of the characters in a range. // `\` is escaped by step 3 /(\\)?\[([^\]/]*?)(\\*)($|\])/g, (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE // '\\[bar]' -> '\\\\[bar\\]' ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === ']' ? endEscape.length % 2 === 0 // A normal case, and it is a range notation // '[bar]' // '[bar\\\\]' ? `[${sanitizeRange(range)}${endEscape}]` // Invalid range notaton // '[bar\\]' -> '[bar\\\\]' : '[]' : '[]' ], // ending [ // 'js' will not match 'js.' // 'ab' will not match 'abc' /(?:[^*])$/, // WTF! // https://git-scm.com/docs/gitignore // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) // which re-fixes #24, #38 // > If there is a separator at the end of the pattern then the pattern // > will only match directories, otherwise the pattern can match both // > files and directories. // 'js*' will not match 'a.js' // 'js/' will not match 'a.js' // 'js' will match 'a.js' and 'a.js/' match => /\/$/.test(match) // foo/ will not match 'foo' ? `${match}$` // foo matches 'foo' and 'foo/' : `${match}(?=$|\\/$)` ], // trailing wildcard [ /(\^|\\\/)?\\\*$/, (_, p1) => { const prefix = p1 // '\^': // '/*' does not match EMPTY // '/*' does not match everything // '\\\/': // 'abc/*' does not match 'abc/' ? `${p1}[^/]+` // 'a*' matches 'a' // 'a*' matches 'aa' : '[^/]*'; return `${prefix}(?=$|\\/$)` } ], ]; // A simple cache, because an ignore rule only has only one certain meaning const regexCache = Object.create(null); // @param {pattern} const makeRegex = (pattern, negative, ignorecase) => { const r = regexCache[pattern]; if (r) { return r } // const replacers = negative // ? NEGATIVE_REPLACERS // : POSITIVE_REPLACERS const source = REPLACERS.reduce( (prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern ); return regexCache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source) }; const isString = subject => typeof subject === 'string'; // > A blank line matches no files, so it can serve as a separator for readability. const checkPattern = pattern => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment. && pattern.indexOf('#') !== 0; const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF); class IgnoreRule { constructor ( origin, pattern, negative, regex ) { this.origin = origin; this.pattern = pattern; this.negative = negative; this.regex = regex; } } const createRule = (pattern, ignorecase) => { const origin = pattern; let negative = false; // > An optional prefix "!" which negates the pattern; if (pattern.indexOf('!') === 0) { negative = true; pattern = pattern.substr(1); } pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that // > begin with a literal "!", for example, `"\!important!.txt"`. .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that // > begin with a hash. .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); const regex = makeRegex(pattern, negative, ignorecase); return new IgnoreRule( origin, pattern, negative, regex ) }; const throwError$1 = (message, Ctor) => { throw new Ctor(message) }; const checkPath = (path, originalPath, doThrow) => { if (!isString(path)) { return doThrow( `path must be a string, but got \`${originalPath}\``, TypeError ) } // We don't know if we should ignore EMPTY, so throw if (!path) { return doThrow(`path must not be empty`, TypeError) } // Check if it is a relative path if (checkPath.isNotRelative(path)) { const r = '`path.relative()`d'; return doThrow( `path should be a ${r} string, but got "${originalPath}"`, RangeError ) } return true }; const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path); checkPath.isNotRelative = isNotRelative; checkPath.convert = p => p; class Ignore { constructor ({ ignorecase = true } = {}) { this._rules = []; this._ignorecase = ignorecase; define(this, KEY_IGNORE, true); this._initCache(); } _initCache () { this._ignoreCache = Object.create(null); this._testCache = Object.create(null); } _addPattern (pattern) { // #32 if (pattern && pattern[KEY_IGNORE]) { this._rules = this._rules.concat(pattern._rules); this._added = true; return } if (checkPattern(pattern)) { const rule = createRule(pattern, this._ignorecase); this._added = true; this._rules.push(rule); } } // @param {Array | string | Ignore} pattern add (pattern) { this._added = false; makeArray( isString(pattern) ? splitPattern(pattern) : pattern ).forEach(this._addPattern, this); // Some rules have just added to the ignore, // making the behavior changed. if (this._added) { this._initCache(); } return this } // legacy addPattern (pattern) { return this.add(pattern) } // | ignored : unignored // negative | 0:0 | 0:1 | 1:0 | 1:1 // -------- | ------- | ------- | ------- | -------- // 0 | TEST | TEST | SKIP | X // 1 | TESTIF | SKIP | TEST | X // - SKIP: always skip // - TEST: always test // - TESTIF: only test if checkUnignored // - X: that never happen // @param {boolean} whether should check if the path is unignored, // setting `checkUnignored` to `false` could reduce additional // path matching. // @returns {TestResult} true if a file is ignored _testOne (path, checkUnignored) { let ignored = false; let unignored = false; this._rules.forEach(rule => { const {negative} = rule; if ( unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored ) { return } const matched = rule.regex.test(path); if (matched) { ignored = !negative; unignored = negative; } }); return { ignored, unignored } } // @returns {TestResult} _test (originalPath, cache, checkUnignored, slices) { const path = originalPath // Supports nullable path && checkPath.convert(originalPath); checkPath(path, originalPath, throwError$1); return this._t(path, cache, checkUnignored, slices) } _t (path, cache, checkUnignored, slices) { if (path in cache) { return cache[path] } if (!slices) { // path/to/a.js // ['path', 'to', 'a.js'] slices = path.split(SLASH); } slices.pop(); // If the path has no parent directory, just test it if (!slices.length) { return cache[path] = this._testOne(path, checkUnignored) } const parent = this._t( slices.join(SLASH) + SLASH, cache, checkUnignored, slices ); // If the path contains a parent directory, check the parent first return cache[path] = parent.ignored // > It is not possible to re-include a file if a parent directory of // > that file is excluded. ? parent : this._testOne(path, checkUnignored) } ignores (path) { return this._test(path, this._ignoreCache, false).ignored } createFilter () { return path => !this.ignores(path) } filter (paths) { return makeArray(paths).filter(this.createFilter()) } // @returns {TestResult} test (path) { return this._test(path, this._testCache, true) } } const factory = options => new Ignore(options); const returnFalse = () => false; const isPathValid = path => checkPath(path && checkPath.convert(path), path, returnFalse); factory.isPathValid = isPathValid; // Fixes typescript factory.default = factory; var ignore = factory; // Windows // -------------------------------------------------------------- /* istanbul ignore if */ if ( // Detect `process` so that it can run in browsers. typeof process !== 'undefined' && ( process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32' ) ) { /* eslint no-control-regex: "off" */ const makePosix = str => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, '/'); checkPath.convert = makePosix; // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' // 'd:\\foo' const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; checkPath.isNotRelative = path => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path); } var ignore$1 = Ignore$1; Ignore$1.prototype.check = check; var sep = path__default['default'].sep; var dirname$1 = path__default['default'].dirname; var relative$1 = path__default['default'].relative; var resolve$2 = path__default['default'].resolve; function Ignore$1(options) { this.cwd = options.cwd; this.ignorePathResolveFrom = options.ignorePathResolveFrom; this.findUp = new findUp$1({ filePath: options.ignorePath, cwd: options.cwd, detect: options.detectIgnore, names: options.ignoreName ? [options.ignoreName] : [], create: create$1 }); } function check(filePath, callback) { var self = this; self.findUp.load(filePath, done); function done(error, ignore) { var normal; if (error) { callback(error); } else if (ignore) { normal = relative$1( resolve$2( self.cwd, self.ignorePathResolveFrom === 'cwd' ? '.' : ignore.filePath ), resolve$2(self.cwd, filePath) ); if ( normal === '' || normal === '..' || normal.charAt(0) === sep || normal.slice(0, 3) === '..' + sep ) { callback(null, false); } else { callback(null, ignore.ignores(normal)); } } else { callback(null, false); } } } function create$1(buf, filePath) { var ignore$1 = ignore().add(String(buf)); ignore$1.filePath = dirname$1(filePath); return ignore$1 } // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var isWindows = process.platform === 'win32'; // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } var normalize = path__default['default'].normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } var realpathSync = function realpathSync(p, cache) { // make p is absolute p = path__default['default'].resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs__default['default'].lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs__default['default'].lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs__default['default'].statSync(base); linkTarget = fs__default['default'].readlinkSync(base); } resolvedLink = path__default['default'].resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = path__default['default'].resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; var realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = path__default['default'].resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs__default['default'].lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs__default['default'].lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs__default['default'].stat(base, function(err) { if (err) return cb(err); fs__default['default'].readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = path__default['default'].resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = path__default['default'].resolve(resolvedLink, p.slice(pos)); start(); } }; var old = { realpathSync: realpathSync, realpath: realpath }; var fs_realpath = realpath$1; realpath$1.realpath = realpath$1; realpath$1.sync = realpathSync$1; realpath$1.realpathSync = realpathSync$1; realpath$1.monkeypatch = monkeypatch; realpath$1.unmonkeypatch = unmonkeypatch; var origRealpath = fs__default['default'].realpath; var origRealpathSync = fs__default['default'].realpathSync; var version = process.version; var ok = /^v[0-5]\./.test(version); function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath$1 (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache; cache = null; } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb); } else { cb(er, result); } }); } function realpathSync$1 (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs__default['default'].realpath = realpath$1; fs__default['default'].realpathSync = realpathSync$1; } function unmonkeypatch () { fs__default['default'].realpath = origRealpath; fs__default['default'].realpathSync = origRealpathSync; } var concatMap = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; var balancedMatch = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } var braceExpansion = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balancedMatch('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), true).map(unescapeBraces); } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balancedMatch('{', '}', str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, false) : ['']; return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length); var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, false) }); } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } return expansions; } var minimatch_1 = minimatch; minimatch.Minimatch = Minimatch; var path = { sep: '/' }; try { path = path__default['default']; } catch (er) {} var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}; var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } }; // any single thing other than / // don't need to escape / when using new RegExp() var qmark = '[^/]'; // * => any number of characters var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot, // followed by anything, any number of times. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp. var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true } function charSet (s) { return s.split('').reduce(function (set, c) { set[c] = true; return set }, {}) } // normalizes slashes. var slashSplit = /\/+/; minimatch.filter = filter; function filter (pattern, options) { options = options || {}; return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { a = a || {}; b = b || {}; var t = {}; Object.keys(b).forEach(function (k) { t[k] = b[k]; }); Object.keys(a).forEach(function (k) { t[k] = a[k]; }); return t } minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return minimatch var orig = minimatch; var m = function minimatch (p, pattern, options) { return orig.minimatch(p, pattern, ext(def, options)) }; m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) }; return m }; Minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return Minimatch return minimatch.defaults(def).Minimatch }; function minimatch (p, pattern, options) { if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {}; // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } // "" only matches "" if (pattern.trim() === '') return p === '' return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {}; pattern = pattern.trim(); // windows support: need to use /, not \ if (path.sep !== '/') { pattern = pattern.split(path.sep).join('/'); } this.options = options; this.set = []; this.pattern = pattern; this.regexp = null; this.negate = false; this.comment = false; this.empty = false; // make the set of regexps etc. this.make(); } Minimatch.prototype.debug = function () {}; Minimatch.prototype.make = make; function make () { // don't do it more than once. if (this._made) return var pattern = this.pattern; var options = this.options; // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true; return } if (!pattern) { this.empty = true; return } // step 1: figure out negation, etc. this.parseNegate(); // step 2: expand braces var set = this.globSet = this.braceExpand(); if (options.debug) this.debug = console.error; this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(function (s) { return s.split(slashSplit) }); this.debug(this.pattern, set); // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this); this.debug(this.pattern, set); // filter out everything that didn't compile properly. set = set.filter(function (s) { return s.indexOf(false) === -1 }); this.debug(this.pattern, set); this.set = set; } Minimatch.prototype.parseNegate = parseNegate; function parseNegate () { var pattern = this.pattern; var negate = false; var options = this.options; var negateOffset = 0; if (options.nonegate) return for (var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === '!' ; i++) { negate = !negate; negateOffset++; } if (negateOffset) this.pattern = pattern.substr(negateOffset); this.negate = negate; } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return braceExpand(pattern, options) }; Minimatch.prototype.braceExpand = braceExpand; function braceExpand (pattern, options) { if (!options) { if (this instanceof Minimatch) { options = this.options; } else { options = {}; } } pattern = typeof pattern === 'undefined' ? this.pattern : pattern; if (typeof pattern === 'undefined') { throw new TypeError('undefined pattern') } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } return braceExpansion(pattern) } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse$2; var SUBPARSE = {}; function parse$2 (pattern, isSub) { if (pattern.length > 1024 * 64) { throw new TypeError('pattern is too long') } var options = this.options; // shortcuts if (!options.noglobstar && pattern === '**') return GLOBSTAR if (pattern === '') return '' var re = ''; var hasMagic = !!options.nocase; var escaping = false; // ? => one single character var patternListStack = []; var negativeLists = []; var stateChar; var inClass = false; var reClassStart = -1; var classStart = -1; // . and .. never match anything that doesn't start with ., // even when options.dot is set. var patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)'; var self = this; function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star; hasMagic = true; break case '?': re += qmark; hasMagic = true; break default: re += '\\' + stateChar; break } self.debug('clearStateChar %j %j', stateChar, re); stateChar = false; } } for (var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i++) { this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped. if (escaping && reSpecials[c]) { re += '\\' + c; escaping = false; continue } switch (c) { case '/': // completely not allowed, even escaped. // Should already be path-split by now. return false case '\\': clearStateChar(); escaping = true; continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class'); if (c === '!' && i === classStart + 1) c = '^'; re += c; continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. self.debug('call clearStateChar %j', stateChar); clearStateChar(); stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar(); continue case '(': if (inClass) { re += '('; continue } if (!stateChar) { re += '\\('; continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }); // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:'; this.debug('plType %j %j', stateChar, re); stateChar = false; continue case ')': if (inClass || !patternListStack.length) { re += '\\)'; continue } clearStateChar(); hasMagic = true; var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*) // The others are (?:) re += pl.close; if (pl.type === '!') { negativeLists.push(pl); } pl.reEnd = re.length; continue case '|': if (inClass || !patternListStack.length || escaping) { re += '\\|'; escaping = false; continue } clearStateChar(); re += '|'; continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar(); if (inClass) { re += '\\' + c; continue } inClass = true; classStart = i; reClassStart = re.length; re += c; continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c; escaping = false; continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" if (inClass) { // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. var cs = pattern.substring(classStart + 1, i); try { RegExp('[' + cs + ']'); } catch (er) { // not a valid class! var sp = this.parse(cs, SUBPARSE); re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'; hasMagic = hasMagic || sp[1]; inClass = false; continue } } // finish up the class. hasMagic = true; inClass = false; re += c; continue default: // swallow any state char that wasn't consumed clearStateChar(); if (escaping) { // no need escaping = false; } else if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\'; } re += c; } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1); sp = this.parse(cs, SUBPARSE); re = re.substr(0, reClassStart) + '\\[' + sp[0]; hasMagic = hasMagic || sp[1]; } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + pl.open.length); this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\'; } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }); this.debug('tail=%j\n %s', tail, tail, pl, re); var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type; hasMagic = true; re = re.slice(0, pl.reStart) + t + '\\(' + tail; } // handle trailing things that only matter at the very end. clearStateChar(); if (escaping) { // trailing \\ re += '\\\\'; } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false; switch (re.charAt(0)) { case '.': case '[': case '(': addPatternStart = true; } // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (var n = negativeLists.length - 1; n > -1; n--) { var nl = negativeLists[n]; var nlBefore = re.slice(0, nl.reStart); var nlFirst = re.slice(nl.reStart, nl.reEnd - 8); var nlLast = re.slice(nl.reEnd - 8, nl.reEnd); var nlAfter = re.slice(nl.reEnd); nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. var openParensBefore = nlBefore.split('(').length - 1; var cleanAfter = nlAfter; for (i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); } nlAfter = cleanAfter; var dollar = ''; if (nlAfter === '' && isSub !== SUBPARSE) { dollar = '$'; } var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast; re = newRe; } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re; } if (addPatternStart) { re = patternStart + re; } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? 'i' : ''; try { var regExp = new RegExp('^' + re + '$', flags); } catch (er) { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } regExp._glob = pattern; regExp._src = re; return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() }; Minimatch.prototype.makeRe = makeRe; function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set; if (!set.length) { this.regexp = false; return this.regexp } var options = this.options; var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot; var flags = options.nocase ? 'i' : ''; var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === 'string') ? regExpEscape(p) : p._src }).join('\\\/') }).join('|'); // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$'; // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$'; try { this.regexp = new RegExp(re, flags); } catch (ex) { this.regexp = false; } return this.regexp } minimatch.match = function (list, pattern, options) { options = options || {}; var mm = new Minimatch(pattern, options); list = list.filter(function (f) { return mm.match(f) }); if (mm.options.nonull && !list.length) { list.push(pattern); } return list }; Minimatch.prototype.match = match; function match (f, partial) { this.debug('match', f, this.pattern); // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true var options = this.options; // windows: need to use /, not \ if (path.sep !== '/') { f = f.split(path.sep).join('/'); } // treat the test path as a set of pathparts. f = f.split(slashSplit); this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set; this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment var filename; var i; for (i = f.length - 1; i >= 0; i--) { filename = f[i]; if (filename) break } for (i = 0; i < set.length; i++) { var pattern = set[i]; var file = f; if (options.matchBase && pattern.length === 1) { file = [filename]; } var hit = this.matchOne(file, pattern, partial); if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options; this.debug('matchOne', { 'this': this, file: file, pattern: pattern }); this.debug('matchOne', file.length, pattern.length); for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop'); var p = pattern[pi]; var f = file[fi]; this.debug(pattern, p, f); // should be impossible. // some invalid regexp stuff in the set. if (p === false) return false if (p === GLOBSTAR) { this.debug('GLOBSTAR', [pattern, p, f]); // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi; var pr = pi + 1; if (pr === pl) { this.debug('** at the end'); // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr]; this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee); // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === '.' || swallowee === '..' || (!options.dot && swallowee.charAt(0) === '.')) { this.debug('dot detected!', file, fr, pattern, pr); break } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue'); fr++; } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr); if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit; if (typeof p === 'string') { if (options.nocase) { hit = f.toLowerCase() === p.toLowerCase(); } else { hit = f === p; } this.debug('string match', p, f, hit); } else { hit = f.match(p); this.debug('pattern match', p, f, hit); } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ var emptyFileEnd = (fi === fl - 1) && (file[fi] === ''); return emptyFileEnd } // should be unreachable. throw new Error('wtf?') }; // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, '$1') } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } var inherits_browser = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } }; } }); var inherits = createCommonjsModule(function (module) { try { var util = util__default['default']; /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = inherits_browser; } }); function posix(path) { return path.charAt(0) === '/'; } function win32(path) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } var pathIsAbsolute = process.platform === 'win32' ? win32 : posix; var posix_1 = posix; var win32_1 = win32; pathIsAbsolute.posix = posix_1; pathIsAbsolute.win32 = win32_1; var alphasort_1 = alphasort; var alphasorti_1 = alphasorti; var setopts_1 = setopts; var ownProp_1 = ownProp; var makeAbs_1 = makeAbs; var finish_1 = finish; var mark_1 = mark$1; var isIgnored_1 = isIgnored; var childrenIgnored_1 = childrenIgnored; function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var Minimatch$1 = minimatch_1.Minimatch; function alphasorti (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()) } function alphasort (a, b) { return a.localeCompare(b) } function setupIgnores (self, options) { self.ignore = options.ignore || []; if (!Array.isArray(self.ignore)) self.ignore = [self.ignore]; if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap); } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null; if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, ''); gmatcher = new Minimatch$1(gpattern, { dot: true }); } return { matcher: new Minimatch$1(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {}; // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern; } self.silent = !!options.silent; self.pattern = pattern; self.strict = options.strict !== false; self.realpath = !!options.realpath; self.realpathCache = options.realpathCache || Object.create(null); self.follow = !!options.follow; self.dot = !!options.dot; self.mark = !!options.mark; self.nodir = !!options.nodir; if (self.nodir) self.mark = true; self.sync = !!options.sync; self.nounique = !!options.nounique; self.nonull = !!options.nonull; self.nosort = !!options.nosort; self.nocase = !!options.nocase; self.stat = !!options.stat; self.noprocess = !!options.noprocess; self.absolute = !!options.absolute; self.maxLength = options.maxLength || Infinity; self.cache = options.cache || Object.create(null); self.statCache = options.statCache || Object.create(null); self.symlinks = options.symlinks || Object.create(null); setupIgnores(self, options); self.changedCwd = false; var cwd = process.cwd(); if (!ownProp(options, "cwd")) self.cwd = cwd; else { self.cwd = path__default['default'].resolve(options.cwd); self.changedCwd = self.cwd !== cwd; } self.root = options.root || path__default['default'].resolve(self.cwd, "/"); self.root = path__default['default'].resolve(self.root); if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/"); // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd); if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); self.nomount = !!options.nomount; // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true; options.nocomment = true; self.minimatch = new Minimatch$1(pattern, options); self.options = self.minimatch.options; } function finish (self) { var nou = self.nounique; var all = nou ? [] : Object.create(null); for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i]; if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i]; if (nou) all.push(literal); else all[literal] = true; } } else { // had matches var m = Object.keys(matches); if (nou) all.push.apply(all, m); else m.forEach(function (m) { all[m] = true; }); } } if (!nou) all = Object.keys(all); if (!self.nosort) all = all.sort(self.nocase ? alphasorti : alphasort); // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]); } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)); var c = self.cache[e] || self.cache[makeAbs(self, e)]; if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c); return notDir }); } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }); self.found = all; } function mark$1 (self, p) { var abs = makeAbs(self, p); var c = self.cache[abs]; var m = p; if (c) { var isDir = c === 'DIR' || Array.isArray(c); var slash = p.slice(-1) === '/'; if (isDir && !slash) m += '/'; else if (!isDir && slash) m = m.slice(0, -1); if (m !== p) { var mabs = makeAbs(self, m); self.statCache[mabs] = self.statCache[abs]; self.cache[mabs] = self.cache[abs]; } } return m } // lotta situps... function makeAbs (self, f) { var abs = f; if (f.charAt(0) === '/') { abs = path__default['default'].join(self.root, f); } else if (pathIsAbsolute(f) || f === '') { abs = f; } else if (self.changedCwd) { abs = path__default['default'].resolve(self.cwd, f); } else { abs = path__default['default'].resolve(f); } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/'); return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } var common$2 = { alphasort: alphasort_1, alphasorti: alphasorti_1, setopts: setopts_1, ownProp: ownProp_1, makeAbs: makeAbs_1, finish: finish_1, mark: mark_1, isIgnored: isIgnored_1, childrenIgnored: childrenIgnored_1 }; var sync$3 = globSync; globSync.GlobSync = GlobSync; var setopts$1 = common$2.setopts; var ownProp$1 = common$2.ownProp; var childrenIgnored$1 = common$2.childrenIgnored; var isIgnored$1 = common$2.isIgnored; function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts$1(this, pattern, options); if (this.noprocess) return this var n = this.minimatch.set.length; this.matches = new Array(n); for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false); } this._finish(); } GlobSync.prototype._finish = function () { assert__default['default'](this instanceof GlobSync); if (this.realpath) { var self = this; this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null); for (var p in matchset) { try { p = self._makeAbs(p); var real = fs_realpath.realpathSync(p, self.realpathCache); set[real] = true; } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true; else throw er } } }); } common$2.finish(this); }; GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert__default['default'](this instanceof GlobSync); // Get the first [n] parts of pattern that are all strings. var n = 0; while (typeof pattern[n] === 'string') { n ++; } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix; switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index); return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null; break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/'); break } var remain = pattern.slice(n); // get the list of entries. var read; if (prefix === null) read = '.'; else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) { if (!prefix || !pathIsAbsolute(prefix)) prefix = '/' + prefix; read = prefix; } else read = prefix; var abs = this._makeAbs(read); //if ignored, skip processing if (childrenIgnored$1(this, read)) return var isGlobStar = remain[0] === minimatch_1.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); else this._processReaddir(prefix, read, abs, remain, index, inGlobStar); }; GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === '.'; var matchedEntries = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.charAt(0) !== '.' || dotOk) { var m; if (negate && !prefix) { m = !e.match(pn); } else { m = e.match(pn); } if (m) matchedEntries.push(e); } } var len = matchedEntries.length; // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e; else e = prefix + e; } if (e.charAt(0) === '/' && !this.nomount) { e = path__default['default'].join(this.root, e); } this._emitMatch(index, e); } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift(); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; var newPattern; if (prefix) newPattern = [prefix, e]; else newPattern = [e]; this._process(newPattern.concat(remain), index, inGlobStar); } }; GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored$1(this, e)) return var abs = this._makeAbs(e); if (this.mark) e = this._mark(e); if (this.absolute) { e = abs; } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs]; if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true; if (this.stat) this._stat(e); }; GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries; var lstat; try { lstat = fs__default['default'].lstatSync(abs); } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink(); this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE'; else entries = this._readdir(abs, false); return entries }; GlobSync.prototype._readdir = function (abs, inGlobStar) { if (inGlobStar && !ownProp$1(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp$1(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, fs__default['default'].readdirSync(abs)) } catch (er) { this._readdirError(abs, er); return null } }; GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i]; if (abs === '/') e = abs + e; else e = abs + '/' + e; this.cache[e] = true; } } this.cache[abs] = entries; // mark and cache dir-ness return entries }; GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f); this.cache[abs] = 'FILE'; if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd); error.path = this.cwd; error.code = er.code; throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false; break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false; if (this.strict) throw er if (!this.silent) console.error('glob error', er); break } }; GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1); var gspref = prefix ? [ prefix ] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false); var len = entries.length; var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i]; if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar); this._process(instead, index, true); var below = gspref.concat(entries[i], remain); this._process(below, index, true); } }; GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix); if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && pathIsAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix); if (prefix.charAt(0) === '/') { prefix = path__default['default'].join(this.root, prefix); } else { prefix = path__default['default'].resolve(this.root, prefix); if (trail) prefix += '/'; } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match this._emitMatch(index, prefix); }; // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f); var needDir = f.slice(-1) === '/'; if (f.length > this.maxLength) return false if (!this.stat && ownProp$1(this.cache, abs)) { var c = this.cache[abs]; if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var stat = this.statCache[abs]; if (!stat) { var lstat; try { lstat = fs__default['default'].lstatSync(abs); } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false; return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = fs__default['default'].statSync(abs); } catch (er) { stat = lstat; } } else { stat = lstat; } } this.statCache[abs] = stat; var c = true; if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE'; this.cache[abs] = this.cache[abs] || c; if (needDir && c === 'FILE') return false return c }; GlobSync.prototype._mark = function (p) { return common$2.mark(this, p) }; GlobSync.prototype._makeAbs = function (f) { return common$2.makeAbs(this, f) }; // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. var wrappy_1 = wrappy; function wrappy (fn, cb) { if (fn && cb) return wrappy(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k]; }); return wrapper function wrapper() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } var ret = fn.apply(this, args); var cb = args[args.length-1]; if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k]; }); } return ret } } var once_1 = wrappy_1(once); var strict = wrappy_1(onceStrict); once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }); Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }); }); function once (fn) { var f = function () { if (f.called) return f.value f.called = true; return f.value = fn.apply(this, arguments) }; f.called = false; return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true; return f.value = fn.apply(this, arguments) }; var name = fn.name || 'Function wrapped with `once`'; f.onceError = name + " shouldn't be called more than once"; f.called = false; return f } once_1.strict = strict; var reqs = Object.create(null); var inflight_1 = wrappy_1(inflight); function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb); return null } else { reqs[key] = [cb]; return makeres(key) } } function makeres (key) { return once_1(function RES () { var cbs = reqs[key]; var len = cbs.length; var args = slice$2(arguments); // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args); } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len); process.nextTick(function () { RES.apply(null, args); }); } else { delete reqs[key]; } } }) } function slice$2 (args) { var length = args.length; var array = []; for (var i = 0; i < length; i++) array[i] = args[i]; return array } // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. var glob_1 = glob; var EE = events__default['default'].EventEmitter; var setopts$2 = common$2.setopts; var ownProp$2 = common$2.ownProp; var childrenIgnored$2 = common$2.childrenIgnored; var isIgnored$2 = common$2.isIgnored; function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {}; if (!options) options = {}; if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return sync$3(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = sync$3; var GlobSync$1 = glob.GlobSync = sync$3.GlobSync; // old api surface glob.glob = glob; function extend$1 (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin } glob.hasMagic = function (pattern, options_) { var options = extend$1({}, options_); options.noprocess = true; var g = new Glob(pattern, options); var set = g.minimatch.set; if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false }; glob.Glob = Glob; inherits(Glob, EE); function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options; options = null; } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync$1(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts$2(this, pattern, options); this._didRealPath = false; // process each pattern in the minimatch set var n = this.minimatch.set.length; // The matches are stored as {: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n); if (typeof cb === 'function') { cb = once_1(cb); this.on('error', cb); this.on('end', function (matches) { cb(null, matches); }); } var self = this; this._processing = 0; this._emitQueue = []; this._processQueue = []; this.paused = false; if (this.noprocess) return this if (n === 0) return done() var sync = true; for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done); } sync = false; function done () { --self._processing; if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish(); }); } else { self._finish(); } } } } Glob.prototype._finish = function () { assert__default['default'](this instanceof Glob); if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common$2.finish(this); this.emit('end', this.found); }; Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true; var n = this.matches.length; if (n === 0) return this._finish() var self = this; for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next); function next () { if (--n === 0) self._finish(); } }; Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index]; if (!matchset) return cb() var found = Object.keys(matchset); var self = this; var n = found.length; if (n === 0) return cb() var set = this.matches[index] = Object.create(null); found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p); fs_realpath.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true; else if (er.syscall === 'stat') set[p] = true; else self.emit('error', er); // srsly wtf right here if (--n === 0) { self.matches[index] = set; cb(); } }); }); }; Glob.prototype._mark = function (p) { return common$2.mark(this, p) }; Glob.prototype._makeAbs = function (f) { return common$2.makeAbs(this, f) }; Glob.prototype.abort = function () { this.aborted = true; this.emit('abort'); }; Glob.prototype.pause = function () { if (!this.paused) { this.paused = true; this.emit('pause'); } }; Glob.prototype.resume = function () { if (this.paused) { this.emit('resume'); this.paused = false; if (this._emitQueue.length) { var eq = this._emitQueue.slice(0); this._emitQueue.length = 0; for (var i = 0; i < eq.length; i ++) { var e = eq[i]; this._emitMatch(e[0], e[1]); } } if (this._processQueue.length) { var pq = this._processQueue.slice(0); this._processQueue.length = 0; for (var i = 0; i < pq.length; i ++) { var p = pq[i]; this._processing--; this._process(p[0], p[1], p[2], p[3]); } } } }; Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert__default['default'](this instanceof Glob); assert__default['default'](typeof cb === 'function'); if (this.aborted) return this._processing++; if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]); return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0; while (typeof pattern[n] === 'string') { n ++; } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix; switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb); return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null; break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/'); break } var remain = pattern.slice(n); // get the list of entries. var read; if (prefix === null) read = '.'; else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) { if (!prefix || !pathIsAbsolute(prefix)) prefix = '/' + prefix; read = prefix; } else read = prefix; var abs = this._makeAbs(read); //if ignored, skip _processing if (childrenIgnored$2(this, read)) return cb() var isGlobStar = remain[0] === minimatch_1.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); }; Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this; this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }); }; Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === '.'; var matchedEntries = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.charAt(0) !== '.' || dotOk) { var m; if (negate && !prefix) { m = !e.match(pn); } else { m = e.match(pn); } if (m) matchedEntries.push(e); } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length; // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix !== '/') e = prefix + '/' + e; else e = prefix + e; } if (e.charAt(0) === '/' && !this.nomount) { e = path__default['default'].join(this.root, e); } this._emitMatch(index, e); } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift(); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix !== '/') e = prefix + '/' + e; else e = prefix + e; } this._process([e].concat(remain), index, inGlobStar, cb); } cb(); }; Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored$2(this, e)) return if (this.paused) { this._emitQueue.push([index, e]); return } var abs = pathIsAbsolute(e) ? e : this._makeAbs(e); if (this.mark) e = this._mark(e); if (this.absolute) e = abs; if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs]; if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true; var st = this.statCache[abs]; if (st) this.emit('stat', e, st); this.emit('match', e); }; Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs; var self = this; var lstatcb = inflight_1(lstatkey, lstatcb_); if (lstatcb) fs__default['default'].lstat(abs, lstatcb); function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink(); self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE'; cb(); } else self._readdir(abs, false, cb); } }; Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb); if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp$2(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp$2(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } fs__default['default'].readdir(abs, readdirCb(this, abs, cb)); }; function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb); else self._readdirEntries(abs, entries, cb); } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i]; if (abs === '/') e = abs + e; else e = abs + '/' + e; this.cache[e] = true; } } this.cache[abs] = entries; return cb(null, entries) }; Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f); this.cache[abs] = 'FILE'; if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd); error.path = this.cwd; error.code = er.code; this.emit('error', error); this.abort(); } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false; break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false; if (this.strict) { this.emit('error', er); // If the error is handled, then we abort // if not, we threw out of here this.abort(); } if (!this.silent) console.error('glob error', er); break } return cb() }; Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this; this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); }); }; Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1); var gspref = prefix ? [ prefix ] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb); var isSym = this.symlinks[abs]; var len = entries.length; // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i]; if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar); this._process(instead, index, true, cb); var below = gspref.concat(entries[i], remain); this._process(below, index, true, cb); } cb(); }; Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this; this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb); }); }; Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && pathIsAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix); if (prefix.charAt(0) === '/') { prefix = path__default['default'].join(this.root, prefix); } else { prefix = path__default['default'].resolve(this.root, prefix); if (trail) prefix += '/'; } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match this._emitMatch(index, prefix); cb(); }; // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f); var needDir = f.slice(-1) === '/'; if (f.length > this.maxLength) return cb() if (!this.stat && ownProp$2(this.cache, abs)) { var c = this.cache[abs]; if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var stat = this.statCache[abs]; if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE'; if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this; var statcb = inflight_1('stat\0' + abs, lstatcb_); if (statcb) fs__default['default'].lstat(abs, statcb); function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return fs__default['default'].stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb); else self._stat2(f, abs, er, stat, cb); }) } else { self._stat2(f, abs, er, lstat, cb); } } }; Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false; return cb() } var needDir = f.slice(-1) === '/'; this.statCache[abs] = stat; if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true; if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE'; this.cache[abs] = this.cache[abs] || c; if (needDir && c === 'FILE') return cb() return cb(null, c, stat) }; /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ var isBuffer = function isBuffer (obj) { return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) }; var own = {}.hasOwnProperty; var unistUtilStringifyPosition = stringify; function stringify(value) { // Nothing. if (!value || typeof value !== 'object') { return '' } // Node. if (own.call(value, 'position') || own.call(value, 'type')) { return position(value.position) } // Position. if (own.call(value, 'start') || own.call(value, 'end')) { return position(value) } // Point. if (own.call(value, 'line') || own.call(value, 'column')) { return point(value) } // ? return '' } function point(point) { if (!point || typeof point !== 'object') { point = {}; } return index(point.line) + ':' + index(point.column) } function position(pos) { if (!pos || typeof pos !== 'object') { pos = {}; } return point(pos.start) + '-' + point(pos.end) } function index(value) { return value && typeof value === 'number' ? value : 1 } var vfileMessage = VMessage; // Inherit from `Error#`. function VMessagePrototype() {} VMessagePrototype.prototype = Error.prototype; VMessage.prototype = new VMessagePrototype(); // Message properties. var proto = VMessage.prototype; proto.file = ''; proto.name = ''; proto.reason = ''; proto.message = ''; proto.stack = ''; proto.fatal = null; proto.column = null; proto.line = null; // Construct a new VMessage. // // Note: We cannot invoke `Error` on the created context, as that adds readonly // `line` and `column` attributes on Safari 9, thus throwing and failing the // data. function VMessage(reason, position, origin) { var parts; var range; var location; if (typeof position === 'string') { origin = position; position = null; } parts = parseOrigin(origin); range = unistUtilStringifyPosition(position) || '1:1'; location = { start: {line: null, column: null}, end: {line: null, column: null} }; // Node. if (position && position.position) { position = position.position; } if (position) { // Position. if (position.start) { location = position; position = position.start; } else { // Point. location.start = position; } } if (reason.stack) { this.stack = reason.stack; reason = reason.message; } this.message = reason; this.name = range; this.reason = reason; this.line = position ? position.line : null; this.column = position ? position.column : null; this.location = location; this.source = parts[0]; this.ruleId = parts[1]; } function parseOrigin(origin) { var result = [null, null]; var index; if (typeof origin === 'string') { index = origin.indexOf(':'); if (index === -1) { result[1] = origin; } else { result[0] = origin.slice(0, index); result[1] = origin.slice(index + 1); } } return result } function replaceExt(npath, ext) { if (typeof npath !== 'string') { return npath; } if (npath.length === 0) { return npath; } var nFileName = path__default['default'].basename(npath, path__default['default'].extname(npath)) + ext; return path__default['default'].join(path__default['default'].dirname(npath), nFileName); } var replaceExt_1 = replaceExt; var core$1 = VFile; var own$1 = {}.hasOwnProperty; var proto$1 = VFile.prototype; // Order of setting (least specific to most), we need this because otherwise // `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a // stem can be set. var order = ['history', 'path', 'basename', 'stem', 'extname', 'dirname']; proto$1.toString = toString; // Access full path (`~/index.min.js`). Object.defineProperty(proto$1, 'path', {get: getPath, set: setPath}); // Access parent path (`~`). Object.defineProperty(proto$1, 'dirname', {get: getDirname, set: setDirname}); // Access basename (`index.min.js`). Object.defineProperty(proto$1, 'basename', {get: getBasename, set: setBasename}); // Access extname (`.js`). Object.defineProperty(proto$1, 'extname', {get: getExtname, set: setExtname}); // Access stem (`index.min`). Object.defineProperty(proto$1, 'stem', {get: getStem, set: setStem}); // Construct a new file. function VFile(options) { var prop; var index; var length; if (!options) { options = {}; } else if (typeof options === 'string' || isBuffer(options)) { options = {contents: options}; } else if ('message' in options && 'messages' in options) { return options } if (!(this instanceof VFile)) { return new VFile(options) } this.data = {}; this.messages = []; this.history = []; this.cwd = process.cwd(); // Set path related properties in the correct order. index = -1; length = order.length; while (++index < length) { prop = order[index]; if (own$1.call(options, prop)) { this[prop] = options[prop]; } } // Set non-path related properties. for (prop in options) { if (order.indexOf(prop) === -1) { this[prop] = options[prop]; } } } function getPath() { return this.history[this.history.length - 1] } function setPath(path) { assertNonEmpty(path, 'path'); if (path !== this.path) { this.history.push(path); } } function getDirname() { return typeof this.path === 'string' ? path__default['default'].dirname(this.path) : undefined } function setDirname(dirname) { assertPath(this.path, 'dirname'); this.path = path__default['default'].join(dirname || '', this.basename); } function getBasename() { return typeof this.path === 'string' ? path__default['default'].basename(this.path) : undefined } function setBasename(basename) { assertNonEmpty(basename, 'basename'); assertPart(basename, 'basename'); this.path = path__default['default'].join(this.dirname || '', basename); } function getExtname() { return typeof this.path === 'string' ? path__default['default'].extname(this.path) : undefined } function setExtname(extname) { var ext = extname || ''; assertPart(ext, 'extname'); assertPath(this.path, 'extname'); if (ext) { if (ext.charAt(0) !== '.') { throw new Error('`extname` must start with `.`') } if (ext.indexOf('.', 1) !== -1) { throw new Error('`extname` cannot contain multiple dots') } } this.path = replaceExt_1(this.path, ext); } function getStem() { return typeof this.path === 'string' ? path__default['default'].basename(this.path, this.extname) : undefined } function setStem(stem) { assertNonEmpty(stem, 'stem'); assertPart(stem, 'stem'); this.path = path__default['default'].join(this.dirname || '', stem + (this.extname || '')); } // Get the value of the file. function toString(encoding) { var value = this.contents || ''; return isBuffer(value) ? value.toString(encoding) : String(value) } // Assert that `part` is not a path (i.e., does not contain `path.sep`). function assertPart(part, name) { if (part.indexOf(path__default['default'].sep) !== -1) { throw new Error( '`' + name + '` cannot be a path: did not expect `' + path__default['default'].sep + '`' ) } } // Assert that `part` is not empty. function assertNonEmpty(part, name) { if (!part) { throw new Error('`' + name + '` cannot be empty') } } // Assert `path` exists. function assertPath(path, name) { if (!path) { throw new Error('Setting `' + name + '` requires `path` to be set too') } } var vfile = core$1; var proto$2 = core$1.prototype; proto$2.message = message; proto$2.info = info; proto$2.fail = fail; // Create a message with `reason` at `position`. // When an error is passed in as `reason`, copies the stack. function message(reason, position, origin) { var filePath = this.path; var message = new vfileMessage(reason, position, origin); if (filePath) { message.name = filePath + ':' + message.name; message.file = filePath; } message.fatal = false; this.messages.push(message); return message } // Fail: creates a vmessage, associates it with the file, and throws it. function fail() { var message = this.message.apply(this, arguments); message.fatal = true; throw message } // Info: creates a vmessage, associates it with the file, and marks the fatality // as null. function info() { var message = this.message.apply(this, arguments); message.fatal = null; return message } var core$2 = toVFile; // Create a virtual file from a description. If `options` is a string or a // buffer, it’s used as the path. In all other cases, the options are passed // through to `vfile()`. function toVFile(options) { if (typeof options === 'string' || isBuffer(options)) { options = {path: String(options)}; } return vfile(options) } var read$2 = readSync; var write = writeSync; // Create a virtual file and read it in, synchronously. function readSync(description, options) { var file = core$2(description); file.contents = fs__default['default'].readFileSync(path__default['default'].resolve(file.cwd, file.path), options); return file } // Create a virtual file and write it out, synchronously. function writeSync(description, options) { var file = core$2(description); fs__default['default'].writeFileSync( path__default['default'].resolve(file.cwd, file.path), file.contents || '', options ); return file } var sync$4 = { read: read$2, write: write }; var read_1 = read$3; var write_1 = write$1; // Create a virtual file and read it in, asynchronously. function read$3(description, options, callback) { var file = core$2(description); if (!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { return new Promise(executor) } executor(resolve, callback); function resolve(result) { callback(null, result); } function executor(resolve, reject) { var fp; try { fp = path__default['default'].resolve(file.cwd, file.path); } catch (error) { return reject(error) } fs__default['default'].readFile(fp, options, done); function done(error, res) { if (error) { reject(error); } else { file.contents = res; resolve(file); } } } } // Create a virtual file and write it out, asynchronously. function write$1(description, options, callback) { var file = core$2(description); // Weird, right? Otherwise `fs` doesn’t accept it. if (!callback && typeof options === 'function') { callback = options; options = undefined; } if (!callback) { return new Promise(executor) } executor(resolve, callback); function resolve(result) { callback(null, result); } function executor(resolve, reject) { var fp; try { fp = path__default['default'].resolve(file.cwd, file.path); } catch (error) { return reject(error) } fs__default['default'].writeFile(fp, file.contents || '', options, done); function done(error) { if (error) { reject(error); } else { resolve(file); } } } } var async = { read: read_1, write: write_1 }; var fs = core$2; core$2.read = async.read; core$2.readSync = sync$4.read; core$2.write = async.write; core$2.writeSync = sync$4.write; var toVfile = fs; var readdir = fs__default['default'].readdir; var stat = fs__default['default'].stat; var sep$1 = path__default['default'].sep; var join$1 = path__default['default'].join; var relative$2 = path__default['default'].relative; var resolve$3 = path__default['default'].resolve; var basename = path__default['default'].basename; var extname = path__default['default'].extname; var magic = glob_1.hasMagic; var finder$1 = find; // Search `patterns`, a mix of globs, paths, and files. function find(input, options, callback) { expand$1(input, options, done); function done(error, result) { /* istanbul ignore if - glob errors are unusual. * other errors are on the vfile results. */ if (error) { callback(error); } else { callback(null, {oneFileMode: oneFileMode(result), files: result.output}); } } } // Expand the given glob patterns, search given and found directories, and map // to vfiles. function expand$1(input, options, next) { var cwd = options.cwd; var paths = []; var actual = 0; var expected = 0; var failed; input.forEach(each); if (!expected) { search(paths, options, done); } function each(file) { if (typeof file === 'string') { if (magic(file)) { expected++; glob_1(file, {cwd: cwd}, one); } else { // `relative` to make the paths canonical. file = relative$2(cwd, resolve$3(cwd, file)) || '.'; paths.push(file); } } else { file.cwd = cwd; file.path = relative$2(cwd, file.path); file.history = [file.path]; paths.push(file); } } function one(error, files) { /* istanbul ignore if - Glob errors are unusual. */ if (failed) { return } /* istanbul ignore if - Glob errors are unusual. */ if (error) { failed = true; done(error); } else { actual++; paths = paths.concat(files); if (actual === expected) { search(paths, options, done); } } } function done(error, files) { /* istanbul ignore if - `search` currently does not give errors. */ if (error) { next(error); } else { next(null, {input: paths, output: files}); } } } // Search `paths`. function search(input, options, next) { var cwd = options.cwd; var silent = options.silentlyIgnore; var nested = options.nested; var extensions = options.extensions; var extraIgnore = ignore().add(options.ignorePatterns); var files = []; var expected = 0; var actual = 0; input.forEach(each); if (!expected) { next(null, files); } return each function each(file) { var ext = typeof file === 'string' ? extname(file) : file.extname; var part; // Normalise globs. if (typeof file === 'string') { file = file.split('/').join(path__default['default'].sep); } part = base(file); if (nested && (part.charAt(0) === '.' || part === 'node_modules')) { return } expected++; statAndIgnore( file, Object.assign({}, options, {extraIgnore: extraIgnore}), handle ); function handle(error, result) { var ignored = result && result.ignored; var dir = result && result.stats && result.stats.isDirectory(); if (ignored && (nested || silent)) { return one(null, []) } if (!ignored && dir) { return readdir(resolve$3(cwd, filePath(file)), directory) } if ( nested && !dir && extensions.length !== 0 && extensions.indexOf(ext) === -1 ) { return one(null, []) } file = toVfile(file); file.cwd = cwd; if (ignored) { try { file.fail('Cannot process specified file: it’s ignored'); } catch (_) {} } if (error && error.code === 'ENOENT') { try { file.fail( error.syscall === 'stat' ? 'No such file or directory' : error ); } catch (_) {} } one(null, [file]); } function directory(error, basenames) { var file; /* istanbul ignore if - Should not happen often: the directory is `stat`ed * first, which was ok, but reading it is not. */ if (error) { file = toVfile(filePath(file)); file.cwd = cwd; try { file.fail('Cannot read directory'); } catch (_) {} one(null, [file]); } else { search( basenames.map(concat), Object.assign({}, options, {nested: true}), one ); } } // Error is never given. Always given `results`. function one(_, results) { /* istanbul ignore else - Always given. */ if (results) { files = files.concat(results); } actual++; if (actual === expected) { next(null, files); } } function concat(value) { return join$1(filePath(file), value) } } } function statAndIgnore(file, options, callback) { var ignore = options.ignore; var extraIgnore = options.extraIgnore; var cwd = options.cwd; var fp = resolve$3(cwd, filePath(file)); var normal = relative$2(cwd, fp); var expected = 1; var actual = 0; var stats; var ignored; if (!file.contents) { expected++; stat(fp, handleStat); } ignore.check(fp, handleIgnore); function handleStat(error, value) { stats = value; one(error); } function handleIgnore(error, value) { ignored = value; one(error); } function one(error) { actual++; if (error) { callback(error); actual = -1; } else if (actual === expected) { callback(null, { stats: stats, ignored: ignored || (normal === '' || normal === '..' || normal.charAt(0) === sep$1 || normal.slice(0, 3) === '..' + sep$1 ? false : extraIgnore.ignores(normal)) }); } } } function base(file) { return typeof file === 'string' ? basename(file) : file.basename } function filePath(file) { return typeof file === 'string' ? file : file.path } function oneFileMode(result) { return ( result.output.length === 1 && result.input.length === 1 && result.output[0].path === result.input[0] ) } var fileSystem_1 = fileSystem; // Find files from the file-system. function fileSystem(context, settings, next) { var input = context.files; if (input.length === 0) { next(); } else { finder$1( input, { cwd: settings.cwd, extensions: settings.extensions, silentlyIgnore: settings.silentlyIgnore, ignorePatterns: settings.ignorePatterns, ignore: new ignore$1({ cwd: settings.cwd, detectIgnore: settings.detectIgnore, ignoreName: settings.ignoreName, ignorePath: settings.ignorePath, ignorePathResolveFrom: settings.ignorePathResolveFrom }) }, onfound ); } function onfound(error, result) { var output = result.files; // Sort alphabetically. // Everything is unique so we do not care about cases where left and right // are equal. output.sort(sortAlphabetically); // Mark as given. // This allows outputting files, which can be pretty dangerous, so it’s // “hidden”. output.forEach(markAsGiven); context.files = output; // If `out` was not set, detect it based on whether one file was given. if (settings.out === null || settings.out === undefined) { settings.out = result.oneFileMode; } next(error); } function markAsGiven(file) { file.data.unifiedEngineGiven = true; } function sortAlphabetically(left, right) { return left.path < right.path ? -1 : 1 } } var toString$1 = Object.prototype.toString; var isModern = ( typeof Buffer.alloc === 'function' && typeof Buffer.allocUnsafe === 'function' && typeof Buffer.from === 'function' ); function isArrayBuffer (input) { return toString$1.call(input).slice(8, -1) === 'ArrayBuffer' } function fromArrayBuffer (obj, byteOffset, length) { byteOffset >>>= 0; var maxLength = obj.byteLength - byteOffset; if (maxLength < 0) { throw new RangeError("'offset' is out of bounds") } if (length === undefined) { length = maxLength; } else { length >>>= 0; if (length > maxLength) { throw new RangeError("'length' is out of bounds") } } return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } return isModern ? Buffer.from(string, encoding) : new Buffer(string, encoding) } function bufferFrom (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (isArrayBuffer(value)) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(value, encodingOrOffset) } return isModern ? Buffer.from(value) : new Buffer(value) } var bufferFrom_1 = bufferFrom; var typedarray = createCommonjsModule(function (module, exports) { var undefined$1 = (void 0); // Paranoia // Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to // create, and consume so much memory, that the browser appears frozen. var MAX_ARRAY_LENGTH = 1e5; // Approximations of internal ECMAScript conversion functions var ECMAScript = (function() { // Stash a copy in case other scripts modify these var opts = Object.prototype.toString, ophop = Object.prototype.hasOwnProperty; return { // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); }, HasProperty: function(o, p) { return p in o; }, HasOwnProperty: function(o, p) { return ophop.call(o, p); }, IsCallable: function(o) { return typeof o === 'function'; }, ToInt32: function(v) { return v >> 0; }, ToUint32: function(v) { return v >>> 0; } }; }()); // Snapshot intrinsics var LN2 = Math.LN2, abs = Math.abs, floor = Math.floor, log = Math.log, min = Math.min, pow = Math.pow, round = Math.round; // ES5: lock down object properties function configureProperties(obj) { if (getOwnPropNames && defineProp) { var props = getOwnPropNames(obj), i; for (i = 0; i < props.length; i += 1) { defineProp(obj, props[i], { value: obj[props[i]], writable: false, enumerable: false, configurable: false }); } } } // emulate ES5 getter/setter API using legacy APIs // http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx // (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but // note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless) var defineProp; if (Object.defineProperty && (function() { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { return false; } })()) { defineProp = Object.defineProperty; } else { defineProp = function(o, p, desc) { if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object"); if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); } if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); } if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; } return o; }; } var getOwnPropNames = Object.getOwnPropertyNames || function (o) { if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object"); var props = [], p; for (p in o) { if (ECMAScript.HasOwnProperty(o, p)) { props.push(p); } } return props; }; // ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value) // for index in 0 ... obj.length function makeArrayAccessors(obj) { if (!defineProp) { return; } if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill"); function makeArrayAccessor(index) { defineProp(obj, index, { 'get': function() { return obj._getter(index); }, 'set': function(v) { obj._setter(index, v); }, enumerable: true, configurable: false }); } var i; for (i = 0; i < obj.length; i += 1) { makeArrayAccessor(i); } } // Internal conversion functions: // pack() - take a number (interpreted as Type), output a byte array // unpack() - take a byte array, output a Type-like number function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; } function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; } function packI8(n) { return [n & 0xff]; } function unpackI8(bytes) { return as_signed(bytes[0], 8); } function packU8(n) { return [n & 0xff]; } function unpackU8(bytes) { return as_unsigned(bytes[0], 8); } function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; } function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; } function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); } function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; } function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); } function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, i, bits, str, bytes; function roundToEven(n) { var w = floor(n), f = n - w; if (f < 0.5) return w; if (f > 0.5) return w + 1; return w % 2 ? w + 1 : w; } // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = abs(v); if (v >= pow(2, 1 - bias)) { e = min(floor(log(v) / LN2), 1023); f = roundToEven(v / pow(2, e) * pow(2, fbits)); if (f / pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normalized e = e + bias; f = f - pow(2, fbits); } } else { // Denormalized e = 0; f = roundToEven(v / pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.substring(0, 8), 2)); str = str.substring(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.substring(0, 1), 2) ? -1 : 1; e = parseInt(str.substring(1, 1 + ebits), 2); f = parseInt(str.substring(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackF64(b) { return unpackIEEE754(b, 11, 52); } function packF64(v) { return packIEEE754(v, 11, 52); } function unpackF32(b) { return unpackIEEE754(b, 8, 23); } function packF32(v) { return packIEEE754(v, 8, 23); } // // 3 The ArrayBuffer Type // (function() { /** @constructor */ var ArrayBuffer = function ArrayBuffer(length) { length = ECMAScript.ToInt32(length); if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer'); this.byteLength = length; this._bytes = []; this._bytes.length = length; var i; for (i = 0; i < this.byteLength; i += 1) { this._bytes[i] = 0; } configureProperties(this); }; exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer; // // 4 The ArrayBufferView Type // // NOTE: this constructor is not exported /** @constructor */ var ArrayBufferView = function ArrayBufferView() { //this.buffer = null; //this.byteOffset = 0; //this.byteLength = 0; }; // // 5 The Typed Array View Types // function makeConstructor(bytesPerElement, pack, unpack) { // Each TypedArray type requires a distinct constructor instance with // identical logic, which this produces. var ctor; ctor = function(buffer, byteOffset, length) { var array, sequence, i, s; if (!arguments.length || typeof arguments[0] === 'number') { // Constructor(unsigned long length) this.length = ECMAScript.ToInt32(arguments[0]); if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer'); this.byteLength = this.length * this.BYTES_PER_ELEMENT; this.buffer = new ArrayBuffer(this.byteLength); this.byteOffset = 0; } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) { // Constructor(TypedArray array) array = arguments[0]; this.length = array.length; this.byteLength = this.length * this.BYTES_PER_ELEMENT; this.buffer = new ArrayBuffer(this.byteLength); this.byteOffset = 0; for (i = 0; i < this.length; i += 1) { this._setter(i, array._getter(i)); } } else if (typeof arguments[0] === 'object' && !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { // Constructor(sequence array) sequence = arguments[0]; this.length = ECMAScript.ToUint32(sequence.length); this.byteLength = this.length * this.BYTES_PER_ELEMENT; this.buffer = new ArrayBuffer(this.byteLength); this.byteOffset = 0; for (i = 0; i < this.length; i += 1) { s = sequence[i]; this._setter(i, Number(s)); } } else if (typeof arguments[0] === 'object' && (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { // Constructor(ArrayBuffer buffer, // optional unsigned long byteOffset, optional unsigned long length) this.buffer = buffer; this.byteOffset = ECMAScript.ToUint32(byteOffset); if (this.byteOffset > this.buffer.byteLength) { throw new RangeError("byteOffset out of range"); } if (this.byteOffset % this.BYTES_PER_ELEMENT) { // The given byteOffset must be a multiple of the element // size of the specific type, otherwise an exception is raised. throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size."); } if (arguments.length < 3) { this.byteLength = this.buffer.byteLength - this.byteOffset; if (this.byteLength % this.BYTES_PER_ELEMENT) { throw new RangeError("length of buffer minus byteOffset not a multiple of the element size"); } this.length = this.byteLength / this.BYTES_PER_ELEMENT; } else { this.length = ECMAScript.ToUint32(length); this.byteLength = this.length * this.BYTES_PER_ELEMENT; } if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); } } else { throw new TypeError("Unexpected argument type(s)"); } this.constructor = ctor; configureProperties(this); makeArrayAccessors(this); }; ctor.prototype = new ArrayBufferView(); ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; ctor.prototype._pack = pack; ctor.prototype._unpack = unpack; ctor.BYTES_PER_ELEMENT = bytesPerElement; // getter type (unsigned long index); ctor.prototype._getter = function(index) { if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); index = ECMAScript.ToUint32(index); if (index >= this.length) { return undefined$1; } var bytes = [], i, o; for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; i < this.BYTES_PER_ELEMENT; i += 1, o += 1) { bytes.push(this.buffer._bytes[o]); } return this._unpack(bytes); }; // NONSTANDARD: convenience alias for getter: type get(unsigned long index); ctor.prototype.get = ctor.prototype._getter; // setter void (unsigned long index, type value); ctor.prototype._setter = function(index, value) { if (arguments.length < 2) throw new SyntaxError("Not enough arguments"); index = ECMAScript.ToUint32(index); if (index >= this.length) { return undefined$1; } var bytes = this._pack(value), i, o; for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; i < this.BYTES_PER_ELEMENT; i += 1, o += 1) { this.buffer._bytes[o] = bytes[i]; } }; // void set(TypedArray array, optional unsigned long offset); // void set(sequence array, optional unsigned long offset); ctor.prototype.set = function(index, value) { if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); var array, sequence, offset, len, i, s, d, byteOffset, byteLength, tmp; if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) { // void set(TypedArray array, optional unsigned long offset); array = arguments[0]; offset = ECMAScript.ToUint32(arguments[1]); if (offset + array.length > this.length) { throw new RangeError("Offset plus length of array is out of range"); } byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; byteLength = array.length * this.BYTES_PER_ELEMENT; if (array.buffer === this.buffer) { tmp = []; for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) { tmp[i] = array.buffer._bytes[s]; } for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) { this.buffer._bytes[d] = tmp[i]; } } else { for (i = 0, s = array.byteOffset, d = byteOffset; i < byteLength; i += 1, s += 1, d += 1) { this.buffer._bytes[d] = array.buffer._bytes[s]; } } } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') { // void set(sequence array, optional unsigned long offset); sequence = arguments[0]; len = ECMAScript.ToUint32(sequence.length); offset = ECMAScript.ToUint32(arguments[1]); if (offset + len > this.length) { throw new RangeError("Offset plus length of array is out of range"); } for (i = 0; i < len; i += 1) { s = sequence[i]; this._setter(offset + i, Number(s)); } } else { throw new TypeError("Unexpected argument type(s)"); } }; // TypedArray subarray(long begin, optional long end); ctor.prototype.subarray = function(start, end) { function clamp(v, min, max) { return v < min ? min : v > max ? max : v; } start = ECMAScript.ToInt32(start); end = ECMAScript.ToInt32(end); if (arguments.length < 1) { start = 0; } if (arguments.length < 2) { end = this.length; } if (start < 0) { start = this.length + start; } if (end < 0) { end = this.length + end; } start = clamp(start, 0, this.length); end = clamp(end, 0, this.length); var len = end - start; if (len < 0) { len = 0; } return new this.constructor( this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len); }; return ctor; } var Int8Array = makeConstructor(1, packI8, unpackI8); var Uint8Array = makeConstructor(1, packU8, unpackU8); var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8); var Int16Array = makeConstructor(2, packI16, unpackI16); var Uint16Array = makeConstructor(2, packU16, unpackU16); var Int32Array = makeConstructor(4, packI32, unpackI32); var Uint32Array = makeConstructor(4, packU32, unpackU32); var Float32Array = makeConstructor(4, packF32, unpackF32); var Float64Array = makeConstructor(8, packF64, unpackF64); exports.Int8Array = exports.Int8Array || Int8Array; exports.Uint8Array = exports.Uint8Array || Uint8Array; exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray; exports.Int16Array = exports.Int16Array || Int16Array; exports.Uint16Array = exports.Uint16Array || Uint16Array; exports.Int32Array = exports.Int32Array || Int32Array; exports.Uint32Array = exports.Uint32Array || Uint32Array; exports.Float32Array = exports.Float32Array || Float32Array; exports.Float64Array = exports.Float64Array || Float64Array; }()); // // 6 The DataView View Type // (function() { function r(array, index) { return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index]; } var IS_BIG_ENDIAN = (function() { var u16array = new(exports.Uint16Array)([0x1234]), u8array = new(exports.Uint8Array)(u16array.buffer); return r(u8array, 0) === 0x12; }()); // Constructor(ArrayBuffer buffer, // optional unsigned long byteOffset, // optional unsigned long byteLength) /** @constructor */ var DataView = function DataView(buffer, byteOffset, byteLength) { if (arguments.length === 0) { buffer = new exports.ArrayBuffer(0); } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) { throw new TypeError("TypeError"); } this.buffer = buffer || new exports.ArrayBuffer(0); this.byteOffset = ECMAScript.ToUint32(byteOffset); if (this.byteOffset > this.buffer.byteLength) { throw new RangeError("byteOffset out of range"); } if (arguments.length < 3) { this.byteLength = this.buffer.byteLength - this.byteOffset; } else { this.byteLength = ECMAScript.ToUint32(byteLength); } if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); } configureProperties(this); }; function makeGetter(arrayType) { return function(byteOffset, littleEndian) { byteOffset = ECMAScript.ToUint32(byteOffset); if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { throw new RangeError("Array index out of range"); } byteOffset += this.byteOffset; var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT), bytes = [], i; for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { bytes.push(r(uint8Array, i)); } if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { bytes.reverse(); } return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0); }; } DataView.prototype.getUint8 = makeGetter(exports.Uint8Array); DataView.prototype.getInt8 = makeGetter(exports.Int8Array); DataView.prototype.getUint16 = makeGetter(exports.Uint16Array); DataView.prototype.getInt16 = makeGetter(exports.Int16Array); DataView.prototype.getUint32 = makeGetter(exports.Uint32Array); DataView.prototype.getInt32 = makeGetter(exports.Int32Array); DataView.prototype.getFloat32 = makeGetter(exports.Float32Array); DataView.prototype.getFloat64 = makeGetter(exports.Float64Array); function makeSetter(arrayType) { return function(byteOffset, value, littleEndian) { byteOffset = ECMAScript.ToUint32(byteOffset); if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { throw new RangeError("Array index out of range"); } // Get bytes var typeArray = new arrayType([value]), byteArray = new exports.Uint8Array(typeArray.buffer), bytes = [], i, byteView; for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { bytes.push(r(byteArray, i)); } // Flip if necessary if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { bytes.reverse(); } // Write them byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT); byteView.set(bytes); }; } DataView.prototype.setUint8 = makeSetter(exports.Uint8Array); DataView.prototype.setInt8 = makeSetter(exports.Int8Array); DataView.prototype.setUint16 = makeSetter(exports.Uint16Array); DataView.prototype.setInt16 = makeSetter(exports.Int16Array); DataView.prototype.setUint32 = makeSetter(exports.Uint32Array); DataView.prototype.setInt32 = makeSetter(exports.Int32Array); DataView.prototype.setFloat32 = makeSetter(exports.Float32Array); DataView.prototype.setFloat64 = makeSetter(exports.Float64Array); exports.DataView = exports.DataView || DataView; }()); }); var typedarray_1 = typedarray.ArrayBuffer; var typedarray_2 = typedarray.Int8Array; var typedarray_3 = typedarray.Uint8Array; var typedarray_4 = typedarray.Uint8ClampedArray; var typedarray_5 = typedarray.Int16Array; var typedarray_6 = typedarray.Uint16Array; var typedarray_7 = typedarray.Int32Array; var typedarray_8 = typedarray.Uint32Array; var typedarray_9 = typedarray.Float32Array; var typedarray_10 = typedarray.Float64Array; var typedarray_11 = typedarray.DataView; var Writable = stream__default['default'].Writable; if (typeof Uint8Array === 'undefined') { var U8 = typedarray.Uint8Array; } else { var U8 = Uint8Array; } function ConcatStream(opts, cb) { if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb) if (typeof opts === 'function') { cb = opts; opts = {}; } if (!opts) opts = {}; var encoding = opts.encoding; var shouldInferEncoding = false; if (!encoding) { shouldInferEncoding = true; } else { encoding = String(encoding).toLowerCase(); if (encoding === 'u8' || encoding === 'uint8') { encoding = 'uint8array'; } } Writable.call(this, { objectMode: true }); this.encoding = encoding; this.shouldInferEncoding = shouldInferEncoding; if (cb) this.on('finish', function () { cb(this.getBody()); }); this.body = []; } var concatStream = ConcatStream; inherits(ConcatStream, Writable); ConcatStream.prototype._write = function(chunk, enc, next) { this.body.push(chunk); next(); }; ConcatStream.prototype.inferEncoding = function (buff) { var firstBuffer = buff === undefined ? this.body[0] : buff; if (Buffer.isBuffer(firstBuffer)) return 'buffer' if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array' if (Array.isArray(firstBuffer)) return 'array' if (typeof firstBuffer === 'string') return 'string' if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object' return 'buffer' }; ConcatStream.prototype.getBody = function () { if (!this.encoding && this.body.length === 0) return [] if (this.shouldInferEncoding) this.encoding = this.inferEncoding(); if (this.encoding === 'array') return arrayConcat(this.body) if (this.encoding === 'string') return stringConcat(this.body) if (this.encoding === 'buffer') return bufferConcat(this.body) if (this.encoding === 'uint8array') return u8Concat(this.body) return this.body }; function isArrayish$1 (arr) { return /Array\]$/.test(Object.prototype.toString.call(arr)) } function isBufferish (p) { return typeof p === 'string' || isArrayish$1(p) || (p && typeof p.subarray === 'function') } function stringConcat (parts) { var strings = []; for (var i = 0; i < parts.length; i++) { var p = parts[i]; if (typeof p === 'string') { strings.push(p); } else if (Buffer.isBuffer(p)) { strings.push(p); } else if (isBufferish(p)) { strings.push(bufferFrom_1(p)); } else { strings.push(bufferFrom_1(String(p))); } } if (Buffer.isBuffer(parts[0])) { strings = Buffer.concat(strings); strings = strings.toString('utf8'); } else { strings = strings.join(''); } return strings } function bufferConcat (parts) { var bufs = []; for (var i = 0; i < parts.length; i++) { var p = parts[i]; if (Buffer.isBuffer(p)) { bufs.push(p); } else if (isBufferish(p)) { bufs.push(bufferFrom_1(p)); } else { bufs.push(bufferFrom_1(String(p))); } } return Buffer.concat(bufs) } function arrayConcat (parts) { var res = []; for (var i = 0; i < parts.length; i++) { res.push.apply(res, parts[i]); } return res } function u8Concat (parts) { var len = 0; for (var i = 0; i < parts.length; i++) { if (typeof parts[i] === 'string') { parts[i] = bufferFrom_1(parts[i]); } len += parts[i].length; } var u8 = new U8(len); for (var i = 0, offset = 0; i < parts.length; i++) { var part = parts[i]; for (var j = 0; j < part.length; j++) { u8[offset++] = part[j]; } } return u8 } var debug$1 = src('unified-engine:file-set-pipeline:stdin'); var stdin_1 = stdin; function stdin(context, settings, next) { var streamIn = settings.streamIn; var error; if (settings.files && settings.files.length !== 0) { debug$1('Ignoring `streamIn`'); if (settings.filePath) { error = new Error( 'Do not pass both `--file-path` and real files.\nDid you mean to pass stdin instead of files?' ); } next(error); return } if (streamIn.isTTY) { debug$1('Cannot read from `tty` stream'); next(new Error('No input')); return } debug$1('Reading from `streamIn`'); streamIn.pipe(concatStream({encoding: 'string'}, read)); function read(value) { var file = toVfile(settings.filePath || undefined); debug$1('Read from `streamIn`'); file.cwd = settings.cwd; file.contents = value; file.data.unifiedEngineGiven = true; file.data.unifiedEngineStreamIn = true; context.files = [file]; // If `out` was not set, set `out`. settings.out = settings.out === null || settings.out === undefined ? true : settings.out; next(); } } var inherits$1 = util__default['default'].inherits; var fileSet = FileSet; // FileSet constructor. function FileSet() { var self = this; self.files = []; self.origins = []; self.expected = 0; self.actual = 0; self.pipeline = trough_1(); self.plugins = []; events__default['default'].init.call(self); self.on('one', one.bind(self)); } // Events. inherits$1(FileSet, events__default['default'].EventEmitter); // Expose methods. FileSet.prototype.valueOf = valueOf; FileSet.prototype.use = use; FileSet.prototype.add = add; // Create an array representation of `fileSet`. function valueOf() { return this.files } // Attach middleware to the pipeline on `fileSet`. function use(plugin) { var self = this; var pipeline = self.pipeline; var duplicate = false; if (plugin && plugin.pluginId) { duplicate = self.plugins.some(matches); } if (!duplicate && self.plugins.indexOf(plugin) !== -1) { duplicate = true; } if (!duplicate) { self.plugins.push(plugin); pipeline.use(plugin); } return self function matches(fn) { return fn.pluginId === plugin.pluginId } } // Add a file to be processed. // Ignores duplicate files (based on the `filePath` at time of addition). // Only runs `file-pipeline` on files which have not `failed` before addition. function add(file) { var self = this; var origin; if (typeof file === 'string') { file = toVfile(file); } // Prevent files from being added multiple times. origin = file.history[0]; if (self.origins.indexOf(origin) !== -1) { return self } self.origins.push(origin); // Add. self.valueOf().push(file); self.expected++; // Force an asynchronous operation. // This ensures that files which fall through the file pipeline immediately // (such as, when already fatally failed) still queue up correctly. setImmediate(add); return self function add() { self.emit('add', file); } } // Utility invoked when a single file has completed it's pipeline, triggering // `done` when all files are complete. function one() { var self = this; self.actual++; if (self.actual >= self.expected) { self.emit('done'); } } var debug$2 = src('unified-engine:file-pipeline:read'); var read_1$1 = read$4; var resolve$4 = path__default['default'].resolve; var readFile = fs__default['default'].readFile; // Fill a file with its contents when not already filled. function read$4(context, file, fileSet, next) { var filePath = file.path; if (file.contents || file.data.unifiedEngineStreamIn) { debug$2('Not reading file `%s` with contents', filePath); next(); } else if (vfileStatistics(file).fatal) { debug$2('Not reading failed file `%s`', filePath); next(); } else { filePath = resolve$4(context.cwd, filePath); debug$2('Reading `%s` in `%s`', filePath, 'utf8'); readFile(filePath, 'utf8', onread); } function onread(error, contents) { debug$2('Read `%s` (error: %s)', filePath, error); file.contents = contents || ''; next(error); } } /** * Has own property. * * @type {Function} */ var has = Object.prototype.hasOwnProperty; /** * To string. * * @type {Function} */ var toString$2 = Object.prototype.toString; /** * Test whether a value is "empty". * * @param {Mixed} val * @return {Boolean} */ function isEmpty(val) { // Null and Undefined... if (val == null) return true // Booleans... if ('boolean' == typeof val) return false // Numbers... if ('number' == typeof val) return val === 0 // Strings... if ('string' == typeof val) return val.length === 0 // Functions... if ('function' == typeof val) return val.length === 0 // Arrays... if (Array.isArray(val)) return val.length === 0 // Errors... if (val instanceof Error) return val.message === '' // Objects... if (val.toString == toString$2) { switch (val.toString()) { // Maps, Sets, Files and Errors... case '[object File]': case '[object Map]': case '[object Set]': { return val.size === 0 } // Plain objects... case '[object Object]': { for (var key in val) { if (has.call(val, key)) return false } return true } } } // Anything else... return false } /** * Export `isEmpty`. * * @type {Function} */ var lib$3 = isEmpty; var debug$3 = src('unified-engine:file-pipeline:configure'); var configure_1$1 = configure$1; // Collect configuration for a file based on the context. function configure$1(context, file, fileSet, next) { var config = context.configuration; var processor = context.processor; if (vfileStatistics(file).fatal) { return next() } config.load(file.path, handleConfiguration); function handleConfiguration(error, configuration) { var plugins; var options; var plugin; var length; var index; var name; if (error) { return next(error) } // Store configuration on the context object. debug$3('Using settings `%j`', configuration.settings); processor.data('settings', configuration.settings); plugins = configuration.plugins; length = plugins.length; index = -1; debug$3('Using `%d` plugins', length); while (++index < length) { plugin = plugins[index][0]; options = plugins[index][1]; if (options === false) { continue } // Allow for default arguments in es2020. if (options === null || (typeof options === 'object' && lib$3(options))) { options = undefined; } name = plugin.displayName || plugin.name || 'function'; debug$3('Using plugin `%s`, with options `%j`', name, options); try { processor.use(plugin, options, fileSet); } catch (error_) { /* istanbul ignore next - Should not happen anymore! */ return next(error_) } } next(); } } var debug$4 = src('unified-engine:file-pipeline:parse'); var parse_1 = parse$3; // Fill a file with a tree. function parse$3(context, file) { var message; if (vfileStatistics(file).fatal) { return } if (context.treeIn) { debug$4('Not parsing already parsed document'); try { context.tree = parseJson$1(file.toString()); } catch (error) { message = file.message( new Error('Cannot read file as JSON\n' + error.message) ); message.fatal = true; } // Add the preferred extension to ensure the file, when serialized, is // correctly recognised. // Only add it if there is a path — not if the file is for example stdin. if (file.path) { file.extname = context.extensions[0]; } file.contents = ''; return } debug$4('Parsing `%s`', file.path); context.tree = context.processor.parse(file); debug$4('Parsed document'); } var debug$5 = src('unified-engine:file-pipeline:transform'); var transform_1 = transform; // Transform the tree associated with a file with configured plugins. function transform(context, file, fileSet, next) { if (vfileStatistics(file).fatal) { next(); } else { debug$5('Transforming document `%s`', file.path); context.processor.run(context.tree, file, onrun); } function onrun(error, node) { debug$5('Transformed document (error: %s)', error); context.tree = node; next(error); } } var debug$6 = src('unified-engine:file-pipeline:queue'); var queue_1 = queue; // Queue all files which came this far. // When the last file gets here, run the file-set pipeline and flush the queue. function queue(context, file, fileSet, next) { var origin = file.history[0]; var map = fileSet.complete; var complete = true; if (!map) { map = {}; fileSet.complete = map; } debug$6('Queueing `%s`', origin); map[origin] = next; fileSet.valueOf().forEach(each); if (!complete) { debug$6('Not flushing: some files cannot be flushed'); return } fileSet.complete = {}; fileSet.pipeline.run(fileSet, done); function each(file) { var key = file.history[0]; if (vfileStatistics(file).fatal) { return } if (typeof map[key] === 'function') { debug$6('`%s` can be flushed', key); } else { debug$6('Interupting flush: `%s` is not finished', key); complete = false; } } function done(error) { debug$6('Flushing: all files can be flushed'); // Flush. for (origin in map) { map[origin](error); } } } // Detect color support. var color = true; try { color = 'inspect' in util__default['default']; } catch (_) { /* istanbul ignore next - browser */ color = false; } var unistUtilInspect = color ? inspect : /* istanbul ignore next */ noColor; inspect.color = inspect; noColor.color = inspect; inspect.noColor = noColor; noColor.noColor = noColor; var dim = ansiColor(2, 22); var yellow = ansiColor(33, 39); var green = ansiColor(32, 39); // Define ANSII color removal functionality. var colorExpression = new RegExp( '(?:' + '(?:\\u001b\\[)|' + '\\u009b' + ')' + '(?:' + '(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m]' + ')|' + '\\u001b[A-M]', 'g' ); // Standard keys defined by unist: https://github.com/syntax-tree/unist. // We don’t ignore `data` though. var ignore$2 = ['type', 'value', 'children', 'position']; // Inspects a node, without using color. function noColor(node, pad) { return stripColor(inspect(node, pad)) } // Inspects a node. function inspect(node, pad) { var result; var children; var index; var length; if (node && Boolean(node.length) && typeof node !== 'string') { length = node.length; index = -1; result = []; while (++index < length) { result[index] = inspect(node[index]); } return result.join('\n') } if (!node || !node.type) { return String(node) } result = [formatNode(node)]; children = node.children; length = children && children.length; index = -1; if (!length) { return result[0] } if (!pad || typeof pad === 'number') { pad = ''; } while (++index < length) { node = children[index]; if (index === length - 1) { result.push(formatNesting(pad + '└─ ') + inspect(node, pad + ' ')); } else { result.push(formatNesting(pad + '├─ ') + inspect(node, pad + '│ ')); } } return result.join('\n') } // Colored nesting formatter. function formatNesting(value) { return dim(value) } // Compile a single position. function compile(pos) { var values = []; if (!pos) { return null } values = [[pos.line || 1, pos.column || 1].join(':')]; if ('offset' in pos) { values.push(String(pos.offset || 0)); } return values } // Compile a location. function stringify$1(start, end) { var values = []; var positions = []; var offsets = []; add(start); add(end); if (positions.length !== 0) { values.push(positions.join('-')); } if (offsets.length !== 0) { values.push(offsets.join('-')); } return values.join(', ') // Add a position. function add(position) { var tuple = compile(position); if (tuple) { positions.push(tuple[0]); if (tuple[1]) { offsets.push(tuple[1]); } } } } // Colored node formatter. function formatNode(node) { var log = node.type; var location = node.position || {}; var position = stringify$1(location.start, location.end); var key; var values = []; var value; if (node.children) { log += dim('[') + yellow(node.children.length) + dim(']'); } else if (typeof node.value === 'string') { log += dim(': ') + green(JSON.stringify(node.value)); } if (position) { log += ' (' + position + ')'; } for (key in node) { value = node[key]; if ( ignore$2.indexOf(key) !== -1 || value === null || value === undefined || (typeof value === 'object' && lib$3(value)) ) { continue } values.push('[' + key + '=' + JSON.stringify(value) + ']'); } if (values.length !== 0) { log += ' ' + values.join(''); } return log } // Remove ANSI colour from `value`. function stripColor(value) { return value.replace(colorExpression, '') } // Factory to wrap values in ANSI colours. function ansiColor(open, close) { return color function color(value) { return '\u001B[' + open + 'm' + value + '\u001B[' + close + 'm' } } var debug$7 = src('unified-engine:file-pipeline:stringify'); var stringify_1 = stringify$2; // Stringify a tree. function stringify$2(context, file) { var processor = context.processor; var tree = context.tree; var value; if (vfileStatistics(file).fatal) { debug$7('Not compiling failed document'); return } if (!context.output && !context.out && !context.alwaysStringify) { debug$7('Not compiling document without output settings'); return } debug$7('Compiling `%s`', file.path); if (context.inspect) { // Add a `txt` extension if there is a path. if (file.path) { file.extname = '.txt'; } value = unistUtilInspect[context.color ? 'color' : 'noColor'](tree) + '\n'; } else if (context.treeOut) { // Add a `json` extension to ensure the file is correctly seen as JSON. // Only add it if there is a path — not if the file is for example stdin. if (file.path) { file.extname = '.json'; } // Add the line feed to create a valid UNIX file. value = JSON.stringify(tree, null, 2) + '\n'; } else { value = processor.stringify(tree, file); } if (value === undefined || value === null) ; else if (typeof value === 'string' || isBuffer(value)) { file.contents = value; } else { file.result = value; } debug$7('Serialized document'); } var debug$8 = src('unified-engine:file-pipeline:copy'); var copy_1 = copy; var stat$1 = fs__default['default'].stat; var dirname$2 = path__default['default'].dirname; var resolve$5 = path__default['default'].resolve; var relative$3 = path__default['default'].relative; // Move a file. function copy(context, file, fileSet, next) { var output = context.output; var multi = fileSet.expected > 1; var outpath = output; var currentPath = file.path; if (typeof outpath !== 'string') { debug$8('Not copying'); return next() } outpath = resolve$5(context.cwd, outpath); debug$8('Copying `%s`', currentPath); stat$1(outpath, onstatfile); function onstatfile(error, stats) { if (error) { if ( error.code !== 'ENOENT' || output.charAt(output.length - 1) === path__default['default'].sep ) { return next( new Error('Cannot read output directory. Error:\n' + error.message) ) } stat$1(dirname$2(outpath), onstatparent); } else { done(stats.isDirectory()); } } // This is either given an error, or the parent exists which is a directory, // but we should keep the basename of the given file. function onstatparent(error) { if (error) { next(new Error('Cannot read parent directory. Error:\n' + error.message)); } else { done(false); } } function done(directory) { if (!directory && multi) { return next( new Error('Cannot write multiple files to single output: ' + outpath) ) } file[directory ? 'dirname' : 'path'] = relative$3(file.cwd, outpath); debug$8('Copying document from %s to %s', currentPath, file.path); next(); } } var debug$9 = src('unified-engine:file-pipeline:stdout'); var stdout_1 = stdout; // Write a virtual file to `streamOut`. // Ignored when `output` is given, more than one file was processed, or `out` // is false. function stdout(context, file, fileSet, next) { if (!file.data.unifiedEngineGiven) { debug$9('Ignoring programmatically added file'); next(); } else if (vfileStatistics(file).fatal || context.output || !context.out) { debug$9('Ignoring writing to `streamOut`'); next(); } else { debug$9('Writing document to `streamOut`'); context.streamOut.write(file.toString(), next); } } var debug$a = src('unified-engine:file-pipeline:file-system'); var fileSystem_1$1 = fileSystem$1; var writeFile = fs__default['default'].writeFile; var resolve$6 = path__default['default'].resolve; // Write a virtual file to the file-system. // Ignored when `output` is not given. function fileSystem$1(context, file, fileSet, next) { var destinationPath; if (!context.output) { debug$a('Ignoring writing to file-system'); return next() } if (!file.data.unifiedEngineGiven) { debug$a('Ignoring programmatically added file'); return next() } destinationPath = file.path; if (!destinationPath) { debug$a('Cannot write file without a `destinationPath`'); return next(new Error('Cannot write file without an output path')) } if (vfileStatistics(file).fatal) { debug$a('Cannot write file with a fatal error'); return next() } destinationPath = resolve$6(context.cwd, destinationPath); debug$a('Writing document to `%s`', destinationPath); file.stored = true; writeFile(destinationPath, file.toString(), next); } // This pipeline ensures each of the pipes always runs: even if the read pipe // fails, queue and write run. var filePipeline = trough_1() .use(chunk(trough_1().use(read_1$1).use(configure_1$1).use(parse_1).use(transform_1))) .use(chunk(trough_1().use(queue_1))) .use(chunk(trough_1().use(stringify_1).use(copy_1).use(stdout_1).use(fileSystem_1$1))); // Factory to run a pipe. // Wraps a pipe to trigger an error on the `file` in `context`, but still call // `next`. function chunk(pipe) { return run // Run the bound bound pipe and handles any errors. function run(context, file, fileSet, next) { pipe.run(context, file, fileSet, one); function one(error) { var messages = file.messages; var index; if (error) { index = messages.indexOf(error); if (index === -1) { error = file.message(error); index = messages.length - 1; } messages[index].fatal = true; } next(); } } } var transform_1$1 = transform$1; // Transform all files. function transform$1(context, settings, next) { var fileSet$1 = new fileSet(); context.fileSet = fileSet$1; fileSet$1.on('add', add).on('done', next); if (context.files.length === 0) { next(); } else { context.files.forEach(fileSet$1.add, fileSet$1); } function add(file) { filePipeline.run( { configuration: context.configuration, processor: settings.processor(), cwd: settings.cwd, extensions: settings.extensions, pluginPrefix: settings.pluginPrefix, treeIn: settings.treeIn, treeOut: settings.treeOut, inspect: settings.inspect, color: settings.color, out: settings.out, output: settings.output, streamOut: settings.streamOut, alwaysStringify: settings.alwaysStringify }, file, fileSet$1, done ); function done(error) { /* istanbul ignore next - Does not occur as all failures in `filePipeLine` * are failed on each file. * Still, just to ensure things work in the future, we add an extra * check. */ if (error) { error = file.message(error); error.fatal = true; } fileSet$1.emit('one', file); } } } var hasFlag$2 = (flag, argv) => { argv = argv || process.argv; const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const pos = argv.indexOf(prefix + flag); const terminatorPos = argv.indexOf('--'); return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); }; const {env: env$2} = process; let forceColor$2; if (hasFlag$2('no-color') || hasFlag$2('no-colors') || hasFlag$2('color=false') || hasFlag$2('color=never')) { forceColor$2 = 0; } else if (hasFlag$2('color') || hasFlag$2('colors') || hasFlag$2('color=true') || hasFlag$2('color=always')) { forceColor$2 = 1; } if ('FORCE_COLOR' in env$2) { if (env$2.FORCE_COLOR === true || env$2.FORCE_COLOR === 'true') { forceColor$2 = 1; } else if (env$2.FORCE_COLOR === false || env$2.FORCE_COLOR === 'false') { forceColor$2 = 0; } else { forceColor$2 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3); } } function translateLevel$2(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor$2(stream) { if (forceColor$2 === 0) { return 0; } if (hasFlag$2('color=16m') || hasFlag$2('color=full') || hasFlag$2('color=truecolor')) { return 3; } if (hasFlag$2('color=256')) { return 2; } if (stream && !stream.isTTY && forceColor$2 === undefined) { return 0; } const min = forceColor$2 || 0; if (env$2.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Node.js 7.5.0 is the first version of Node.js to include a patch to // libuv that enables 256 color output on Windows. Anything earlier and it // won't work. However, here we target Node.js 8 at minimum as it is an LTS // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows // release that supports 256 colors. Windows 10 build 14931 is the first release // that supports 16m/TrueColor. const osRelease = os__default['default'].release().split('.'); if ( Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env$2) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env$2) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; } if (env$2.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env$2) { const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env$2.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env$2.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { return 1; } if ('COLORTERM' in env$2) { return 1; } return min; } function getSupportLevel$2(stream) { const level = supportsColor$2(stream); return translateLevel$2(level); } var supportsColor_1$2 = { supportsColor: getSupportLevel$2, stdout: getSupportLevel$2(process.stdout), stderr: getSupportLevel$2(process.stderr) }; var ansiRegex = ({onlyFirst = false} = {}) => { const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' ].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); }; var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; /* eslint-disable yoda */ const isFullwidthCodePoint = codePoint => { if (Number.isNaN(codePoint)) { return false; } // Code points are derived from: // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt if ( codePoint >= 0x1100 && ( codePoint <= 0x115F || // Hangul Jamo codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET // CJK Radicals Supplement .. Enclosed CJK Letters and Months (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A (0x3250 <= codePoint && codePoint <= 0x4DBF) || // CJK Unified Ideographs .. Yi Radicals (0x4E00 <= codePoint && codePoint <= 0xA4C6) || // Hangul Jamo Extended-A (0xA960 <= codePoint && codePoint <= 0xA97C) || // Hangul Syllables (0xAC00 <= codePoint && codePoint <= 0xD7A3) || // CJK Compatibility Ideographs (0xF900 <= codePoint && codePoint <= 0xFAFF) || // Vertical Forms (0xFE10 <= codePoint && codePoint <= 0xFE19) || // CJK Compatibility Forms .. Small Form Variants (0xFE30 <= codePoint && codePoint <= 0xFE6B) || // Halfwidth and Fullwidth Forms (0xFF01 <= codePoint && codePoint <= 0xFF60) || (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || // Kana Supplement (0x1B000 <= codePoint && codePoint <= 0x1B001) || // Enclosed Ideographic Supplement (0x1F200 <= codePoint && codePoint <= 0x1F251) || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane (0x20000 <= codePoint && codePoint <= 0x3FFFD) ) ) { return true; } return false; }; var isFullwidthCodePoint_1 = isFullwidthCodePoint; var _default$2 = isFullwidthCodePoint; isFullwidthCodePoint_1.default = _default$2; var emojiRegex = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; const stringWidth = string => { string = string.replace(emojiRegex(), ' '); if (typeof string !== 'string' || string.length === 0) { return 0; } string = stripAnsi(string); let width = 0; for (let i = 0; i < string.length; i++) { const code = string.codePointAt(i); // Ignore control characters if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { continue; } // Ignore combining characters if (code >= 0x300 && code <= 0x36F) { continue; } // Surrogates if (code > 0xFFFF) { i++; } width += isFullwidthCodePoint_1(code) ? 2 : 1; } return width; }; var stringWidth_1 = stringWidth; // TODO: remove this in the next major version var _default$3 = stringWidth; stringWidth_1.default = _default$3; /*! * repeat-string * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ /** * Results cache */ var res = ''; var cache; /** * Expose `repeat` */ var repeatString = repeat$1; /** * Repeat the given `string` the specified `number` * of times. * * **Example:** * * ```js * var repeat = require('repeat-string'); * repeat('A', 5); * //=> AAAAA * ``` * * @param {String} `string` The string to repeat * @param {Number} `number` The number of times to repeat the string * @return {String} Repeated string * @api public */ function repeat$1(str, num) { if (typeof str !== 'string') { throw new TypeError('expected a string'); } // cover common, quick use cases if (num === 1) return str; if (num === 2) return str + str; var max = str.length * num; if (cache !== str || typeof cache === 'undefined') { cache = str; res = ''; } else if (res.length >= max) { return res.substr(0, max); } while (max > res.length && num > 1) { if (num & 1) { res += str; } num >>= 1; str += str; } res += str; res = res.substr(0, max); return res; } var vfileSort = sort; var severities = { true: 2, false: 1, null: 0, undefined: 0 }; function sort(file) { file.messages.sort(comparator); return file } function comparator(a, b) { return ( check$1(a, b, 'line') || check$1(a, b, 'column') || severities[b.fatal] - severities[a.fatal] || compare(a, b, 'source') || compare(a, b, 'ruleId') || compare(a, b, 'reason') || 0 ) } function check$1(a, b, property) { return (a[property] || 0) - (b[property] || 0) } function compare(a, b, property) { return (a[property] || '').localeCompare(b[property] || '') } var supported = supportsColor_1$2.stderr.hasBasic; var vfileReporter = reporter; // Check which characters should be used. var windows$1 = process.platform === 'win32'; // `log-symbols` without chalk: /* istanbul ignore next - Windows. */ var chars = windows$1 ? {error: '×', warning: '‼'} : {error: '✖', warning: '⚠'}; // Match trailing white-space. var trailing = /\s*$/; // Default filename. var defaultName = ''; var noop = {open: '', close: ''}; var colors = { underline: {open: '\u001B[4m', close: '\u001B[24m'}, red: {open: '\u001B[31m', close: '\u001B[39m'}, yellow: {open: '\u001B[33m', close: '\u001B[39m'}, green: {open: '\u001B[32m', close: '\u001B[39m'} }; var noops = { underline: noop, red: noop, yellow: noop, green: noop }; var labels = { true: 'error', false: 'warning', null: 'info', undefined: 'info' }; // Report a file’s messages. function reporter(files, options) { var settings = options || {}; var one; if (!files) { return '' } // Error. if ('name' in files && 'message' in files) { return String(files.stack || files) } // One file. if (!('length' in files)) { one = true; files = [files]; } return compile$1(parse$4(filter$1(files, settings), settings), one, settings) } function filter$1(files, options) { var result = []; var length = files.length; var index = -1; var file; if (!options.quiet && !options.silent) { return files.concat() } while (++index < length) { file = files[index]; if (applicable(file, options).length !== 0) { result.push(file); } } return result } function parse$4(files, options) { var length = files.length; var index = -1; var rows = []; var all = []; var locationSize = 0; var labelSize = 0; var reasonSize = 0; var ruleIdSize = 0; var file; var destination; var origin; var messages; var offset; var count; var message; var loc; var reason; var label; var id; while (++index < length) { file = files[index]; destination = file.path; origin = file.history[0] || destination; messages = vfileSort({messages: applicable(file, options)}).messages; if (rows.length !== 0 && rows[rows.length - 1].type !== 'header') { rows.push({type: 'separator'}); } rows.push({ type: 'header', origin: origin, destination: destination, name: origin || options.defaultName || defaultName, stored: Boolean(file.stored), moved: Boolean(file.stored && destination !== origin), stats: vfileStatistics(messages) }); offset = -1; count = messages.length; while (++offset < count) { message = messages[offset]; id = message.ruleId || ''; reason = message.stack || message.message; loc = message.location; loc = unistUtilStringifyPosition(loc.end.line && loc.end.column ? loc : loc.start); if (options.verbose && message.note) { reason += '\n' + message.note; } label = labels[message.fatal]; rows.push({ location: loc, label: label, reason: reason, ruleId: id, source: message.source }); locationSize = Math.max(realLength(loc), locationSize); labelSize = Math.max(realLength(label), labelSize); reasonSize = Math.max(realLength(reason), reasonSize); ruleIdSize = Math.max(realLength(id), ruleIdSize); } all = all.concat(messages); } return { rows: rows, statistics: vfileStatistics(all), location: locationSize, label: labelSize, reason: reasonSize, ruleId: ruleIdSize } } // eslint-disable-next-line complexity function compile$1(map, one, options) { var enabled = options.color; var all = map.statistics; var rows = map.rows; var length = rows.length; var index = -1; var lines = []; var row; var line; var style; var color; var reason; var rest; var position; if (enabled === null || enabled === undefined) { enabled = supported; } style = enabled ? colors : noops; while (++index < length) { row = rows[index]; if (row.type === 'separator') { lines.push(''); } else if (row.type === 'header') { if (one && !options.defaultName && !row.origin) { line = ''; } else { color = style[row.stats.fatal ? 'red' : row.stats.total ? 'yellow' : 'green']; line = style.underline.open + color.open + row.name + color.close + style.underline.close; line += row.moved ? ' > ' + row.destination : ''; } if (!row.stats.total) { line += line ? ': ' : ''; if (row.stored) { line += style.yellow.open + 'written' + style.yellow.close; } else { line += 'no issues found'; } } if (line) { lines.push(line); } } else { color = style[row.label === 'error' ? 'red' : 'yellow']; reason = row.reason; rest = ''; position = reason.indexOf('\n'); if (position !== -1) { rest = reason.slice(position); reason = reason.slice(0, position); } lines.push( [ '', padLeft(row.location, map.location), padRight(color.open + row.label + color.close, map.label), padRight(reason, map.reason), padRight(row.ruleId, map.ruleId), row.source || '' ] .join(' ') .replace(trailing, '') + rest ); } } if (all.fatal || all.warn) { line = []; if (all.fatal) { line.push( [ style.red.open + chars.error + style.red.close, all.fatal, plural$1(labels.true, all.fatal) ].join(' ') ); } if (all.warn) { line.push( [ style.yellow.open + chars.warning + style.yellow.close, all.warn, plural$1(labels.false, all.warn) ].join(' ') ); } line = line.join(', '); if (all.total !== all.fatal && all.total !== all.warn) { line = all.total + ' messages (' + line + ')'; } lines.push('', line); } return lines.join('\n') } function applicable(file, options) { var messages = file.messages; var length = messages.length; var index = -1; var result = []; if (options.silent) { while (++index < length) { if (messages[index].fatal) { result.push(messages[index]); } } } else { result = messages.concat(); } return result } // Get the length of `value`, ignoring ANSI sequences. function realLength(value) { var length = value.indexOf('\n'); return stringWidth_1(length === -1 ? value : value.slice(0, length)) } // Pad `value` on the left. function padLeft(value, minimum) { return repeatString(' ', minimum - realLength(value)) + value } // Pad `value` on the right. function padRight(value, minimum) { return value + repeatString(' ', minimum - realLength(value)) } function plural$1(value, count) { return count === 1 ? value : value + 's' } var log_1 = log; var prefix = 'vfile-reporter'; function log(context, settings, next) { var reporter = settings.reporter || vfileReporter; var diagnostics; if (typeof reporter === 'string') { try { reporter = loadPlugin_1(reporter, {cwd: settings.cwd, prefix: prefix}); } catch (_) { next(new Error('Could not find reporter `' + reporter + '`')); return } } diagnostics = reporter( context.files.filter(given), Object.assign({}, settings.reporterOptions, { quiet: settings.quiet, silent: settings.silent, color: settings.color }) ); if (diagnostics) { if (diagnostics.charAt(diagnostics.length - 1) !== '\n') { diagnostics += '\n'; } settings.streamError.write(diagnostics, next); } else { next(); } } function given(file) { return file.data.unifiedEngineGiven } var fileSetPipeline = trough_1() .use(configure_1) .use(fileSystem_1) .use(stdin_1) .use(transform_1$1) .use(log_1); var PassThrough = stream__default['default'].PassThrough; var lib$4 = run; // Run the file set pipeline once. // `callback` is invoked with a fatal error, or with a status code (`0` on // success, `1` on failure). function run(options, callback) { var settings = {}; var stdin = new PassThrough(); var tree; var detectConfig; var hasConfig; var detectIgnore; var hasIgnore; try { stdin = process.stdin; } catch (_) { // Obscure bug in Node (seen on Windows). // See: , // . } if (!callback) { throw new Error('Missing `callback`') } if (!options || !options.processor) { return next(new Error('Missing `processor`')) } // Processor. settings.processor = options.processor; // Path to run as. settings.cwd = options.cwd || process.cwd(); // Input. settings.files = options.files || []; settings.extensions = (options.extensions || []).map(extension); settings.filePath = options.filePath || null; settings.streamIn = options.streamIn || stdin; // Output. settings.streamOut = options.streamOut || process.stdout; settings.streamError = options.streamError || process.stderr; settings.alwaysStringify = options.alwaysStringify; settings.output = options.output; settings.out = options.out; // Null overwrites config settings, `undefined` does not. if (settings.output === null || settings.output === undefined) { settings.output = undefined; } if (settings.output && settings.out) { return next(new Error('Cannot accept both `output` and `out`')) } // Process phase management. tree = options.tree || false; settings.treeIn = options.treeIn; settings.treeOut = options.treeOut; settings.inspect = options.inspect; if (settings.treeIn === null || settings.treeIn === undefined) { settings.treeIn = tree; } if (settings.treeOut === null || settings.treeOut === undefined) { settings.treeOut = tree; } // Configuration. detectConfig = options.detectConfig; hasConfig = Boolean(options.rcName || options.packageField); if (detectConfig && !hasConfig) { return next( new Error('Missing `rcName` or `packageField` with `detectConfig`') ) } settings.detectConfig = detectConfig === null || detectConfig === undefined ? hasConfig : detectConfig; settings.rcName = options.rcName || null; settings.rcPath = options.rcPath || null; settings.packageField = options.packageField || null; settings.settings = options.settings || {}; settings.configTransform = options.configTransform; settings.defaultConfig = options.defaultConfig; // Ignore. detectIgnore = options.detectIgnore; hasIgnore = Boolean(options.ignoreName); settings.detectIgnore = detectIgnore === null || detectIgnore === undefined ? hasIgnore : detectIgnore; settings.ignoreName = options.ignoreName || null; settings.ignorePath = options.ignorePath || null; settings.ignorePathResolveFrom = options.ignorePathResolveFrom || 'dir'; settings.ignorePatterns = options.ignorePatterns || []; settings.silentlyIgnore = Boolean(options.silentlyIgnore); if (detectIgnore && !hasIgnore) { return next(new Error('Missing `ignoreName` with `detectIgnore`')) } // Plugins. settings.pluginPrefix = options.pluginPrefix || null; settings.plugins = options.plugins || {}; // Reporting. settings.reporter = options.reporter || null; settings.reporterOptions = options.reporterOptions || null; settings.color = options.color || false; settings.silent = options.silent || false; settings.quiet = options.quiet || false; settings.frail = options.frail || false; // Process. fileSetPipeline.run({files: options.files || []}, settings, next); function next(error, context) { var stats = vfileStatistics((context || {}).files); var failed = Boolean( settings.frail ? stats.fatal || stats.warn : stats.fatal ); if (error) { callback(error); } else { callback(null, failed ? 1 : 0, context); } } } function extension(ext) { return ext.charAt(0) === '.' ? ext : '.' + ext } var colorName$1 = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; /* MIT license */ /* eslint-disable no-mixed-operators */ // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) const reverseKeywords = {}; for (const key of Object.keys(colorName$1)) { reverseKeywords[colorName$1[key]] = key; } const convert$1 = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; var conversions$1 = convert$1; // Hide .channels and .labels properties for (const model of Object.keys(convert$1)) { if (!('channels' in convert$1[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert$1[model])) { throw new Error('missing channel labels property: ' + model); } if (convert$1[model].labels.length !== convert$1[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } const {channels, labels} = convert$1[model]; delete convert$1[model].channels; delete convert$1[model].labels; Object.defineProperty(convert$1[model], 'channels', {value: channels}); Object.defineProperty(convert$1[model], 'labels', {value: labels}); } convert$1.rgb.hsl = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert$1.rgb.hsv = function (rgb) { let rdif; let gdif; let bdif; let h; let s; const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const v = Math.max(r, g, b); const diff = v - Math.min(r, g, b); const diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = 0; s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert$1.rgb.hwb = function (rgb) { const r = rgb[0]; const g = rgb[1]; let b = rgb[2]; const h = convert$1.rgb.hsl(rgb)[0]; const w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert$1.rgb.cmyk = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const k = Math.min(1 - r, 1 - g, 1 - b); const c = (1 - r - k) / (1 - k) || 0; const m = (1 - g - k) / (1 - k) || 0; const y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; function comparativeDistance(x, y) { /* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance */ return ( ((x[0] - y[0]) ** 2) + ((x[1] - y[1]) ** 2) + ((x[2] - y[2]) ** 2) ); } convert$1.rgb.keyword = function (rgb) { const reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } let currentClosestDistance = Infinity; let currentClosestKeyword; for (const keyword of Object.keys(colorName$1)) { const value = colorName$1[keyword]; // Compute comparative distance const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } return currentClosestKeyword; }; convert$1.keyword.rgb = function (keyword) { return colorName$1[keyword]; }; convert$1.rgb.xyz = function (rgb) { let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; // Assume sRGB r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert$1.rgb.lab = function (rgb) { const xyz = convert$1.rgb.xyz(rgb); let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert$1.hsl.rgb = function (hsl) { const h = hsl[0] / 360; const s = hsl[1] / 100; const l = hsl[2] / 100; let t2; let t3; let val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } const t1 = 2 * l - t2; const rgb = [0, 0, 0]; for (let i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert$1.hsl.hsv = function (hsl) { const h = hsl[0]; let s = hsl[1] / 100; let l = hsl[2] / 100; let smin = s; const lmin = Math.max(l, 0.01); l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; const v = (l + s) / 2; const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert$1.hsv.rgb = function (hsv) { const h = hsv[0] / 60; const s = hsv[1] / 100; let v = hsv[2] / 100; const hi = Math.floor(h) % 6; const f = h - Math.floor(h); const p = 255 * v * (1 - s); const q = 255 * v * (1 - (s * f)); const t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert$1.hsv.hsl = function (hsv) { const h = hsv[0]; const s = hsv[1] / 100; const v = hsv[2] / 100; const vmin = Math.max(v, 0.01); let sl; let l; l = (2 - s) * v; const lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert$1.hwb.rgb = function (hwb) { const h = hwb[0] / 360; let wh = hwb[1] / 100; let bl = hwb[2] / 100; const ratio = wh + bl; let f; // Wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } const i = Math.floor(6 * h); const v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } const n = wh + f * (v - wh); // Linear interpolation let r; let g; let b; /* eslint-disable max-statements-per-line,no-multi-spaces */ switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } /* eslint-enable max-statements-per-line,no-multi-spaces */ return [r * 255, g * 255, b * 255]; }; convert$1.cmyk.rgb = function (cmyk) { const c = cmyk[0] / 100; const m = cmyk[1] / 100; const y = cmyk[2] / 100; const k = cmyk[3] / 100; const r = 1 - Math.min(1, c * (1 - k) + k); const g = 1 - Math.min(1, m * (1 - k) + k); const b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert$1.xyz.rgb = function (xyz) { const x = xyz[0] / 100; const y = xyz[1] / 100; const z = xyz[2] / 100; let r; let g; let b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // Assume sRGB r = r > 0.0031308 ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert$1.xyz.lab = function (xyz) { let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert$1.lab.xyz = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let x; let y; let z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; const y2 = y ** 3; const x2 = x ** 3; const z2 = z ** 3; y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert$1.lab.lch = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let h; const hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } const c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert$1.lch.lab = function (lch) { const l = lch[0]; const c = lch[1]; const h = lch[2]; const hr = h / 360 * 2 * Math.PI; const a = c * Math.cos(hr); const b = c * Math.sin(hr); return [l, a, b]; }; convert$1.rgb.ansi16 = function (args, saturation = null) { const [r, g, b] = args; let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } let ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert$1.hsv.ansi16 = function (args) { // Optimization here; we already know the value and don't need to get // it converted for us. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]); }; convert$1.rgb.ansi256 = function (args) { const r = args[0]; const g = args[1]; const b = args[2]; // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } const ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert$1.ansi16.rgb = function (args) { let color = args % 10; // Handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } const mult = (~~(args > 50) + 1) * 0.5; const r = ((color & 1) * mult) * 255; const g = (((color >> 1) & 1) * mult) * 255; const b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert$1.ansi256.rgb = function (args) { // Handle greyscale if (args >= 232) { const c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; let rem; const r = Math.floor(args / 36) / 5 * 255; const g = Math.floor((rem = args % 36) / 6) / 5 * 255; const b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert$1.rgb.hex = function (args) { const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert$1.hex.rgb = function (args) { const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } let colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(char => { return char + char; }).join(''); } const integer = parseInt(colorString, 16); const r = (integer >> 16) & 0xFF; const g = (integer >> 8) & 0xFF; const b = integer & 0xFF; return [r, g, b]; }; convert$1.rgb.hcg = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const max = Math.max(Math.max(r, g), b); const min = Math.min(Math.min(r, g), b); const chroma = (max - min); let grayscale; let hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert$1.hsl.hcg = function (hsl) { const s = hsl[1] / 100; const l = hsl[2] / 100; const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); let f = 0; if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert$1.hsv.hcg = function (hsv) { const s = hsv[1] / 100; const v = hsv[2] / 100; const c = s * v; let f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert$1.hcg.rgb = function (hcg) { const h = hcg[0] / 360; const c = hcg[1] / 100; const g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } const pure = [0, 0, 0]; const hi = (h % 1) * 6; const v = hi % 1; const w = 1 - v; let mg = 0; /* eslint-disable max-statements-per-line */ switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } /* eslint-enable max-statements-per-line */ mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert$1.hcg.hsv = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); let f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert$1.hcg.hsl = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const l = g * (1.0 - c) + 0.5 * c; let s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert$1.hcg.hwb = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert$1.hwb.hcg = function (hwb) { const w = hwb[1] / 100; const b = hwb[2] / 100; const v = 1 - b; const c = v - w; let g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert$1.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert$1.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert$1.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert$1.gray.hsl = function (args) { return [0, 0, args[0]]; }; convert$1.gray.hsv = convert$1.gray.hsl; convert$1.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert$1.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert$1.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert$1.gray.hex = function (gray) { const val = Math.round(gray[0] / 100 * 255) & 0xFF; const integer = (val << 16) + (val << 8) + val; const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert$1.rgb.gray = function (rgb) { const val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; /* This function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph$1() { const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 const models = Object.keys(conversions$1); for (let len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS$1(fromModel) { const graph = buildGraph$1(); const queue = [fromModel]; // Unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { const current = queue.pop(); const adjacents = Object.keys(conversions$1[current]); for (let len = adjacents.length, i = 0; i < len; i++) { const adjacent = adjacents[i]; const node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link$1(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion$1(toModel, graph) { const path = [graph[toModel].parent, toModel]; let fn = conversions$1[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link$1(conversions$1[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route$1 = function (fromModel) { const graph = deriveBFS$1(fromModel); const conversion = {}; const models = Object.keys(graph); for (let len = models.length, i = 0; i < len; i++) { const toModel = models[i]; const node = graph[toModel]; if (node.parent === null) { // No possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion$1(toModel, graph); } return conversion; }; const convert$2 = {}; const models$1 = Object.keys(conversions$1); function wrapRaw$1(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } return fn(args); }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded$1(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } const result = fn(args); // We're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (let len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models$1.forEach(fromModel => { convert$2[fromModel] = {}; Object.defineProperty(convert$2[fromModel], 'channels', {value: conversions$1[fromModel].channels}); Object.defineProperty(convert$2[fromModel], 'labels', {value: conversions$1[fromModel].labels}); const routes = route$1(fromModel); const routeModels = Object.keys(routes); routeModels.forEach(toModel => { const fn = routes[toModel]; convert$2[fromModel][toModel] = wrapRounded$1(fn); convert$2[fromModel][toModel].raw = wrapRaw$1(fn); }); }); var colorConvert$1 = convert$2; var ansiStyles$1 = createCommonjsModule(function (module) { const wrapAnsi16 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => (...args) => { const rgb = fn(...args); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; const setLazyProperty = (object, property, get) => { Object.defineProperty(object, property, { get: () => { const value = get(); Object.defineProperty(object, property, { value, enumerable: true, configurable: true }); return value; }, enumerable: true, configurable: true }); }; /** @type {typeof import('color-convert')} */ let colorConvert; const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { if (colorConvert === undefined) { colorConvert = colorConvert$1; } const offset = isBackground ? 10 : 0; const styles = {}; for (const [sourceSpace, suite] of Object.entries(colorConvert)) { const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; if (sourceSpace === targetSpace) { styles[name] = wrap(identity, offset); } else if (typeof suite === 'object') { styles[name] = wrap(suite[targetSpace], offset); } } return styles; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }); const stringReplaceAll = (string, substring, replacer) => { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; var util = { stringReplaceAll, stringEncaseCRLFWithFirstIndex }; const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES$1 = new Map([ ['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007'] ]); function unescape$1(c) { const u = c[0] === 'u'; const bracket = c[1] === '{'; if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { return String.fromCharCode(parseInt(c.slice(1), 16)); } if (u && bracket) { return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); } return ESCAPES$1.get(c) || c; } function parseArguments$1(name, arguments_) { const results = []; const chunks = arguments_.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { const number = Number(chunk); if (!Number.isNaN(number)) { results.push(number); } else if ((matches = chunk.match(STRING_REGEX$1))) { results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } } return results; } function parseStyle$1(style) { STYLE_REGEX$1.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX$1.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments$1(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle$1(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const [styleName, styles] of Object.entries(enabled)) { if (!Array.isArray(styles)) { continue; } if (!(styleName in current)) { throw new Error(`Unknown Chalk style: ${styleName}`); } current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; } return current; } var templates$1 = (chalk, temporary) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => { if (escapeCharacter) { chunk.push(unescape$1(escapeCharacter)); } else if (style) { const string = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string)); styles.push({inverse, styles: parseStyle$1(style)}); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle$1(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(character); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; throw new Error(errMsg); } return chunks.join(''); }; const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1$1; const { stringReplaceAll: stringReplaceAll$1, stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1 } = util; // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = [ 'ansi', 'ansi', 'ansi256', 'ansi16m' ]; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level > 3 || options.level < 0) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; class ChalkClass { constructor(options) { return chalkFactory(options); } } const chalkFactory = options => { const chalk = {}; applyOptions(chalk, options); chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = () => { throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); }; chalk.template.Instance = ChalkClass; return chalk.template; }; function Chalk(options) { return chalkFactory(options); } for (const [styleName, style] of Object.entries(ansiStyles$1)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); Object.defineProperty(this, styleName, {value: builder}); return builder; } }; } styles.visible = { get() { const builder = createBuilder(this, this._styler, true); Object.defineProperty(this, 'visible', {value: builder}); return builder; } }; const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } for (const model of usedModels) { const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } const proto$3 = Object.defineProperties(() => {}, { ...styles, level: { enumerable: true, get() { return this._generator.level; }, set(level) { this._generator.level = level; } } }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent }; }; const createBuilder = (self, _styler, _isEmpty) => { const builder = (...arguments_) => { // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); }; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto$3; // eslint-disable-line no-proto builder._generator = self; builder._styler = _styler; builder._isEmpty = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self._isEmpty ? '' : string; } let styler = self._styler; if (styler === undefined) { return string; } const {openAll, closeAll} = styler; if (string.indexOf('\u001B') !== -1) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll$1(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; let template; const chalkTag = (chalk, ...strings) => { const [firstString] = strings; if (!Array.isArray(firstString)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return strings.join(' '); } const arguments_ = strings.slice(1); const parts = [firstString.raw[0]]; for (let i = 1; i < firstString.length; i++) { parts.push( String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]) ); } if (template === undefined) { template = templates$1; } return template(chalk, parts.join('')); }; Object.defineProperties(Chalk.prototype, styles); const chalk$1 = Chalk(); // eslint-disable-line new-cap chalk$1.supportsColor = stdoutColor; chalk$1.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap chalk$1.stderr.supportsColor = stderrColor; // For TypeScript chalk$1.Level = { None: 0, Basic: 1, Ansi256: 2, TrueColor: 3, 0: 'None', 1: 'Basic', 2: 'Ansi256', 3: 'TrueColor' }; var source = chalk$1; const WIN_SLASH = '\\\\/'; const WIN_NO_SLASH = `[^${WIN_SLASH}]`; /** * Posix glob regex */ const DOT_LITERAL = '\\.'; const PLUS_LITERAL = '\\+'; const QMARK_LITERAL = '\\?'; const SLASH_LITERAL = '\\/'; const ONE_CHAR = '(?=.)'; const QMARK = '[^/]'; const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; const NO_DOT = `(?!${DOT_LITERAL})`; const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; const STAR = `${QMARK}*?`; const POSIX_CHARS = { DOT_LITERAL, PLUS_LITERAL, QMARK_LITERAL, SLASH_LITERAL, ONE_CHAR, QMARK, END_ANCHOR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK_NO_DOT, STAR, START_ANCHOR }; /** * Windows glob regex */ const WINDOWS_CHARS = { ...POSIX_CHARS, SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }; /** * POSIX Bracket Regex */ const POSIX_REGEX_SOURCE = { alnum: 'a-zA-Z0-9', alpha: 'a-zA-Z', ascii: '\\x00-\\x7F', blank: ' \\t', cntrl: '\\x00-\\x1F\\x7F', digit: '0-9', graph: '\\x21-\\x7E', lower: 'a-z', print: '\\x20-\\x7E ', punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', space: ' \\t\\r\\n\\v\\f', upper: 'A-Z', word: 'A-Za-z0-9_', xdigit: 'A-Fa-f0-9' }; var constants = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE, // regular expressions REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { '***': '*', '**/**': '**', '**/**/**': '**' }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ CHAR_COLON: 58, /* : */ CHAR_COMMA: 44, /* , */ CHAR_DOT: 46, /* . */ CHAR_DOUBLE_QUOTE: 34, /* " */ CHAR_EQUAL: 61, /* = */ CHAR_EXCLAMATION_MARK: 33, /* ! */ CHAR_FORM_FEED: 12, /* \f */ CHAR_FORWARD_SLASH: 47, /* / */ CHAR_GRAVE_ACCENT: 96, /* ` */ CHAR_HASH: 35, /* # */ CHAR_HYPHEN_MINUS: 45, /* - */ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ CHAR_LEFT_CURLY_BRACE: 123, /* { */ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ CHAR_LINE_FEED: 10, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ CHAR_PERCENT: 37, /* % */ CHAR_PLUS: 43, /* + */ CHAR_QUESTION_MARK: 63, /* ? */ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ CHAR_RIGHT_CURLY_BRACE: 125, /* } */ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ CHAR_SEMICOLON: 59, /* ; */ CHAR_SINGLE_QUOTE: 39, /* ' */ CHAR_SPACE: 32, /* */ CHAR_TAB: 9, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ SEP: path__default['default'].sep, /** * Create EXTGLOB_CHARS */ extglobChars(chars) { return { '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, '?': { type: 'qmark', open: '(?:', close: ')?' }, '+': { type: 'plus', open: '(?:', close: ')+' }, '*': { type: 'star', open: '(?:', close: ')*' }, '@': { type: 'at', open: '(?:', close: ')' } }; }, /** * Create GLOB_CHARS */ globChars(win32) { return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; } }; var utils = createCommonjsModule(function (module, exports) { const win32 = process.platform === 'win32'; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = constants; exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); exports.removeBackslashes = str => { return str.replace(REGEX_REMOVE_BACKSLASH, match => { return match === '\\' ? '' : match; }); }; exports.supportsLookbehinds = () => { const segs = process.version.slice(1).split('.').map(Number); if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { return true; } return false; }; exports.isWindows = options => { if (options && typeof options.windows === 'boolean') { return options.windows; } return win32 === true || path__default['default'].sep === '\\'; }; exports.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith('./')) { output = output.slice(2); state.prefix = './'; } return output; }; exports.wrapOutput = (input, state = {}, options = {}) => { const prepend = options.contains ? '' : '^'; const append = options.contains ? '' : '$'; let output = `${prepend}(?:${input})${append}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; }); var utils_1 = utils.isObject; var utils_2 = utils.hasRegexChars; var utils_3 = utils.isRegexChar; var utils_4 = utils.escapeRegex; var utils_5 = utils.toPosixSlashes; var utils_6 = utils.removeBackslashes; var utils_7 = utils.supportsLookbehinds; var utils_8 = utils.isWindows; var utils_9 = utils.escapeLast; var utils_10 = utils.removePrefix; var utils_11 = utils.wrapOutput; const { CHAR_ASTERISK: CHAR_ASTERISK$1, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ } = constants; const isPathSeparator = code => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; }; const depth = token => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; /** * Quickly scans a glob pattern and returns an object with a handful of * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), * `glob` (the actual pattern), and `negated` (true if the path starts with `!`). * * ```js * const pm = require('picomatch'); * console.log(pm.scan('foo/bar/*.js')); * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } * ``` * @param {String} `str` * @param {Object} `options` * @return {Object} Returns an object with tokens and regex source string. * @api public */ const scan$1 = (input, options) => { const opts = options || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob = false; let isExtglob = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let finished = false; let braces = 0; let prev; let code; let token = { value: '', depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA$1) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH) { slashes.push(index); tokens.push(token); token = { value: '', depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT && index === (start + 1)) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK$1 || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK$1) { if (prev === CHAR_ASTERISK$1) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET$1) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } } } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { finished = true; break; } } continue; } break; } if (isGlob === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob = false; isGlob = false; } let base = str; let prefix = ''; let glob = ''; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob = str.slice(lastIndex); } else if (isGlob === true) { base = ''; glob = str; } else { base = str; } if (base && base !== '' && base !== '/' && base !== str) { if (isPathSeparator(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils.removeBackslashes(glob); if (base && backslashes === true) { base = utils.removeBackslashes(base); } } const state = { prefix, input, start, base, glob, isBrace, isBracket, isGlob, isExtglob, isGlobstar, negated }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value = input.slice(n, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value; } depth(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value !== '') { parts.push(value); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value = input.slice(prevIndex + 1); parts.push(value); if (opts.tokens) { tokens[tokens.length - 1].value = value; depth(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; var scan_1 = scan$1; /** * Constants */ const { MAX_LENGTH, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants; /** * Helpers */ const expandRange = (args, options) => { if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join('-')}]`; try { /* eslint-disable-next-line no-new */ new RegExp(value); } catch (ex) { return args.map(v => utils.escapeRegex(v)).join('..'); } return value; }; /** * Create the message for a syntax error */ const syntaxError = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; /** * Parse the given input string. * @param {String} input * @param {Object} options * @return {Object} */ const parse$5 = (input, options) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } input = REPLACEMENTS[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: 'bos', value: '', output: opts.prepend || '' }; const tokens = [bos]; const capture = opts.capture ? '' : '?:'; const win32 = utils.isWindows(options); // create constants based on platform, for windows or posix const PLATFORM_CHARS = constants.globChars(win32); const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = (opts) => { return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? '' : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } // minimatch options support if (typeof opts.noext === 'boolean') { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: '', output: '', prefix: '', backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; /** * Tokenizing helpers */ const eos = () => state.index === len - 1; const peek = state.peek = (n = 1) => input[state.index + n]; const advance = state.advance = () => input[++state.index]; const remaining = () => input.slice(state.index + 1); const consume = (value = '', num = 0) => { state.consumed += value; state.index += num; }; const append = token => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = type => { state[type]++; stack.push(type); }; const decrement = type => { state[type]--; stack.pop(); }; /** * Push tokens onto the tokens array. This helper speeds up * tokenizing by 1) helping us avoid backtracking as much as possible, * and 2) helping us avoid creating extra tokens when consecutive * characters are plain text. This improves performance and simplifies * lookbehinds. */ const push = tok => { if (prev.type === 'globstar') { const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = 'star'; prev.value = '*'; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === 'text' && tok.type === 'text') { prev.value += tok.value; prev.output = (prev.output || '') + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value) => { const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); push({ type, value, output: state.output ? '' : ONE_CHAR }); push({ type: 'paren', extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = token => { let output = token.close + (opts.capture ? ')' : ''); if (token.type === 'negate') { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.prev.type === 'bos' && eos()) { state.negatedExtglob = true; } } push({ type: 'paren', extglob: true, value, output }); decrement('parens'); }; /** * Fast paths */ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { if (first === '\\') { backslashes = true; return m; } if (first === '?') { if (esc) { return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } return QMARK.repeat(chars.length); } if (first === '.') { return DOT_LITERAL.repeat(chars.length); } if (first === '*') { if (esc) { return esc + first + (rest ? star : ''); } return star; } return esc ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ''); } else { output = output.replace(/\\+/g, m => { return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils.wrapOutput(output, state, options); return state; } /** * Tokenize input until we reach end-of-string */ while (!eos()) { value = advance(); if (value === '\u0000') { continue; } /** * Escaped characters */ if (value === '\\') { const next = peek(); if (next === '/' && opts.bash !== true) { continue; } if (next === '.' || next === ';') { continue; } if (!next) { value += '\\'; push({ type: 'text', value }); continue; } // collapse slashes to reduce potential for exploits const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += '\\'; } } if (opts.unescape === true) { value = advance() || ''; } else { value += advance() || ''; } if (state.brackets === 0) { push({ type: 'text', value }); continue; } } /** * If we're inside a regex character class, continue * until we reach the closing bracket. */ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { if (opts.posix !== false && value === ':') { const inner = prev.value.slice(1); if (inner.includes('[')) { prev.posix = true; if (inner.includes(':')) { const idx = prev.value.lastIndexOf('['); const pre = prev.value.slice(0, idx); const rest = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE$1[rest]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { value = `\\${value}`; } if (value === ']' && (prev.value === '[' || prev.value === '[^')) { value = `\\${value}`; } if (opts.posix === true && value === '!' && prev.value === '[') { value = '^'; } prev.value += value; append({ value }); continue; } /** * If we're inside a quoted string, continue * until we reach the closing double quote. */ if (state.quotes === 1 && value !== '"') { value = utils.escapeRegex(value); prev.value += value; append({ value }); continue; } /** * Double quotes */ if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: 'text', value }); } continue; } /** * Parentheses */ if (value === '(') { increment('parens'); push({ type: 'paren', value }); continue; } if (value === ')') { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '(')); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); decrement('parens'); continue; } /** * Square brackets */ if (value === '[') { if (opts.nobracket === true || !remaining().includes(']')) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('closing', ']')); } value = `\\${value}`; } else { increment('brackets'); } push({ type: 'bracket', value }); continue; } if (value === ']') { if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { push({ type: 'text', value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '[')); } push({ type: 'text', value, output: `\\${value}` }); continue; } decrement('brackets'); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { value = `/${value}`; } prev.value += value; append({ value }); // when literal brackets are explicitly disabled // assume we should match with a regex character class if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { continue; } const escaped = utils.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled // assume we should escape the brackets to match literal characters if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } // when the user specifies nothing, try to match both prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } /** * Braces */ if (value === '{' && opts.nobrace !== true) { increment('braces'); const open = { type: 'brace', value, output: '(', outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open); push(open); continue; } if (value === '}') { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: 'text', value, output: value }); continue; } let output = ')'; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === 'brace') { break; } if (arr[i].type !== 'dots') { range.unshift(arr[i].value); } } output = expandRange(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = '\\{'; value = output = '\\}'; state.output = out; for (const t of toks) { state.output += (t.output || t.value); } } push({ type: 'brace', value, output }); decrement('braces'); braces.pop(); continue; } /** * Pipes */ if (value === '|') { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: 'text', value }); continue; } /** * Commas */ if (value === ',') { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === 'braces') { brace.comma = true; output = '|'; } push({ type: 'comma', value, output }); continue; } /** * Slashes */ if (value === '/') { // if the beginning of the glob is "./", advance the start // to the current index, and don't add the "./" characters // to the state. This greatly simplifies lookbehinds when // checking for BOS characters like "!" and "." (not "./") if (prev.type === 'dot' && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ''; state.output = ''; tokens.pop(); prev = bos; // reset "prev" to the first token continue; } push({ type: 'slash', value, output: SLASH_LITERAL }); continue; } /** * Dots */ if (value === '.') { if (state.braces > 0 && prev.type === 'dot') { if (prev.value === '.') prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = 'dots'; prev.output += value; prev.value += value; brace.dots = true; continue; } if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { push({ type: 'text', value, output: DOT_LITERAL }); continue; } push({ type: 'dot', value, output: DOT_LITERAL }); continue; } /** * Question marks */ if (value === '?') { const isGroup = prev && prev.value === '('; if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('qmark', value); continue; } if (prev && prev.type === 'paren') { const next = peek(); let output = value; if (next === '<' && !utils.supportsLookbehinds()) { throw new Error('Node.js v10 or higher is required for regex lookbehinds'); } if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { output = `\\${value}`; } push({ type: 'text', value, output }); continue; } if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { push({ type: 'qmark', value, output: QMARK_NO_DOT }); continue; } push({ type: 'qmark', value, output: QMARK }); continue; } /** * Exclamation */ if (value === '!') { if (opts.noextglob !== true && peek() === '(') { if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { extglobOpen('negate', value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } /** * Plus */ if (value === '+') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('plus', value); continue; } if ((prev && prev.value === '(') || opts.regex === false) { push({ type: 'plus', value, output: PLUS_LITERAL }); continue; } if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { push({ type: 'plus', value }); continue; } push({ type: 'plus', value: PLUS_LITERAL }); continue; } /** * Plain text */ if (value === '@') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { push({ type: 'at', extglob: true, value, output: '' }); continue; } push({ type: 'text', value }); continue; } /** * Plain text */ if (value !== '*') { if (value === '$' || value === '^') { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: 'text', value }); continue; } /** * Stars */ if (prev && (prev.type === 'globstar' || prev.star === true)) { prev.type = 'star'; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen('star', value); continue; } if (prev.type === 'star') { if (opts.noglobstar === true) { consume(value); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === 'slash' || prior.type === 'bos'; const afterStar = before && (before.type === 'star' || before.type === 'globstar'); if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { push({ type: 'star', value, output: '' }); continue; } const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { push({ type: 'star', value, output: '' }); continue; } // strip consecutive `/**/` while (rest.slice(0, 3) === '/**') { const after = input[state.index + 4]; if (after && after !== '/') { break; } rest = rest.slice(3); consume('/**', 3); } if (prior.type === 'bos' && eos()) { prev.type = 'globstar'; prev.value += value; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); prev.value += value; state.globstar = true; state.output += prior.output + prev.output; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { const end = rest[1] !== void 0 ? '|$' : ''; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; prev.value += value; state.output += prior.output + prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } if (prior.type === 'bos' && rest[0] === '/') { prev.type = 'globstar'; prev.value += value; prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; state.output = prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } // remove single star from output state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar prev.type = 'globstar'; prev.output = globstar(opts); prev.value += value; // reset output with globstar state.output += prev.output; state.globstar = true; consume(value); continue; } const token = { type: 'star', value, output: star }; if (opts.bash === true) { token.output = '.*?'; if (prev.type === 'bos' || prev.type === 'slash') { token.output = nodot + token.output; } push(token); continue; } if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { token.output = value; push(token); continue; } if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { if (prev.type === 'dot') { state.output += NO_DOT_SLASH; prev.output += NO_DOT_SLASH; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH; prev.output += NO_DOTS_SLASH; } else { state.output += nodot; prev.output += nodot; } if (peek() !== '*') { state.output += ONE_CHAR; prev.output += ONE_CHAR; } } push(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); state.output = utils.escapeLast(state.output, '['); decrement('brackets'); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); state.output = utils.escapeLast(state.output, '('); decrement('parens'); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); state.output = utils.escapeLast(state.output, '{'); decrement('braces'); } if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); } // rebuild the output if we had to backtrack at any point if (state.backtrack === true) { state.output = ''; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; /** * Fast paths for creating regular expressions for common glob patterns. * This can significantly speed up processing and has very little downside * impact when none of the fast paths match. */ parse$5.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS[input] || input; const win32 = utils.isWindows(options); // create constants based on platform, for windows or posix const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants.globChars(win32); const nodot = opts.dot ? NO_DOTS : NO_DOT; const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; const capture = opts.capture ? '' : '?:'; const state = { negated: false, prefix: '' }; let star = opts.bash === true ? '.*?' : STAR; if (opts.capture) { star = `(${star})`; } const globstar = (opts) => { if (opts.noglobstar === true) return star; return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const create = str => { switch (str) { case '*': return `${nodot}${ONE_CHAR}${star}`; case '.*': return `${DOT_LITERAL}${ONE_CHAR}${star}`; case '*.*': return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '*/*': return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; case '**': return nodot + globstar(opts); case '**/*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; case '**/*.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '**/.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; default: { const match = /^(.*?)\.(\w+)$/.exec(str); if (!match) return; const source = create(match[1]); if (!source) return; return source + DOT_LITERAL + match[2]; } } }; const output = utils.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; var parse_1$1 = parse$5; const isObject$1 = val => val && typeof val === 'object' && !Array.isArray(val); /** * Creates a matcher function from one or more glob patterns. The * returned function takes a string to match as its first argument, * and returns true if the string is a match. The returned matcher * function also takes a boolean as the second argument that, when true, * returns an object with additional information. * * ```js * const picomatch = require('picomatch'); * // picomatch(glob[, options]); * * const isMatch = picomatch('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @name picomatch * @param {String|Array} `globs` One or more glob patterns. * @param {Object=} `options` * @return {Function=} Returns a matcher function. * @api public */ const picomatch = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map(input => picomatch(input, options, returnState)); const arrayMatcher = str => { for (const isMatch of fns) { const state = isMatch(str); if (state) return state; } return false; }; return arrayMatcher; } const isState = isObject$1(glob) && glob.tokens && glob.input; if (glob === '' || (typeof glob !== 'string' && !isState)) { throw new TypeError('Expected pattern to be a non-empty string'); } const opts = options || {}; const posix = utils.isWindows(options); const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); const state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); const result = { glob, state, regex, posix, input, output, match, isMatch }; if (typeof opts.onResult === 'function') { opts.onResult(result); } if (isMatch === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === 'function') { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === 'function') { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher.state = state; } return matcher; }; /** * Test `input` with the given `regex`. This is used by the main * `picomatch()` function to test the input string. * * ```js * const picomatch = require('picomatch'); * // picomatch.test(input, regex[, options]); * * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } * ``` * @param {String} `input` String to test. * @param {RegExp} `regex` * @return {Object} Returns an object with matching info. * @api public */ picomatch.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected input to be a string'); } if (input === '') { return { isMatch: false, output: '' }; } const opts = options || {}; const format = opts.format || (posix ? utils.toPosixSlashes : null); let match = input === glob; let output = (match && format) ? format(input) : input; if (match === false) { output = format ? format(input) : input; match = output === glob; } if (match === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match = picomatch.matchBase(input, regex, options, posix); } else { match = regex.exec(output); } } return { isMatch: Boolean(match), match, output }; }; /** * Match the basename of a filepath. * * ```js * const picomatch = require('picomatch'); * // picomatch.matchBase(input, glob[, options]); * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true * ``` * @param {String} `input` String to test. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). * @return {Boolean} * @api public */ picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); return regex.test(path__default['default'].basename(input)); }; /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const picomatch = require('picomatch'); * // picomatch.isMatch(string, patterns[, options]); * * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String|Array} str The string to test. * @param {String|Array} patterns One or more glob patterns to use for matching. * @param {Object} [options] See available [options](#options). * @return {Boolean} Returns true if any patterns match `str` * @api public */ picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const picomatch = require('picomatch'); * const result = picomatch.parse(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as a regex source string. * @api public */ picomatch.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); return parse_1$1(pattern, { ...options, fastpaths: false }); }; /** * Scan a glob pattern to separate the pattern into segments. * * ```js * const picomatch = require('picomatch'); * // picomatch.scan(input[, options]); * * const result = picomatch.scan('!./foo/*.js'); * console.log(result); * { prefix: '!./', * input: '!./foo/*.js', * start: 3, * base: 'foo', * glob: '*.js', * isBrace: false, * isBracket: false, * isGlob: true, * isExtglob: false, * isGlobstar: false, * negated: true } * ``` * @param {String} `input` Glob pattern to scan. * @param {Object} `options` * @return {Object} Returns an object with * @api public */ picomatch.scan = (input, options) => scan_1(input, options); /** * Create a regular expression from a parsed glob pattern. * * ```js * const picomatch = require('picomatch'); * const state = picomatch.parse('*.js'); * // picomatch.compileRe(state[, options]); * * console.log(picomatch.compileRe(state)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `state` The object returned from the `.parse` method. * @param {Object} `options` * @return {RegExp} Returns a regex created from the given pattern. * @api public */ picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => { if (returnOutput === true) { return parsed.output; } const opts = options || {}; const prepend = opts.contains ? '' : '^'; const append = opts.contains ? '' : '$'; let source = `${prepend}(?:${parsed.output})${append}`; if (parsed && parsed.negated === true) { source = `^(?!${source}).*$`; } const regex = picomatch.toRegex(source, options); if (returnState === true) { regex.state = parsed; } return regex; }; picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => { if (!input || typeof input !== 'string') { throw new TypeError('Expected a non-empty string'); } const opts = options || {}; let parsed = { negated: false, fastpaths: true }; let prefix = ''; let output; if (input.startsWith('./')) { input = input.slice(2); prefix = parsed.prefix = './'; } if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { output = parse_1$1.fastpaths(input, options); } if (output === undefined) { parsed = parse_1$1(input, options); parsed.prefix = prefix + (parsed.prefix || ''); } else { parsed.output = output; } return picomatch.compileRe(parsed, options, returnOutput, returnState); }; /** * Create a regular expression from the given regex source string. * * ```js * const picomatch = require('picomatch'); * // picomatch.toRegex(source[, options]); * * const { output } = picomatch.parse('*.js'); * console.log(picomatch.toRegex(output)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `source` Regular expression source string. * @param {Object} `options` * @return {RegExp} * @api public */ picomatch.toRegex = (source, options) => { try { const opts = options || {}; return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); } catch (err) { if (options && options.debug === true) throw err; return /$^/; } }; /** * Picomatch constants. * @return {Object} */ picomatch.constants = constants; /** * Expose "picomatch" */ var picomatch_1 = picomatch; var picomatch$1 = picomatch_1; const { Readable } = stream__default['default']; const { promisify } = util__default['default']; const readdir$1 = promisify(fs__default['default'].readdir); const stat$2 = promisify(fs__default['default'].stat); const lstat = promisify(fs__default['default'].lstat); const realpath$2 = promisify(fs__default['default'].realpath); /** * @typedef {Object} EntryInfo * @property {String} path * @property {String} fullPath * @property {fs.Stats=} stats * @property {fs.Dirent=} dirent * @property {String} basename */ const BANG = '!'; const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP']); const FILE_TYPE = 'files'; const DIR_TYPE = 'directories'; const FILE_DIR_TYPE = 'files_directories'; const EVERYTHING_TYPE = 'all'; const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]; const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code); const normalizeFilter = filter => { if (filter === undefined) return; if (typeof filter === 'function') return filter; if (typeof filter === 'string') { const glob = picomatch$1(filter.trim()); return entry => glob(entry.basename); } if (Array.isArray(filter)) { const positive = []; const negative = []; for (const item of filter) { const trimmed = item.trim(); if (trimmed.charAt(0) === BANG) { negative.push(picomatch$1(trimmed.slice(1))); } else { positive.push(picomatch$1(trimmed)); } } if (negative.length > 0) { if (positive.length > 0) { return entry => positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename)); } return entry => !negative.some(f => f(entry.basename)); } return entry => positive.some(f => f(entry.basename)); } }; class ReaddirpStream extends Readable { static get defaultOptions() { return { root: '.', /* eslint-disable no-unused-vars */ fileFilter: (path) => true, directoryFilter: (path) => true, /* eslint-enable no-unused-vars */ type: FILE_TYPE, lstat: false, depth: 2147483648, alwaysStat: false }; } constructor(options = {}) { super({ objectMode: true, autoDestroy: true, highWaterMark: options.highWaterMark || 4096 }); const opts = { ...ReaddirpStream.defaultOptions, ...options }; const { root, type } = opts; this._fileFilter = normalizeFilter(opts.fileFilter); this._directoryFilter = normalizeFilter(opts.directoryFilter); const statMethod = opts.lstat ? lstat : stat$2; // Use bigint stats if it's windows and stat() supports options (node 10+). if (process.platform === 'win32' && stat$2.length === 3) { this._stat = path => statMethod(path, { bigint: true }); } else { this._stat = statMethod; } this._maxDepth = opts.depth; this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); this._wantsEverything = type === EVERYTHING_TYPE; this._root = path__default['default'].resolve(root); this._isDirent = ('Dirent' in fs__default['default']) && !opts.alwaysStat; this._statsProp = this._isDirent ? 'dirent' : 'stats'; this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent }; // Launch stream with one parent, the root dir. this.parents = [this._exploreDir(root, 1)]; this.reading = false; this.parent = undefined; } async _read(batch) { if (this.reading) return; this.reading = true; try { while (!this.destroyed && batch > 0) { const { path, depth, files = [] } = this.parent || {}; if (files.length > 0) { const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path)); for (const entry of await Promise.all(slice)) { if (this.destroyed) return; const entryType = await this._getEntryType(entry); if (entryType === 'directory' && this._directoryFilter(entry)) { if (depth <= this._maxDepth) { this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); } if (this._wantsDir) { this.push(entry); batch--; } } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) { if (this._wantsFile) { this.push(entry); batch--; } } } } else { const parent = this.parents.pop(); if (!parent) { this.push(null); break; } this.parent = await parent; if (this.destroyed) return; } } } catch (error) { this.destroy(error); } finally { this.reading = false; } } async _exploreDir(path, depth) { let files; try { files = await readdir$1(path, this._rdOptions); } catch (error) { this._onError(error); } return {files, depth, path}; } async _formatEntry(dirent, path) { let entry; try { const basename = this._isDirent ? dirent.name : dirent; const fullPath = path__default['default'].resolve(path__default['default'].join(path, basename)); entry = {path: path__default['default'].relative(this._root, fullPath), fullPath, basename}; entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); } catch (err) { this._onError(err); } return entry; } _onError(err) { if (isNormalFlowError(err) && !this.destroyed) { this.emit('warn', err); } else { this.destroy(err); } } async _getEntryType(entry) { // entry may be undefined, because a warning or an error were emitted // and the statsProp is undefined const stats = entry && entry[this._statsProp]; if (!stats) { return; } if (stats.isFile()) { return 'file'; } if (stats.isDirectory()) { return 'directory'; } if (stats && stats.isSymbolicLink()) { const full = entry.fullPath; try { const entryRealPath = await realpath$2(full); const entryRealPathStats = await lstat(entryRealPath); if (entryRealPathStats.isFile()) { return 'file'; } if (entryRealPathStats.isDirectory()) { const len = entryRealPath.length; if (full.startsWith(entryRealPath) && full.substr(len, 1) === path__default['default'].sep) { return this._onError(new Error( `Circular symlink detected: "${full}" points to "${entryRealPath}"` )); } return 'directory'; } } catch (error) { this._onError(error); } } } _includeAsFile(entry) { const stats = entry && entry[this._statsProp]; return stats && this._wantsEverything && !stats.isDirectory(); } } /** * @typedef {Object} ReaddirpArguments * @property {Function=} fileFilter * @property {Function=} directoryFilter * @property {String=} type * @property {Number=} depth * @property {String=} root * @property {Boolean=} lstat * @property {Boolean=} bigint */ /** * Main function which ends up calling readdirRec and reads all files and directories in given root recursively. * @param {String} root Root directory * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth */ const readdirp = (root, options = {}) => { let type = options.entryType || options.type; if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility if (type) options.type = type; if (!root) { throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)'); } else if (typeof root !== 'string') { throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)'); } else if (type && !ALL_TYPES.includes(type)) { throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`); } options.root = root; return new ReaddirpStream(options); }; const readdirpPromise = (root, options = {}) => { return new Promise((resolve, reject) => { const files = []; readdirp(root, options) .on('data', entry => files.push(entry)) .on('end', () => resolve(files)) .on('error', error => reject(error)); }); }; readdirp.promise = readdirpPromise; readdirp.ReaddirpStream = ReaddirpStream; readdirp.default = readdirp; var readdirp_1 = readdirp; /*! * normalize-path * * Copyright (c) 2014-2018, Jon Schlinkert. * Released under the MIT License. */ var normalizePath = function(path, stripTrailing) { if (typeof path !== 'string') { throw new TypeError('expected path to be a string'); } if (path === '\\' || path === '/') return '/'; var len = path.length; if (len <= 1) return path; // ensure that win32 namespaces has two leading slashes, so that the path is // handled properly by the win32 version of path.parse() after being normalized // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces var prefix = ''; if (len > 4 && path[3] === '\\') { var ch = path[2]; if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { path = path.slice(2); prefix = '//'; } } var segs = path.split(/[/\\]+/); if (stripTrailing !== false && segs[segs.length - 1] === '') { segs.pop(); } return prefix + segs.join('/'); }; var anymatch_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); /** * @typedef {(testString: string) => boolean} AnymatchFn * @typedef {string|RegExp|AnymatchFn} AnymatchPattern * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher */ const BANG = '!'; const DEFAULT_OPTIONS = {returnIndex: false}; const arrify = (item) => Array.isArray(item) ? item : [item]; /** * @param {AnymatchPattern} matcher * @param {object} options * @returns {AnymatchFn} */ const createPattern = (matcher, options) => { if (typeof matcher === 'function') { return matcher; } if (typeof matcher === 'string') { const glob = picomatch$1(matcher, options); return (string) => matcher === string || glob(string); } if (matcher instanceof RegExp) { return (string) => matcher.test(string); } return (string) => false; }; /** * @param {Array} patterns * @param {Array} negPatterns * @param {String|Array} args * @param {Boolean} returnIndex * @returns {boolean|number} */ const matchPatterns = (patterns, negPatterns, args, returnIndex) => { const isList = Array.isArray(args); const _path = isList ? args[0] : args; if (!isList && typeof _path !== 'string') { throw new TypeError('anymatch: second argument must be a string: got ' + Object.prototype.toString.call(_path)) } const path = normalizePath(_path); for (let index = 0; index < negPatterns.length; index++) { const nglob = negPatterns[index]; if (nglob(path)) { return returnIndex ? -1 : false; } } const applied = isList && [path].concat(args.slice(1)); for (let index = 0; index < patterns.length; index++) { const pattern = patterns[index]; if (isList ? pattern(...applied) : pattern(path)) { return returnIndex ? index : true; } } return returnIndex ? -1 : false; }; /** * @param {AnymatchMatcher} matchers * @param {Array|string} testString * @param {object} options * @returns {boolean|number|Function} */ const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { if (matchers == null) { throw new TypeError('anymatch: specify first argument'); } const opts = typeof options === 'boolean' ? {returnIndex: options} : options; const returnIndex = opts.returnIndex || false; // Early cache for matchers. const mtchers = arrify(matchers); const negatedGlobs = mtchers .filter(item => typeof item === 'string' && item.charAt(0) === BANG) .map(item => item.slice(1)) .map(item => picomatch$1(item, opts)); const patterns = mtchers.map(matcher => createPattern(matcher, opts)); if (testString == null) { return (testString, ri = false) => { const returnIndex = typeof ri === 'boolean' ? ri : false; return matchPatterns(patterns, negatedGlobs, testString, returnIndex); } } return matchPatterns(patterns, negatedGlobs, testString, returnIndex); }; anymatch.default = anymatch; module.exports = anymatch; }); unwrapExports(anymatch_1); /*! * is-extglob * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ var isExtglob = function isExtglob(str) { if (typeof str !== 'string' || str === '') { return false; } var match; while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { if (match[2]) return true; str = str.slice(match.index + match[0].length); } return false; }; /*! * is-glob * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ var chars$1 = { '{': '}', '(': ')', '[': ']'}; var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; var isGlob = function isGlob(str, options) { if (typeof str !== 'string' || str === '') { return false; } if (isExtglob(str)) { return true; } var regex = strictRegex; var match; // optionally relax regex if (options && options.strict === false) { regex = relaxedRegex; } while ((match = regex.exec(str))) { if (match[2]) return true; var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped, // set the index to the next closing character var open = match[1]; var close = open ? chars$1[open] : null; if (open && close) { var n = str.indexOf(close, idx); if (n !== -1) { idx = n + 1; } } str = str.slice(idx); } return false; }; var pathPosixDirname = path__default['default'].posix.dirname; var isWin32 = os__default['default'].platform() === 'win32'; var slash = '/'; var backslash = /\\/g; var enclosure = /[\{\[].*[\/]*.*[\}\]]$/; var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; /** * @param {string} str * @param {Object} opts * @param {boolean} [opts.flipBackslashes=true] */ var globParent = function globParent(str, opts) { var options = Object.assign({ flipBackslashes: true }, opts); // flip windows path separators if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { str = str.replace(backslash, slash); } // special case for strings ending in enclosure containing path separator if (enclosure.test(str)) { str += slash; } // preserves full path in case of trailing path separator str += 'a'; // remove path parts that are globby do { str = pathPosixDirname(str); } while (isGlob(str) || globby.test(str)); // remove escape chars and return result return str.replace(escaped, '$1'); }; var utils$1 = createCommonjsModule(function (module, exports) { exports.isInteger = num => { if (typeof num === 'number') { return Number.isInteger(num); } if (typeof num === 'string' && num.trim() !== '') { return Number.isInteger(Number(num)); } return false; }; /** * Find a node of the given type */ exports.find = (node, type) => node.nodes.find(node => node.type === type); /** * Find a node of the given type */ exports.exceedsLimit = (min, max, step = 1, limit) => { if (limit === false) return false; if (!exports.isInteger(min) || !exports.isInteger(max)) return false; return ((Number(max) - Number(min)) / Number(step)) >= limit; }; /** * Escape the given node with '\\' before node.value */ exports.escapeNode = (block, n = 0, type) => { let node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { if (node.escaped !== true) { node.value = '\\' + node.value; node.escaped = true; } } }; /** * Returns true if the given brace node should be enclosed in literal braces */ exports.encloseBrace = node => { if (node.type !== 'brace') return false; if ((node.commas >> 0 + node.ranges >> 0) === 0) { node.invalid = true; return true; } return false; }; /** * Returns true if a brace node is invalid. */ exports.isInvalidBrace = block => { if (block.type !== 'brace') return false; if (block.invalid === true || block.dollar) return true; if ((block.commas >> 0 + block.ranges >> 0) === 0) { block.invalid = true; return true; } if (block.open !== true || block.close !== true) { block.invalid = true; return true; } return false; }; /** * Returns true if a node is an open or close node */ exports.isOpenOrClose = node => { if (node.type === 'open' || node.type === 'close') { return true; } return node.open === true || node.close === true; }; /** * Reduce an array of text nodes. */ exports.reduce = nodes => nodes.reduce((acc, node) => { if (node.type === 'text') acc.push(node.value); if (node.type === 'range') node.type = 'text'; return acc; }, []); /** * Flatten an array */ exports.flatten = (...args) => { const result = []; const flat = arr => { for (let i = 0; i < arr.length; i++) { let ele = arr[i]; Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); } return result; }; flat(args); return result; }; }); var utils_1$1 = utils$1.isInteger; var utils_2$1 = utils$1.find; var utils_3$1 = utils$1.exceedsLimit; var utils_4$1 = utils$1.escapeNode; var utils_5$1 = utils$1.encloseBrace; var utils_6$1 = utils$1.isInvalidBrace; var utils_7$1 = utils$1.isOpenOrClose; var utils_8$1 = utils$1.reduce; var utils_9$1 = utils$1.flatten; var stringify$3 = (ast, options = {}) => { let stringify = (node, parent = {}) => { let invalidBlock = options.escapeInvalid && utils$1.isInvalidBrace(parent); let invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { if ((invalidBlock || invalidNode) && utils$1.isOpenOrClose(node)) { return '\\' + node.value; } return node.value; } if (node.value) { return node.value; } if (node.nodes) { for (let child of node.nodes) { output += stringify(child); } } return output; }; return stringify(ast); }; /*! * is-number * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. */ var isNumber = function(num) { if (typeof num === 'number') { return num - num === 0; } if (typeof num === 'string' && num.trim() !== '') { return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); } return false; }; const toRegexRange = (min, max, options) => { if (isNumber(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange.cache.hasOwnProperty(cacheKey)) { return toRegexRange.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false) || []; let onlyPositive = filterPatterns(pos, neg, '', false) || []; let intersected = filterPatterns(neg, pos, '-?', true) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare$1); return stops; } /** * Convert a range to a regex pattern * @param {Number} `start` * @param {Number} `stop` * @return {String} */ function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare$1(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange.cache = {}; toRegexRange.clearCache = () => (toRegexRange.cache = {}); /** * Expose `toRegexRange` */ var toRegexRange_1 = toRegexRange; const isObject$2 = val => val !== null && typeof val === 'object' && !Array.isArray(val); const transform$2 = toNumber => { return value => toNumber === true ? Number(value) : String(value); }; const isValidValue = value => { return typeof value === 'number' || (typeof value === 'string' && value !== ''); }; const isNumber$1 = num => Number.isInteger(+num); const zeros = input => { let value = `${input}`; let index = -1; if (value[0] === '-') value = value.slice(1); if (value === '0') return false; while (value[++index] === '0'); return index > 0; }; const stringify$4 = (start, end, options) => { if (typeof start === 'string' || typeof end === 'string') { return true; } return options.stringify === true; }; const pad = (input, maxLength, toNumber) => { if (maxLength > 0) { let dash = input[0] === '-' ? '-' : ''; if (dash) input = input.slice(1); input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); } if (toNumber === false) { return String(input); } return input; }; const toMaxLen = (input, maxLength) => { let negative = input[0] === '-' ? '-' : ''; if (negative) { input = input.slice(1); maxLength--; } while (input.length < maxLength) input = '0' + input; return negative ? ('-' + input) : input; }; const toSequence = (parts, options) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); let prefix = options.capture ? '' : '?:'; let positives = ''; let negatives = ''; let result; if (parts.positives.length) { positives = parts.positives.join('|'); } if (parts.negatives.length) { negatives = `-(${prefix}${parts.negatives.join('|')})`; } if (positives && negatives) { result = `${positives}|${negatives}`; } else { result = positives || negatives; } if (options.wrap) { return `(${prefix}${result})`; } return result; }; const toRange = (a, b, isNumbers, options) => { if (isNumbers) { return toRegexRange_1(a, b, { wrap: false, ...options }); } let start = String.fromCharCode(a); if (a === b) return start; let stop = String.fromCharCode(b); return `[${start}-${stop}]`; }; const toRegex = (start, end, options) => { if (Array.isArray(start)) { let wrap = options.wrap === true; let prefix = options.capture ? '' : '?:'; return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); } return toRegexRange_1(start, end, options); }; const rangeError = (...args) => { return new RangeError('Invalid range arguments: ' + util__default['default'].inspect(...args)); }; const invalidRange = (start, end, options) => { if (options.strictRanges === true) throw rangeError([start, end]); return []; }; const invalidStep = (step, options) => { if (options.strictRanges === true) { throw new TypeError(`Expected step "${step}" to be a number`); } return []; }; const fillNumbers = (start, end, step = 1, options = {}) => { let a = Number(start); let b = Number(end); if (!Number.isInteger(a) || !Number.isInteger(b)) { if (options.strictRanges === true) throw rangeError([start, end]); return []; } // fix negative zero if (a === 0) a = 0; if (b === 0) b = 0; let descending = a > b; let startString = String(start); let endString = String(end); let stepString = String(step); step = Math.max(Math.abs(step), 1); let padded = zeros(startString) || zeros(endString) || zeros(stepString); let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; let toNumber = padded === false && stringify$4(start, end, options) === false; let format = options.transform || transform$2(toNumber); if (options.toRegex && step === 1) { return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); } let parts = { negatives: [], positives: [] }; let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); let range = []; let index = 0; while (descending ? a >= b : a <= b) { if (options.toRegex === true && step > 1) { push(a); } else { range.push(pad(format(a, index), maxLen, toNumber)); } a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return step > 1 ? toSequence(parts, options) : toRegex(range, null, { wrap: false, ...options }); } return range; }; const fillLetters = (start, end, step = 1, options = {}) => { if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) { return invalidRange(start, end, options); } let format = options.transform || (val => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); let descending = a > b; let min = Math.min(a, b); let max = Math.max(a, b); if (options.toRegex && step === 1) { return toRange(min, max, false, options); } let range = []; let index = 0; while (descending ? a >= b : a <= b) { range.push(format(a, index)); a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return toRegex(range, null, { wrap: false, options }); } return range; }; const fill = (start, end, step, options = {}) => { if (end == null && isValidValue(start)) { return [start]; } if (!isValidValue(start) || !isValidValue(end)) { return invalidRange(start, end, options); } if (typeof step === 'function') { return fill(start, end, 1, { transform: step }); } if (isObject$2(step)) { return fill(start, end, 0, step); } let opts = { ...options }; if (opts.capture === true) opts.wrap = true; step = step || opts.step || 1; if (!isNumber$1(step)) { if (step != null && !isObject$2(step)) return invalidStep(step, opts); return fill(start, end, 1, step); } if (isNumber$1(start) && isNumber$1(end)) { return fillNumbers(start, end, step, opts); } return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); }; var fillRange = fill; const compile$2 = (ast, options = {}) => { let walk = (node, parent = {}) => { let invalidBlock = utils$1.isInvalidBrace(parent); let invalidNode = node.invalid === true && options.escapeInvalid === true; let invalid = invalidBlock === true || invalidNode === true; let prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } if (node.isClose === true) { return prefix + node.value; } if (node.type === 'open') { return invalid ? (prefix + node.value) : '('; } if (node.type === 'close') { return invalid ? (prefix + node.value) : ')'; } if (node.type === 'comma') { return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); } if (node.value) { return node.value; } if (node.nodes && node.ranges > 0) { let args = utils$1.reduce(node.nodes); let range = fillRange(...args, { ...options, wrap: false, toRegex: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; } } if (node.nodes) { for (let child of node.nodes) { output += walk(child, node); } } return output; }; return walk(ast); }; var compile_1 = compile$2; const append = (queue = '', stash = '', enclose = false) => { let result = []; queue = [].concat(queue); stash = [].concat(stash); if (!stash.length) return queue; if (!queue.length) { return enclose ? utils$1.flatten(stash).map(ele => `{${ele}}`) : stash; } for (let item of queue) { if (Array.isArray(item)) { for (let value of item) { result.push(append(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); } } } return utils$1.flatten(result); }; const expand$2 = (ast, options = {}) => { let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; let walk = (node, parent = {}) => { node.queue = []; let p = parent; let q = parent.queue; while (p.type !== 'brace' && p.type !== 'root' && p.parent) { p = p.parent; q = p.queue; } if (node.invalid || node.dollar) { q.push(append(q.pop(), stringify$3(node, options))); return; } if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { q.push(append(q.pop(), ['{}'])); return; } if (node.nodes && node.ranges > 0) { let args = utils$1.reduce(node.nodes); if (utils$1.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); } let range = fillRange(...args, options); if (range.length === 0) { range = stringify$3(node, options); } q.push(append(q.pop(), range)); node.nodes = []; return; } let enclose = utils$1.encloseBrace(node); let queue = node.queue; let block = node; while (block.type !== 'brace' && block.type !== 'root' && block.parent) { block = block.parent; queue = block.queue; } for (let i = 0; i < node.nodes.length; i++) { let child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); queue.push(''); continue; } if (child.type === 'close') { q.push(append(q.pop(), queue, enclose)); continue; } if (child.value && child.type !== 'open') { queue.push(append(queue.pop(), child.value)); continue; } if (child.nodes) { walk(child, node); } } return queue; }; return utils$1.flatten(walk(ast)); }; var expand_1 = expand$2; var constants$1 = { MAX_LENGTH: 1024 * 64, // Digits CHAR_0: '0', /* 0 */ CHAR_9: '9', /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 'A', /* A */ CHAR_LOWERCASE_A: 'a', /* a */ CHAR_UPPERCASE_Z: 'Z', /* Z */ CHAR_LOWERCASE_Z: 'z', /* z */ CHAR_LEFT_PARENTHESES: '(', /* ( */ CHAR_RIGHT_PARENTHESES: ')', /* ) */ CHAR_ASTERISK: '*', /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: '&', /* & */ CHAR_AT: '@', /* @ */ CHAR_BACKSLASH: '\\', /* \ */ CHAR_BACKTICK: '`', /* ` */ CHAR_CARRIAGE_RETURN: '\r', /* \r */ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ CHAR_COLON: ':', /* : */ CHAR_COMMA: ',', /* , */ CHAR_DOLLAR: '$', /* . */ CHAR_DOT: '.', /* . */ CHAR_DOUBLE_QUOTE: '"', /* " */ CHAR_EQUAL: '=', /* = */ CHAR_EXCLAMATION_MARK: '!', /* ! */ CHAR_FORM_FEED: '\f', /* \f */ CHAR_FORWARD_SLASH: '/', /* / */ CHAR_HASH: '#', /* # */ CHAR_HYPHEN_MINUS: '-', /* - */ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ CHAR_LEFT_CURLY_BRACE: '{', /* { */ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ CHAR_LINE_FEED: '\n', /* \n */ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ CHAR_PERCENT: '%', /* % */ CHAR_PLUS: '+', /* + */ CHAR_QUESTION_MARK: '?', /* ? */ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ CHAR_RIGHT_CURLY_BRACE: '}', /* } */ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ CHAR_SEMICOLON: ';', /* ; */ CHAR_SINGLE_QUOTE: '\'', /* ' */ CHAR_SPACE: ' ', /* */ CHAR_TAB: '\t', /* \t */ CHAR_UNDERSCORE: '_', /* _ */ CHAR_VERTICAL_LINE: '|', /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ }; /** * Constants */ const { MAX_LENGTH: MAX_LENGTH$1, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA: CHAR_COMMA$2, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$2, /* [ */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$2, /* ] */ CHAR_DOUBLE_QUOTE: CHAR_DOUBLE_QUOTE$1, /* " */ CHAR_SINGLE_QUOTE: CHAR_SINGLE_QUOTE$1, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = constants$1; /** * parse */ const parse$6 = (input, options = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } let opts = options || {}; let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } let ast = { type: 'root', input, nodes: [] }; let stack = [ast]; let block = ast; let prev = ast; let brackets = 0; let length = input.length; let index = 0; let depth = 0; let value; /** * Helpers */ const advance = () => input[index++]; const push = node => { if (node.type === 'text' && prev.type === 'dot') { prev.type = 'text'; } if (prev && prev.type === 'text' && node.type === 'text') { prev.value += node.value; return; } block.nodes.push(node); node.parent = block; node.prev = prev; prev = node; return node; }; push({ type: 'bos' }); while (index < length) { block = stack[stack.length - 1]; value = advance(); /** * Invalid chars */ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { continue; } /** * Escaped chars */ if (value === CHAR_BACKSLASH) { push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); continue; } /** * Right square bracket (literal): ']' */ if (value === CHAR_RIGHT_SQUARE_BRACKET$2) { push({ type: 'text', value: '\\' + value }); continue; } /** * Left square bracket: '[' */ if (value === CHAR_LEFT_SQUARE_BRACKET$2) { brackets++; let next; while (index < length && (next = advance())) { value += next; if (next === CHAR_LEFT_SQUARE_BRACKET$2) { brackets++; continue; } if (next === CHAR_BACKSLASH) { value += advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$2) { brackets--; if (brackets === 0) { break; } } } push({ type: 'text', value }); continue; } /** * Parentheses */ if (value === CHAR_LEFT_PARENTHESES$1) { block = push({ type: 'paren', nodes: [] }); stack.push(block); push({ type: 'text', value }); continue; } if (value === CHAR_RIGHT_PARENTHESES$1) { if (block.type !== 'paren') { push({ type: 'text', value }); continue; } block = stack.pop(); push({ type: 'text', value }); block = stack[stack.length - 1]; continue; } /** * Quotes: '|"|` */ if (value === CHAR_DOUBLE_QUOTE$1 || value === CHAR_SINGLE_QUOTE$1 || value === CHAR_BACKTICK) { let open = value; let next; if (options.keepQuotes !== true) { value = ''; } while (index < length && (next = advance())) { if (next === CHAR_BACKSLASH) { value += next + advance(); continue; } if (next === open) { if (options.keepQuotes === true) value += next; break; } value += next; } push({ type: 'text', value }); continue; } /** * Left curly brace: '{' */ if (value === CHAR_LEFT_CURLY_BRACE$1) { depth++; let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; let brace = { type: 'brace', open: true, close: false, dollar, depth, commas: 0, ranges: 0, nodes: [] }; block = push(brace); stack.push(block); push({ type: 'open', value }); continue; } /** * Right curly brace: '}' */ if (value === CHAR_RIGHT_CURLY_BRACE$1) { if (block.type !== 'brace') { push({ type: 'text', value }); continue; } let type = 'close'; block = stack.pop(); block.close = true; push({ type, value }); depth--; block = stack[stack.length - 1]; continue; } /** * Comma: ',' */ if (value === CHAR_COMMA$2 && depth > 0) { if (block.ranges > 0) { block.ranges = 0; let open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify$3(block) }]; } push({ type: 'comma', value }); block.commas++; continue; } /** * Dot: '.' */ if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) { let siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); continue; } if (prev.type === 'dot') { block.range = []; prev.value += value; prev.type = 'range'; if (block.nodes.length !== 3 && block.nodes.length !== 5) { block.invalid = true; block.ranges = 0; prev.type = 'text'; continue; } block.ranges++; block.args = []; continue; } if (prev.type === 'range') { siblings.pop(); let before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; continue; } push({ type: 'dot', value }); continue; } /** * Text */ push({ type: 'text', value }); } // Mark imbalanced braces and brackets as invalid do { block = stack.pop(); if (block.type !== 'root') { block.nodes.forEach(node => { if (!node.nodes) { if (node.type === 'open') node.isOpen = true; if (node.type === 'close') node.isClose = true; if (!node.nodes) node.type = 'text'; node.invalid = true; } }); // get the location of the block on parent.nodes (block's siblings) let parent = stack[stack.length - 1]; let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } } while (stack.length > 0); push({ type: 'eos' }); return ast; }; var parse_1$2 = parse$6; /** * Expand the given pattern or create a regex-compatible string. * * ```js * const braces = require('braces'); * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] * ``` * @param {String} `str` * @param {Object} `options` * @return {String} * @api public */ const braces = (input, options = {}) => { let output = []; if (Array.isArray(input)) { for (let pattern of input) { let result = braces.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { output.push(result); } } } else { output = [].concat(braces.create(input, options)); } if (options && options.expand === true && options.nodupes === true) { output = [...new Set(output)]; } return output; }; /** * Parse the given `str` with the given `options`. * * ```js * // braces.parse(pattern, [, options]); * const ast = braces.parse('a/{b,c}/d'); * console.log(ast); * ``` * @param {String} pattern Brace pattern to parse * @param {Object} options * @return {Object} Returns an AST * @api public */ braces.parse = (input, options = {}) => parse_1$2(input, options); /** * Creates a braces string from an AST, or an AST node. * * ```js * const braces = require('braces'); * let ast = braces.parse('foo/{a,b}/bar'); * console.log(stringify(ast.nodes[2])); //=> '{a,b}' * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.stringify = (input, options = {}) => { if (typeof input === 'string') { return stringify$3(braces.parse(input, options), options); } return stringify$3(input, options); }; /** * Compiles a brace pattern into a regex-compatible, optimized string. * This method is called by the main [braces](#braces) function by default. * * ```js * const braces = require('braces'); * console.log(braces.compile('a/{b,c}/d')); * //=> ['a/(b|c)/d'] * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.compile = (input, options = {}) => { if (typeof input === 'string') { input = braces.parse(input, options); } return compile_1(input, options); }; /** * Expands a brace pattern into an array. This method is called by the * main [braces](#braces) function when `options.expand` is true. Before * using this method it's recommended that you read the [performance notes](#performance)) * and advantages of using [.compile](#compile) instead. * * ```js * const braces = require('braces'); * console.log(braces.expand('a/{b,c}/d')); * //=> ['a/b/d', 'a/c/d']; * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.expand = (input, options = {}) => { if (typeof input === 'string') { input = braces.parse(input, options); } let result = expand_1(input, options); // filter out empty strings if specified if (options.noempty === true) { result = result.filter(Boolean); } // filter out duplicates if specified if (options.nodupes === true) { result = [...new Set(result)]; } return result; }; /** * Processes a brace pattern and returns either an expanded array * (if `options.expand` is true), a highly optimized regex-compatible string. * This method is called by the main [braces](#braces) function. * * ```js * const braces = require('braces'); * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.create = (input, options = {}) => { if (input === '' || input.length < 3) { return [input]; } return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); }; /** * Expose "braces" */ var braces_1 = braces; var binaryExtensions = [ "3dm", "3ds", "3g2", "3gp", "7z", "a", "aac", "adp", "ai", "aif", "aiff", "alz", "ape", "apk", "appimage", "ar", "arj", "asf", "au", "avi", "bak", "baml", "bh", "bin", "bk", "bmp", "btif", "bz2", "bzip2", "cab", "caf", "cgm", "class", "cmx", "cpio", "cr2", "cur", "dat", "dcm", "deb", "dex", "djvu", "dll", "dmg", "dng", "doc", "docm", "docx", "dot", "dotm", "dra", "DS_Store", "dsk", "dts", "dtshd", "dvb", "dwg", "dxf", "ecelp4800", "ecelp7470", "ecelp9600", "egg", "eol", "eot", "epub", "exe", "f4v", "fbs", "fh", "fla", "flac", "flatpak", "fli", "flv", "fpx", "fst", "fvt", "g3", "gh", "gif", "graffle", "gz", "gzip", "h261", "h263", "h264", "icns", "ico", "ief", "img", "ipa", "iso", "jar", "jpeg", "jpg", "jpgv", "jpm", "jxr", "key", "ktx", "lha", "lib", "lvp", "lz", "lzh", "lzma", "lzo", "m3u", "m4a", "m4v", "mar", "mdi", "mht", "mid", "midi", "mj2", "mka", "mkv", "mmr", "mng", "mobi", "mov", "movie", "mp3", "mp4", "mp4a", "mpeg", "mpg", "mpga", "mxu", "nef", "npx", "numbers", "nupkg", "o", "oga", "ogg", "ogv", "otf", "pages", "pbm", "pcx", "pdb", "pdf", "pea", "pgm", "pic", "png", "pnm", "pot", "potm", "potx", "ppa", "ppam", "ppm", "pps", "ppsm", "ppsx", "ppt", "pptm", "pptx", "psd", "pya", "pyc", "pyo", "pyv", "qt", "rar", "ras", "raw", "resources", "rgb", "rip", "rlc", "rmf", "rmvb", "rpm", "rtf", "rz", "s3m", "s7z", "scpt", "sgi", "shar", "snap", "sil", "sketch", "slk", "smv", "snk", "so", "stl", "suo", "sub", "swf", "tar", "tbz", "tbz2", "tga", "tgz", "thmx", "tif", "tiff", "tlz", "ttc", "ttf", "txz", "udf", "uvh", "uvi", "uvm", "uvp", "uvs", "uvu", "viv", "vob", "war", "wav", "wax", "wbmp", "wdp", "weba", "webm", "webp", "whl", "wim", "wm", "wma", "wmv", "wmx", "woff", "woff2", "wrm", "wvx", "xbm", "xif", "xla", "xlam", "xls", "xlsb", "xlsm", "xlsx", "xlt", "xltm", "xltx", "xm", "xmind", "xpi", "xpm", "xwd", "xz", "z", "zip", "zipx" ]; var binaryExtensions$1 = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': binaryExtensions }); var require$$0$1 = getCjsExportFromNamespace(binaryExtensions$1); var binaryExtensions$2 = require$$0$1; const extensions = new Set(binaryExtensions$2); var isBinaryPath = filePath => extensions.has(path__default['default'].extname(filePath).slice(1).toLowerCase()); var constants$2 = createCommonjsModule(function (module, exports) { const {sep} = path__default['default']; const {platform} = process; exports.EV_ALL = 'all'; exports.EV_READY = 'ready'; exports.EV_ADD = 'add'; exports.EV_CHANGE = 'change'; exports.EV_ADD_DIR = 'addDir'; exports.EV_UNLINK = 'unlink'; exports.EV_UNLINK_DIR = 'unlinkDir'; exports.EV_RAW = 'raw'; exports.EV_ERROR = 'error'; exports.STR_DATA = 'data'; exports.STR_END = 'end'; exports.STR_CLOSE = 'close'; exports.FSEVENT_CREATED = 'created'; exports.FSEVENT_MODIFIED = 'modified'; exports.FSEVENT_DELETED = 'deleted'; exports.FSEVENT_MOVED = 'moved'; exports.FSEVENT_CLONED = 'cloned'; exports.FSEVENT_UNKNOWN = 'unknown'; exports.FSEVENT_TYPE_FILE = 'file'; exports.FSEVENT_TYPE_DIRECTORY = 'directory'; exports.FSEVENT_TYPE_SYMLINK = 'symlink'; exports.KEY_LISTENERS = 'listeners'; exports.KEY_ERR = 'errHandlers'; exports.KEY_RAW = 'rawEmitters'; exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW]; exports.DOT_SLASH = `.${sep}`; exports.BACK_SLASH_RE = /\\/g; exports.DOUBLE_SLASH_RE = /\/\//; exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/; exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; exports.REPLACER_RE = /^\.[/\\]/; exports.SLASH = '/'; exports.SLASH_SLASH = '//'; exports.BRACE_START = '{'; exports.BANG = '!'; exports.ONE_DOT = '.'; exports.TWO_DOTS = '..'; exports.STAR = '*'; exports.GLOBSTAR = '**'; exports.ROOT_GLOBSTAR = '/**/*'; exports.SLASH_GLOBSTAR = '/**'; exports.DIR_SUFFIX = 'Dir'; exports.ANYMATCH_OPTS = {dot: true}; exports.STRING_TYPE = 'string'; exports.FUNCTION_TYPE = 'function'; exports.EMPTY_STR = ''; exports.EMPTY_FN = () => {}; exports.IDENTITY_FN = val => val; exports.isWindows = platform === 'win32'; exports.isMacos = platform === 'darwin'; exports.isLinux = platform === 'linux'; }); var constants_1 = constants$2.EV_ALL; var constants_2 = constants$2.EV_READY; var constants_3 = constants$2.EV_ADD; var constants_4 = constants$2.EV_CHANGE; var constants_5 = constants$2.EV_ADD_DIR; var constants_6 = constants$2.EV_UNLINK; var constants_7 = constants$2.EV_UNLINK_DIR; var constants_8 = constants$2.EV_RAW; var constants_9 = constants$2.EV_ERROR; var constants_10 = constants$2.STR_DATA; var constants_11 = constants$2.STR_END; var constants_12 = constants$2.STR_CLOSE; var constants_13 = constants$2.FSEVENT_CREATED; var constants_14 = constants$2.FSEVENT_MODIFIED; var constants_15 = constants$2.FSEVENT_DELETED; var constants_16 = constants$2.FSEVENT_MOVED; var constants_17 = constants$2.FSEVENT_CLONED; var constants_18 = constants$2.FSEVENT_UNKNOWN; var constants_19 = constants$2.FSEVENT_TYPE_FILE; var constants_20 = constants$2.FSEVENT_TYPE_DIRECTORY; var constants_21 = constants$2.FSEVENT_TYPE_SYMLINK; var constants_22 = constants$2.KEY_LISTENERS; var constants_23 = constants$2.KEY_ERR; var constants_24 = constants$2.KEY_RAW; var constants_25 = constants$2.HANDLER_KEYS; var constants_26 = constants$2.DOT_SLASH; var constants_27 = constants$2.BACK_SLASH_RE; var constants_28 = constants$2.DOUBLE_SLASH_RE; var constants_29 = constants$2.SLASH_OR_BACK_SLASH_RE; var constants_30 = constants$2.DOT_RE; var constants_31 = constants$2.REPLACER_RE; var constants_32 = constants$2.SLASH; var constants_33 = constants$2.SLASH_SLASH; var constants_34 = constants$2.BRACE_START; var constants_35 = constants$2.BANG; var constants_36 = constants$2.ONE_DOT; var constants_37 = constants$2.TWO_DOTS; var constants_38 = constants$2.STAR; var constants_39 = constants$2.GLOBSTAR; var constants_40 = constants$2.ROOT_GLOBSTAR; var constants_41 = constants$2.SLASH_GLOBSTAR; var constants_42 = constants$2.DIR_SUFFIX; var constants_43 = constants$2.ANYMATCH_OPTS; var constants_44 = constants$2.STRING_TYPE; var constants_45 = constants$2.FUNCTION_TYPE; var constants_46 = constants$2.EMPTY_STR; var constants_47 = constants$2.EMPTY_FN; var constants_48 = constants$2.IDENTITY_FN; var constants_49 = constants$2.isWindows; var constants_50 = constants$2.isMacos; var constants_51 = constants$2.isLinux; const { promisify: promisify$1 } = util__default['default']; const { isWindows: isWindows$1, isLinux, EMPTY_FN, EMPTY_STR, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, EV_CHANGE, EV_ADD, EV_ADD_DIR, EV_ERROR, STR_DATA, STR_END, BRACE_START, STAR: STAR$1 } = constants$2; const THROTTLE_MODE_WATCH = 'watch'; const open = promisify$1(fs__default['default'].open); const stat$3 = promisify$1(fs__default['default'].stat); const lstat$1 = promisify$1(fs__default['default'].lstat); const close = promisify$1(fs__default['default'].close); const fsrealpath = promisify$1(fs__default['default'].realpath); const statMethods = { lstat: lstat$1, stat: stat$3 }; // TODO: emit errors properly. Example: EMFILE on Macos. const foreach = (val, fn) => { if (val instanceof Set) { val.forEach(fn); } else { fn(val); } }; const addAndConvert = (main, prop, item) => { let container = main[prop]; if (!(container instanceof Set)) { main[prop] = container = new Set([container]); } container.add(item); }; const clearItem = cont => key => { const set = cont[key]; if (set instanceof Set) { set.clear(); } else { delete cont[key]; } }; const delFromSet = (main, prop, item) => { const container = main[prop]; if (container instanceof Set) { container.delete(item); } else if (container === item) { delete main[prop]; } }; const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; /** * @typedef {String} Path */ // fs_watch helpers // object to hold per-process fs_watch instances // (may be shared across chokidar FSWatcher instances) /** * @typedef {Object} FsWatchContainer * @property {Set} listeners * @property {Set} errHandlers * @property {Set} rawEmitters * @property {fs.FSWatcher=} watcher * @property {Boolean=} watcherUnusable */ /** * @type {Map} */ const FsWatchInstances = new Map(); /** * Instantiates the fs_watch interface * @param {String} path to be watched * @param {Object} options to be passed to fs_watch * @param {Function} listener main event handler * @param {Function} errHandler emits info about errors * @param {Function} emitRaw emits raw event data * @returns {fs.FSWatcher} new fsevents instance */ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { const handleEvent = (rawEvent, evPath) => { listener(path); emitRaw(rawEvent, evPath, {watchedPath: path}); // emit based on events occurring for files from a directory's watcher in // case the file's watcher misses it (and rely on throttling to de-dupe) if (evPath && path !== evPath) { fsWatchBroadcast( path__default['default'].resolve(path, evPath), KEY_LISTENERS, path__default['default'].join(path, evPath) ); } }; try { return fs__default['default'].watch(path, options, handleEvent); } catch (error) { errHandler(error); } } /** * Helper for passing fs_watch event data to a collection of listeners * @param {Path} fullPath absolute path bound to fs_watch instance * @param {String} type listener type * @param {*=} val1 arguments to be passed to listeners * @param {*=} val2 * @param {*=} val3 */ const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => { const cont = FsWatchInstances.get(fullPath); if (!cont) return; foreach(cont[type], (listener) => { listener(val1, val2, val3); }); }; /** * Instantiates the fs_watch interface or binds listeners * to an existing one covering the same file system entry * @param {String} path * @param {String} fullPath absolute path * @param {Object} options to be passed to fs_watch * @param {Object} handlers container for event listener functions */ const setFsWatchListener = (path, fullPath, options, handlers) => { const {listener, errHandler, rawEmitter} = handlers; let cont = FsWatchInstances.get(fullPath); /** @type {fs.FSWatcher=} */ let watcher; if (!options.persistent) { watcher = createFsWatchInstance( path, options, listener, errHandler, rawEmitter ); return watcher.close.bind(watcher); } if (cont) { addAndConvert(cont, KEY_LISTENERS, listener); addAndConvert(cont, KEY_ERR, errHandler); addAndConvert(cont, KEY_RAW, rawEmitter); } else { watcher = createFsWatchInstance( path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here fsWatchBroadcast.bind(null, fullPath, KEY_RAW) ); if (!watcher) return; watcher.on(EV_ERROR, async (error) => { const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); cont.watcherUnusable = true; // documented since Node 10.4.1 // Workaround for https://github.com/joyent/node/issues/4337 if (isWindows$1 && error.code === 'EPERM') { try { const fd = await open(path, 'r'); await close(fd); broadcastErr(error); } catch (err) {} } else { broadcastErr(error); } }); cont = { listeners: listener, errHandlers: errHandler, rawEmitters: rawEmitter, watcher }; FsWatchInstances.set(fullPath, cont); } // const index = cont.listeners.indexOf(listener); // removes this instance's listeners and closes the underlying fs_watch // instance if there are no more listeners left return () => { delFromSet(cont, KEY_LISTENERS, listener); delFromSet(cont, KEY_ERR, errHandler); delFromSet(cont, KEY_RAW, rawEmitter); if (isEmptySet(cont.listeners)) { // Check to protect against issue gh-730. // if (cont.watcherUnusable) { cont.watcher.close(); // } FsWatchInstances.delete(fullPath); HANDLER_KEYS.forEach(clearItem(cont)); cont.watcher = undefined; Object.freeze(cont); } }; }; // fs_watchFile helpers // object to hold per-process fs_watchFile instances // (may be shared across chokidar FSWatcher instances) const FsWatchFileInstances = new Map(); /** * Instantiates the fs_watchFile interface or binds listeners * to an existing one covering the same file system entry * @param {String} path to be watched * @param {String} fullPath absolute path * @param {Object} options options to be passed to fs_watchFile * @param {Object} handlers container for event listener functions * @returns {Function} closer */ const setFsWatchFileListener = (path, fullPath, options, handlers) => { const {listener, rawEmitter} = handlers; let cont = FsWatchFileInstances.get(fullPath); /* eslint-disable no-unused-vars, prefer-destructuring */ let listeners = new Set(); let rawEmitters = new Set(); const copts = cont && cont.options; if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { // "Upgrade" the watcher to persistence or a quicker interval. // This creates some unlikely edge case issues if the user mixes // settings in a very weird way, but solving for those cases // doesn't seem worthwhile for the added complexity. listeners = cont.listeners; rawEmitters = cont.rawEmitters; fs__default['default'].unwatchFile(fullPath); cont = undefined; } /* eslint-enable no-unused-vars, prefer-destructuring */ if (cont) { addAndConvert(cont, KEY_LISTENERS, listener); addAndConvert(cont, KEY_RAW, rawEmitter); } else { // TODO // listeners.add(listener); // rawEmitters.add(rawEmitter); cont = { listeners: listener, rawEmitters: rawEmitter, options, watcher: fs__default['default'].watchFile(fullPath, options, (curr, prev) => { foreach(cont.rawEmitters, (rawEmitter) => { rawEmitter(EV_CHANGE, fullPath, {curr, prev}); }); const currmtime = curr.mtimeMs; if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { foreach(cont.listeners, (listener) => listener(path, curr)); } }) }; FsWatchFileInstances.set(fullPath, cont); } // const index = cont.listeners.indexOf(listener); // Removes this instance's listeners and closes the underlying fs_watchFile // instance if there are no more listeners left. return () => { delFromSet(cont, KEY_LISTENERS, listener); delFromSet(cont, KEY_RAW, rawEmitter); if (isEmptySet(cont.listeners)) { FsWatchFileInstances.delete(fullPath); fs__default['default'].unwatchFile(fullPath); cont.options = cont.watcher = undefined; Object.freeze(cont); } }; }; /** * @mixin */ class NodeFsHandler { /** * @param {import("../index").FSWatcher} fsW */ constructor(fsW) { this.fsw = fsW; this._boundHandleError = (error) => fsW._handleError(error); } /** * Watch file for changes with fs_watchFile or fs_watch. * @param {String} path to file or dir * @param {Function} listener on fs change * @returns {Function} closer for the watcher instance */ _watchWithNodeFs(path, listener) { const opts = this.fsw.options; const directory = path__default['default'].dirname(path); const basename = path__default['default'].basename(path); const parent = this.fsw._getWatchedDir(directory); parent.add(basename); const absolutePath = path__default['default'].resolve(path); const options = {persistent: opts.persistent}; if (!listener) listener = EMPTY_FN; let closer; if (opts.usePolling) { options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? opts.binaryInterval : opts.interval; closer = setFsWatchFileListener(path, absolutePath, options, { listener, rawEmitter: this.fsw._emitRaw }); } else { closer = setFsWatchListener(path, absolutePath, options, { listener, errHandler: this._boundHandleError, rawEmitter: this.fsw._emitRaw }); } return closer; } /** * Watch a file and emit add event if warranted. * @param {Path} file Path * @param {fs.Stats} stats result of fs_stat * @param {Boolean} initialAdd was the file added at watch instantiation? * @returns {Function} closer for the watcher instance */ _handleFile(file, stats, initialAdd) { if (this.fsw.closed) { return; } const dirname = path__default['default'].dirname(file); const basename = path__default['default'].basename(file); const parent = this.fsw._getWatchedDir(dirname); // stats is always present let prevStats = stats; // if the file is already being watched, do nothing if (parent.has(basename)) return; const listener = async (path, newStats) => { if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return; if (!newStats || newStats.mtimeMs === 0) { try { const newStats = await stat$3(file); if (this.fsw.closed) return; // Check that change event was not fired because of changed only accessTime. const at = newStats.atimeMs; const mt = newStats.mtimeMs; if (!at || at <= mt || mt !== prevStats.mtimeMs) { this.fsw._emit(EV_CHANGE, file, newStats); } if (isLinux && prevStats.ino !== newStats.ino) { this.fsw._closeFile(path); prevStats = newStats; this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener)); } else { prevStats = newStats; } } catch (error) { // Fix issues where mtime is null but file is still present this.fsw._remove(dirname, basename); } // add is about to be emitted if file not already tracked in parent } else if (parent.has(basename)) { // Check that change event was not fired because of changed only accessTime. const at = newStats.atimeMs; const mt = newStats.mtimeMs; if (!at || at <= mt || mt !== prevStats.mtimeMs) { this.fsw._emit(EV_CHANGE, file, newStats); } prevStats = newStats; } }; // kick off the watcher const closer = this._watchWithNodeFs(file, listener); // emit an add event if we're supposed to if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { if (!this.fsw._throttle(EV_ADD, file, 0)) return; this.fsw._emit(EV_ADD, file, stats); } return closer; } /** * Handle symlinks encountered while reading a dir. * @param {Object} entry returned by readdirp * @param {String} directory path of dir being read * @param {String} path of this item * @param {String} item basename of this item * @returns {Promise} true if no more processing is needed for this entry. */ async _handleSymlink(entry, directory, path, item) { if (this.fsw.closed) { return; } const full = entry.fullPath; const dir = this.fsw._getWatchedDir(directory); if (!this.fsw.options.followSymlinks) { // watch symlink directly (don't follow) and detect changes this.fsw._incrReadyCount(); const linkPath = await fsrealpath(path); if (this.fsw.closed) return; if (dir.has(item)) { if (this.fsw._symlinkPaths.get(full) !== linkPath) { this.fsw._symlinkPaths.set(full, linkPath); this.fsw._emit(EV_CHANGE, path, entry.stats); } } else { dir.add(item); this.fsw._symlinkPaths.set(full, linkPath); this.fsw._emit(EV_ADD, path, entry.stats); } this.fsw._emitReady(); return true; } // don't follow the same symlink more than once if (this.fsw._symlinkPaths.has(full)) { return true; } this.fsw._symlinkPaths.set(full, true); } _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { // Normalize the directory name on Windows directory = path__default['default'].join(directory, EMPTY_STR); if (!wh.hasGlob) { throttler = this.fsw._throttle('readdir', directory, 1000); if (!throttler) return; } const previous = this.fsw._getWatchedDir(wh.path); const current = new Set(); let stream = this.fsw._readdirp(directory, { fileFilter: entry => wh.filterPath(entry), directoryFilter: entry => wh.filterDir(entry), depth: 0 }).on(STR_DATA, async (entry) => { if (this.fsw.closed) { stream = undefined; return; } const item = entry.path; let path = path__default['default'].join(directory, item); current.add(item); if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) { return; } if (this.fsw.closed) { stream = undefined; return; } // Files that present in current directory snapshot // but absent in previous are added to watch list and // emit `add` event. if (item === target || !target && !previous.has(item)) { this.fsw._incrReadyCount(); // ensure relativeness of path is preserved in case of watcher reuse path = path__default['default'].join(dir, path__default['default'].relative(dir, path)); this._addToNodeFs(path, initialAdd, wh, depth + 1); } }).on(EV_ERROR, this._boundHandleError); return new Promise(resolve => stream.once(STR_END, () => { if (this.fsw.closed) { stream = undefined; return; } const wasThrottled = throttler ? throttler.clear() : false; resolve(); // Files that absent in current directory snapshot // but present in previous emit `remove` event // and are removed from @watched[directory]. previous.getChildren().filter((item) => { return item !== directory && !current.has(item) && // in case of intersecting globs; // a path may have been filtered out of this readdir, but // shouldn't be removed because it matches a different glob (!wh.hasGlob || wh.filterPath({ fullPath: path__default['default'].resolve(directory, item) })); }).forEach((item) => { this.fsw._remove(directory, item); }); stream = undefined; // one more time for any missed in case changes came in extremely quickly if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler); }) ); } /** * Read directory to add / remove files from `@watched` list and re-read it on change. * @param {String} dir fs path * @param {fs.Stats} stats * @param {Boolean} initialAdd * @param {Number} depth relative to user-supplied path * @param {String} target child path targeted for watch * @param {Object} wh Common watch helpers for this path * @param {String} realpath * @returns {Promise} closer for the watcher instance. */ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) { const parentDir = this.fsw._getWatchedDir(path__default['default'].dirname(dir)); const tracked = parentDir.has(path__default['default'].basename(dir)); if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats); } // ensure dir is tracked (harmless if redundant) parentDir.add(path__default['default'].basename(dir)); this.fsw._getWatchedDir(dir); let throttler; let closer; const oDepth = this.fsw.options.depth; if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) { if (!target) { await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); if (this.fsw.closed) return; } closer = this._watchWithNodeFs(dir, (dirPath, stats) => { // if current directory is removed, do nothing if (stats && stats.mtimeMs === 0) return; this._handleRead(dirPath, false, wh, target, dir, depth, throttler); }); } return closer; } /** * Handle added file, directory, or glob pattern. * Delegates call to _handleFile / _handleDir after checks. * @param {String} path to file or ir * @param {Boolean} initialAdd was the file added at watch instantiation? * @param {Object} priorWh depth relative to user-supplied path * @param {Number} depth Child path actually targeted for watch * @param {String=} target Child path actually targeted for watch * @returns {Promise} */ async _addToNodeFs(path, initialAdd, priorWh, depth, target) { const ready = this.fsw._emitReady; if (this.fsw._isIgnored(path) || this.fsw.closed) { ready(); return false; } const wh = this.fsw._getWatchHelpers(path, depth); if (!wh.hasGlob && priorWh) { wh.hasGlob = priorWh.hasGlob; wh.globFilter = priorWh.globFilter; wh.filterPath = entry => priorWh.filterPath(entry); wh.filterDir = entry => priorWh.filterDir(entry); } // evaluate what is at the path we're being asked to watch try { const stats = await statMethods[wh.statMethod](wh.watchPath); if (this.fsw.closed) return; if (this.fsw._isIgnored(wh.watchPath, stats)) { ready(); return false; } const follow = this.fsw.options.followSymlinks && !path.includes(STAR$1) && !path.includes(BRACE_START); let closer; if (stats.isDirectory()) { const targetPath = follow ? await fsrealpath(path) : path; if (this.fsw.closed) return; closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); if (this.fsw.closed) return; // preserve this symlink's target path if (path !== targetPath && targetPath !== undefined) { this.fsw._symlinkPaths.set(targetPath, true); } } else if (stats.isSymbolicLink()) { const targetPath = follow ? await fsrealpath(path) : path; if (this.fsw.closed) return; const parent = path__default['default'].dirname(wh.watchPath); this.fsw._getWatchedDir(parent).add(wh.watchPath); this.fsw._emit(EV_ADD, wh.watchPath, stats); closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath); if (this.fsw.closed) return; // preserve this symlink's target path if (targetPath !== undefined) { this.fsw._symlinkPaths.set(path__default['default'].resolve(path), targetPath); } } else { closer = this._handleFile(wh.watchPath, stats, initialAdd); } ready(); this.fsw._addPathCloser(path, closer); return false; } catch (error) { if (this.fsw._handleError(error)) { ready(); return path; } } } } var nodefsHandler = NodeFsHandler; const { promisify: promisify$2 } = util__default['default']; let fsevents; try { fsevents = undefined; } catch (error) { if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error); } if (fsevents) { // TODO: real check const mtch = process.version.match(/v(\d+)\.(\d+)/); if (mtch && mtch[1] && mtch[2]) { const maj = Number.parseInt(mtch[1], 10); const min = Number.parseInt(mtch[2], 10); if (maj === 8 && min < 16) { fsevents = undefined; } } } const { EV_ADD: EV_ADD$1, EV_CHANGE: EV_CHANGE$1, EV_ADD_DIR: EV_ADD_DIR$1, EV_UNLINK, EV_ERROR: EV_ERROR$1, STR_DATA: STR_DATA$1, STR_END: STR_END$1, FSEVENT_CREATED, FSEVENT_MODIFIED, FSEVENT_DELETED, FSEVENT_MOVED, // FSEVENT_CLONED, FSEVENT_UNKNOWN, FSEVENT_TYPE_FILE, FSEVENT_TYPE_DIRECTORY, FSEVENT_TYPE_SYMLINK, ROOT_GLOBSTAR, DIR_SUFFIX, DOT_SLASH, FUNCTION_TYPE, EMPTY_FN: EMPTY_FN$1, IDENTITY_FN } = constants$2; const Depth = (value) => isNaN(value) ? {} : {depth: value}; const stat$4 = promisify$2(fs__default['default'].stat); const lstat$2 = promisify$2(fs__default['default'].lstat); const realpath$3 = promisify$2(fs__default['default'].realpath); const statMethods$1 = { stat: stat$4, lstat: lstat$2 }; /** * @typedef {String} Path */ /** * @typedef {Object} FsEventsWatchContainer * @property {Set} listeners * @property {Function} rawEmitter * @property {{stop: Function}} watcher */ // fsevents instance helper functions /** * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances) * @type {Map} */ const FSEventsWatchers = new Map(); // Threshold of duplicate path prefixes at which to start // consolidating going forward const consolidateThreshhold = 10; const wrongEventFlags = new Set([ 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912 ]); /** * Instantiates the fsevents interface * @param {Path} path path to be watched * @param {Function} callback called when fsevents is bound and ready * @returns {{stop: Function}} new fsevents instance */ const createFSEventsInstance = (path, callback) => { const stop = fsevents.watch(path, callback); return {stop}; }; /** * Instantiates the fsevents interface or binds listeners to an existing one covering * the same file tree. * @param {Path} path - to be watched * @param {Path} realPath - real path for symlinks * @param {Function} listener - called when fsevents emits events * @param {Function} rawEmitter - passes data to listeners of the 'raw' event * @returns {Function} closer */ function setFSEventsListener(path, realPath, listener, rawEmitter) { let watchPath = path__default['default'].extname(path) ? path__default['default'].dirname(path) : path; const parentPath = path__default['default'].dirname(watchPath); let cont = FSEventsWatchers.get(watchPath); // If we've accumulated a substantial number of paths that // could have been consolidated by watching one directory // above the current one, create a watcher on the parent // path instead, so that we do consolidate going forward. if (couldConsolidate(parentPath)) { watchPath = parentPath; } const resolvedPath = path__default['default'].resolve(path); const hasSymlink = resolvedPath !== realPath; const filteredListener = (fullPath, flags, info) => { if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath); if ( fullPath === resolvedPath || !fullPath.indexOf(resolvedPath + path__default['default'].sep) ) listener(fullPath, flags, info); }; // check if there is already a watcher on a parent path // modifies `watchPath` to the parent path when it finds a match let watchedParent = false; for (const watchedPath of FSEventsWatchers.keys()) { if (realPath.indexOf(path__default['default'].resolve(watchedPath) + path__default['default'].sep) === 0) { watchPath = watchedPath; cont = FSEventsWatchers.get(watchPath); watchedParent = true; break; } } if (cont || watchedParent) { cont.listeners.add(filteredListener); } else { cont = { listeners: new Set([filteredListener]), rawEmitter, watcher: createFSEventsInstance(watchPath, (fullPath, flags) => { if (!cont.listeners.size) return; const info = fsevents.getInfo(fullPath, flags); cont.listeners.forEach(list => { list(fullPath, flags, info); }); cont.rawEmitter(info.event, fullPath, info); }) }; FSEventsWatchers.set(watchPath, cont); } // removes this instance's listeners and closes the underlying fsevents // instance if there are no more listeners left return () => { const lst = cont.listeners; lst.delete(filteredListener); if (!lst.size) { FSEventsWatchers.delete(watchPath); if (cont.watcher) return cont.watcher.stop().then(() => { cont.rawEmitter = cont.watcher = undefined; Object.freeze(cont); }); } }; } // Decide whether or not we should start a new higher-level // parent watcher const couldConsolidate = (path) => { let count = 0; for (const watchPath of FSEventsWatchers.keys()) { if (watchPath.indexOf(path) === 0) { count++; if (count >= consolidateThreshhold) { return true; } } } return false; }; // returns boolean indicating whether fsevents can be used const canUse = () => fsevents && FSEventsWatchers.size < 128; // determines subdirectory traversal levels from root to path const calcDepth = (path, root) => { let i = 0; while (!path.indexOf(root) && (path = path__default['default'].dirname(path)) !== root) i++; return i; }; // returns boolean indicating whether the fsevents' event info has the same type // as the one returned by fs.stat const sameTypes = (info, stats) => ( info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || info.type === FSEVENT_TYPE_FILE && stats.isFile() ); /** * @mixin */ class FsEventsHandler { /** * @param {import('../index').FSWatcher} fsw */ constructor(fsw) { this.fsw = fsw; } checkIgnored(path, stats) { const ipaths = this.fsw._ignoredPaths; if (this.fsw._isIgnored(path, stats)) { ipaths.add(path); if (stats && stats.isDirectory()) { ipaths.add(path + ROOT_GLOBSTAR); } return true; } ipaths.delete(path); ipaths.delete(path + ROOT_GLOBSTAR); } addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) { const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1; this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts); } async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) { try { const stats = await stat$4(path); if (this.fsw.closed) return; if (sameTypes(info, stats)) { this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); } else { this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); } } catch (error) { if (error.code === 'EACCES') { this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); } else { this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); } } } handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) { if (this.fsw.closed || this.checkIgnored(path)) return; if (event === EV_UNLINK) { const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY; // suppress unlink events on never before seen files if (isDirectory || watchedDir.has(item)) { this.fsw._remove(parent, item, isDirectory); } } else { if (event === EV_ADD$1) { // track new directories if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path); if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) { // push symlinks back to the top of the stack to get handled const curDepth = opts.depth === undefined ? undefined : calcDepth(fullPath, realPath) + 1; return this._addToFsEvents(path, false, true, curDepth); } // track new paths // (other than symlinks being followed, which will be tracked soon) this.fsw._getWatchedDir(parent).add(item); } /** * @type {'add'|'addDir'|'unlink'|'unlinkDir'} */ const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event; this.fsw._emit(eventName, path); if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true); } } /** * Handle symlinks encountered during directory scan * @param {String} watchPath - file/dir path to be watched with fsevents * @param {String} realPath - real path (in case of symlinks) * @param {Function} transform - path transformer * @param {Function} globFilter - path filter in case a glob pattern was provided * @returns {Function} closer for the watcher instance */ _watchWithFsEvents(watchPath, realPath, transform, globFilter) { if (this.fsw.closed) return; if (this.fsw._isIgnored(watchPath)) return; const opts = this.fsw.options; const watchCallback = async (fullPath, flags, info) => { if (this.fsw.closed) return; if ( opts.depth !== undefined && calcDepth(fullPath, realPath) > opts.depth ) return; const path = transform(path__default['default'].join( watchPath, path__default['default'].relative(watchPath, fullPath) )); if (globFilter && !globFilter(path)) return; // ensure directories are tracked const parent = path__default['default'].dirname(path); const item = path__default['default'].basename(path); const watchedDir = this.fsw._getWatchedDir( info.type === FSEVENT_TYPE_DIRECTORY ? path : parent ); // correct for wrong events emitted if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) { if (typeof opts.ignored === FUNCTION_TYPE) { let stats; try { stats = await stat$4(path); } catch (error) {} if (this.fsw.closed) return; if (this.checkIgnored(path, stats)) return; if (sameTypes(info, stats)) { this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); } else { this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); } } else { this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); } } else { switch (info.event) { case FSEVENT_CREATED: case FSEVENT_MODIFIED: return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); case FSEVENT_DELETED: case FSEVENT_MOVED: return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); } } }; const closer = setFSEventsListener( watchPath, realPath, watchCallback, this.fsw._emitRaw ); this.fsw._emitReady(); return closer; } /** * Handle symlinks encountered during directory scan * @param {String} linkPath path to symlink * @param {String} fullPath absolute path to the symlink * @param {Function} transform pre-existing path transformer * @param {Number} curDepth level of subdirectories traversed to where symlink is * @returns {Promise} */ async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) { // don't follow the same symlink more than once if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return; this.fsw._symlinkPaths.set(fullPath, true); this.fsw._incrReadyCount(); try { const linkTarget = await realpath$3(linkPath); if (this.fsw.closed) return; if (this.fsw._isIgnored(linkTarget)) { return this.fsw._emitReady(); } this.fsw._incrReadyCount(); // add the linkTarget for watching with a wrapper for transform // that causes emitted paths to incorporate the link's path this._addToFsEvents(linkTarget || linkPath, (path) => { let aliasedPath = linkPath; if (linkTarget && linkTarget !== DOT_SLASH) { aliasedPath = path.replace(linkTarget, linkPath); } else if (path !== DOT_SLASH) { aliasedPath = path__default['default'].join(linkPath, path); } return transform(aliasedPath); }, false, curDepth); } catch(error) { if (this.fsw._handleError(error)) { return this.fsw._emitReady(); } } } /** * * @param {Path} newPath * @param {fs.Stats} stats */ emitAdd(newPath, stats, processPath, opts, forceAdd) { const pp = processPath(newPath); const isDir = stats.isDirectory(); const dirObj = this.fsw._getWatchedDir(path__default['default'].dirname(pp)); const base = path__default['default'].basename(pp); // ensure empty dirs get tracked if (isDir) this.fsw._getWatchedDir(pp); if (dirObj.has(base)) return; dirObj.add(base); if (!opts.ignoreInitial || forceAdd === true) { this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats); } } initWatch(realPath, path, wh, processPath) { if (this.fsw.closed) return; const closer = this._watchWithFsEvents( wh.watchPath, path__default['default'].resolve(realPath || wh.watchPath), processPath, wh.globFilter ); this.fsw._addPathCloser(path, closer); } /** * Handle added path with fsevents * @param {String} path file/dir path or glob pattern * @param {Function|Boolean=} transform converts working path to what the user expects * @param {Boolean=} forceAdd ensure add is emitted * @param {Number=} priorDepth Level of subdirectories already traversed. * @returns {Promise} */ async _addToFsEvents(path, transform, forceAdd, priorDepth) { if (this.fsw.closed) { return; } const opts = this.fsw.options; const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN; const wh = this.fsw._getWatchHelpers(path); // evaluate what is at the path we're being asked to watch try { const stats = await statMethods$1[wh.statMethod](wh.watchPath); if (this.fsw.closed) return; if (this.fsw._isIgnored(wh.watchPath, stats)) { throw null; } if (stats.isDirectory()) { // emit addDir unless this is a glob parent if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd); // don't recurse further if it would exceed depth setting if (priorDepth && priorDepth > opts.depth) return; // scan the contents of the dir this.fsw._readdirp(wh.watchPath, { fileFilter: entry => wh.filterPath(entry), directoryFilter: entry => wh.filterDir(entry), ...Depth(opts.depth - (priorDepth || 0)) }).on(STR_DATA$1, (entry) => { // need to check filterPath on dirs b/c filterDir is less restrictive if (this.fsw.closed) { return; } if (entry.stats.isDirectory() && !wh.filterPath(entry)) return; const joinedPath = path__default['default'].join(wh.watchPath, entry.path); const {fullPath} = entry; if (wh.followSymlinks && entry.stats.isSymbolicLink()) { // preserve the current depth here since it can't be derived from // real paths past the symlink const curDepth = opts.depth === undefined ? undefined : calcDepth(joinedPath, path__default['default'].resolve(wh.watchPath)) + 1; this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth); } else { this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd); } }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => { this.fsw._emitReady(); }); } else { this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd); this.fsw._emitReady(); } } catch (error) { if (!error || this.fsw._handleError(error)) { // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__- this.fsw._emitReady(); this.fsw._emitReady(); } } if (opts.persistent && forceAdd !== true) { if (typeof transform === FUNCTION_TYPE) { // realpath has already been resolved this.initWatch(undefined, path, wh, processPath); } else { let realPath; try { realPath = await realpath$3(wh.watchPath); } catch (e) {} this.initWatch(realPath, path, wh, processPath); } } } } var fseventsHandler = FsEventsHandler; var canUse_1 = canUse; fseventsHandler.canUse = canUse_1; const { EventEmitter } = events__default['default']; const { promisify: promisify$3 } = util__default['default']; const anymatch = anymatch_1.default; const { EV_ALL, EV_READY, EV_ADD: EV_ADD$2, EV_CHANGE: EV_CHANGE$2, EV_UNLINK: EV_UNLINK$1, EV_ADD_DIR: EV_ADD_DIR$2, EV_UNLINK_DIR, EV_RAW, EV_ERROR: EV_ERROR$2, STR_CLOSE, STR_END: STR_END$2, BACK_SLASH_RE, DOUBLE_SLASH_RE, SLASH_OR_BACK_SLASH_RE, DOT_RE, REPLACER_RE, SLASH: SLASH$1, SLASH_SLASH, BRACE_START: BRACE_START$1, BANG: BANG$1, ONE_DOT, TWO_DOTS, GLOBSTAR: GLOBSTAR$1, SLASH_GLOBSTAR, ANYMATCH_OPTS, STRING_TYPE, FUNCTION_TYPE: FUNCTION_TYPE$1, EMPTY_STR: EMPTY_STR$1, EMPTY_FN: EMPTY_FN$2, isWindows: isWindows$2, isMacos } = constants$2; const stat$5 = promisify$3(fs__default['default'].stat); const readdir$2 = promisify$3(fs__default['default'].readdir); /** * @typedef {String} Path * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType */ /** * * @typedef {Object} WatchHelpers * @property {Boolean} followSymlinks * @property {'stat'|'lstat'} statMethod * @property {Path} path * @property {Path} watchPath * @property {Function} entryPath * @property {Boolean} hasGlob * @property {Object} globFilter * @property {Function} filterPath * @property {Function} filterDir */ const arrify = (value = []) => Array.isArray(value) ? value : [value]; const flatten = (list, result = []) => { list.forEach(item => { if (Array.isArray(item)) { flatten(item, result); } else { result.push(item); } }); return result; }; const unifyPaths = (paths_) => { /** * @type {Array} */ const paths = flatten(arrify(paths_)); if (!paths.every(p => typeof p === STRING_TYPE)) { throw new TypeError(`Non-string provided as watch path: ${paths}`); } return paths.map(normalizePathToUnix); }; // If SLASH_SLASH occurs at the beginning of path, it is not replaced // because "//StoragePC/DrivePool/Movies" is a valid network path const toUnix = (string) => { let str = string.replace(BACK_SLASH_RE, SLASH$1); let prepend = false; if (str.startsWith(SLASH_SLASH)) { prepend = true; } while (str.match(DOUBLE_SLASH_RE)) { str = str.replace(DOUBLE_SLASH_RE, SLASH$1); } if (prepend) { str = SLASH$1 + str; } return str; }; // Our version of upath.normalize // TODO: this is not equal to path-normalize module - investigate why const normalizePathToUnix = (path) => toUnix(path__default['default'].normalize(toUnix(path))); const normalizeIgnored = (cwd = EMPTY_STR$1) => (path) => { if (typeof path !== STRING_TYPE) return path; return normalizePathToUnix(path__default['default'].isAbsolute(path) ? path : path__default['default'].join(cwd, path)); }; const getAbsolutePath = (path, cwd) => { if (path__default['default'].isAbsolute(path)) { return path; } if (path.startsWith(BANG$1)) { return BANG$1 + path__default['default'].join(cwd, path.slice(1)); } return path__default['default'].join(cwd, path); }; const undef = (opts, key) => opts[key] === undefined; /** * Directory entry. * @property {Path} path * @property {Set} items */ class DirEntry { /** * @param {Path} dir * @param {Function} removeWatcher */ constructor(dir, removeWatcher) { this.path = dir; this._removeWatcher = removeWatcher; /** @type {Set} */ this.items = new Set(); } add(item) { const {items} = this; if (!items) return; if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item); } async remove(item) { const {items} = this; if (!items) return; items.delete(item); if (items.size > 0) return; const dir = this.path; try { await readdir$2(dir); } catch (err) { if (this._removeWatcher) { this._removeWatcher(path__default['default'].dirname(dir), path__default['default'].basename(dir)); } } } has(item) { const {items} = this; if (!items) return; return items.has(item); } /** * @returns {Array} */ getChildren() { const {items} = this; if (!items) return; return [...items.values()]; } dispose() { this.items.clear(); delete this.path; delete this._removeWatcher; delete this.items; Object.freeze(this); } } const STAT_METHOD_F = 'stat'; const STAT_METHOD_L = 'lstat'; class WatchHelper { constructor(path, watchPath, follow, fsw) { this.fsw = fsw; this.path = path = path.replace(REPLACER_RE, EMPTY_STR$1); this.watchPath = watchPath; this.fullWatchPath = path__default['default'].resolve(watchPath); this.hasGlob = watchPath !== path; /** @type {object|boolean} */ if (path === EMPTY_STR$1) this.hasGlob = false; this.globSymlink = this.hasGlob && follow ? undefined : false; this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false; this.dirParts = this.getDirParts(path); this.dirParts.forEach((parts) => { if (parts.length > 1) parts.pop(); }); this.followSymlinks = follow; this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; } checkGlobSymlink(entry) { // only need to resolve once // first entry should always have entry.parentDir === EMPTY_STR if (this.globSymlink === undefined) { this.globSymlink = entry.fullParentDir === this.fullWatchPath ? false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath}; } if (this.globSymlink) { return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath); } return entry.fullPath; } entryPath(entry) { return path__default['default'].join(this.watchPath, path__default['default'].relative(this.watchPath, this.checkGlobSymlink(entry)) ); } filterPath(entry) { const {stats} = entry; if (stats && stats.isSymbolicLink()) return this.filterDir(entry); const resolvedPath = this.entryPath(entry); const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE$1 ? this.globFilter(resolvedPath) : true; return matchesGlob && this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats); } getDirParts(path) { if (!this.hasGlob) return []; const parts = []; const expandedPath = path.includes(BRACE_START$1) ? braces_1.expand(path) : [path]; expandedPath.forEach((path) => { parts.push(path__default['default'].relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE)); }); return parts; } filterDir(entry) { if (this.hasGlob) { const entryParts = this.getDirParts(this.checkGlobSymlink(entry)); let globstar = false; this.unmatchedGlob = !this.dirParts.some((parts) => { return parts.every((part, i) => { if (part === GLOBSTAR$1) globstar = true; return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS); }); }); } return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats); } } /** * Watches files & directories for changes. Emitted events: * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` * * new FSWatcher() * .add(directories) * .on('add', path => log('File', path, 'was added')) */ class FSWatcher extends EventEmitter { // Not indenting methods for history sake; for now. constructor(_opts) { super(); const opts = {}; if (_opts) Object.assign(opts, _opts); // for frozen objects /** @type {Map} */ this._watched = new Map(); /** @type {Map} */ this._closers = new Map(); /** @type {Set} */ this._ignoredPaths = new Set(); /** @type {Map} */ this._throttled = new Map(); /** @type {Map} */ this._symlinkPaths = new Map(); this._streams = new Set(); this.closed = false; // Set up default options. if (undef(opts, 'persistent')) opts.persistent = true; if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false; if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false; if (undef(opts, 'interval')) opts.interval = 100; if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300; if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false; opts.enableBinaryInterval = opts.binaryInterval !== opts.interval; // Enable fsevents on OS X when polling isn't explicitly enabled. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling; // If we can't use fsevents, ensure the options reflect it's disabled. const canUseFsEvents = fseventsHandler.canUse(); if (!canUseFsEvents) opts.useFsEvents = false; // Use polling on Mac if not using fsevents. // Other platforms use non-polling fs_watch. if (undef(opts, 'usePolling') && !opts.useFsEvents) { opts.usePolling = isMacos; } // Global override (useful for end-developers that need to force polling for all // instances of chokidar, regardless of usage/dependency depth) const envPoll = process.env.CHOKIDAR_USEPOLLING; if (envPoll !== undefined) { const envLower = envPoll.toLowerCase(); if (envLower === 'false' || envLower === '0') { opts.usePolling = false; } else if (envLower === 'true' || envLower === '1') { opts.usePolling = true; } else { opts.usePolling = !!envLower; } } const envInterval = process.env.CHOKIDAR_INTERVAL; if (envInterval) { opts.interval = Number.parseInt(envInterval, 10); } // Editor atomic write normalization enabled by default with fs.watch if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents; if (opts.atomic) this._pendingUnlinks = new Map(); if (undef(opts, 'followSymlinks')) opts.followSymlinks = true; if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false; if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {}; const awf = opts.awaitWriteFinish; if (awf) { if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000; if (!awf.pollInterval) awf.pollInterval = 100; this._pendingWrites = new Map(); } if (opts.ignored) opts.ignored = arrify(opts.ignored); let readyCalls = 0; this._emitReady = () => { readyCalls++; if (readyCalls >= this._readyCount) { this._emitReady = EMPTY_FN$2; this._readyEmitted = true; // use process.nextTick to allow time for listener to be bound process.nextTick(() => this.emit(EV_READY)); } }; this._emitRaw = (...args) => this.emit(EV_RAW, ...args); this._readyEmitted = false; this.options = opts; // Initialize with proper watcher. if (opts.useFsEvents) { this._fsEventsHandler = new fseventsHandler(this); } else { this._nodeFsHandler = new nodefsHandler(this); } // You’re frozen when your heart’s not open. Object.freeze(opts); } // Public methods /** * Adds paths to be watched on an existing FSWatcher instance * @param {Path|Array} paths_ * @param {String=} _origAdd private; for handling non-existent paths to be watched * @param {Boolean=} _internal private; indicates a non-user add * @returns {FSWatcher} for chaining */ add(paths_, _origAdd, _internal) { const {cwd, disableGlobbing} = this.options; this.closed = false; let paths = unifyPaths(paths_); if (cwd) { paths = paths.map((path) => { const absPath = getAbsolutePath(path, cwd); // Check `path` instead of `absPath` because the cwd portion can't be a glob if (disableGlobbing || !isGlob(path)) { return absPath; } return normalizePath(absPath); }); } // set aside negated glob strings paths = paths.filter((path) => { if (path.startsWith(BANG$1)) { this._ignoredPaths.add(path.slice(1)); return false; } // if a path is being added that was previously ignored, stop ignoring it this._ignoredPaths.delete(path); this._ignoredPaths.delete(path + SLASH_GLOBSTAR); // reset the cached userIgnored anymatch fn // to make ignoredPaths changes effective this._userIgnored = undefined; return true; }); if (this.options.useFsEvents && this._fsEventsHandler) { if (!this._readyCount) this._readyCount = paths.length; if (this.options.persistent) this._readyCount *= 2; paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path)); } else { if (!this._readyCount) this._readyCount = 0; this._readyCount += paths.length; Promise.all( paths.map(async path => { const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd); if (res) this._emitReady(); return res; }) ).then(results => { if (this.closed) return; results.filter(item => item).forEach(item => { this.add(path__default['default'].dirname(item), path__default['default'].basename(_origAdd || item)); }); }); } return this; } /** * Close watchers or start ignoring events from specified paths. * @param {Path|Array} paths_ - string or array of strings, file/directory paths and/or globs * @returns {FSWatcher} for chaining */ unwatch(paths_) { if (this.closed) return this; const paths = unifyPaths(paths_); const {cwd} = this.options; paths.forEach((path) => { // convert to absolute path unless relative path already matches if (!path__default['default'].isAbsolute(path) && !this._closers.has(path)) { if (cwd) path = path__default['default'].join(cwd, path); path = path__default['default'].resolve(path); } this._closePath(path); this._ignoredPaths.add(path); if (this._watched.has(path)) { this._ignoredPaths.add(path + SLASH_GLOBSTAR); } // reset the cached userIgnored anymatch fn // to make ignoredPaths changes effective this._userIgnored = undefined; }); return this; } /** * Close watchers and remove all listeners from watched paths. * @returns {Promise}. */ close() { if (this.closed) return this._closePromise; this.closed = true; // Memory management. this.removeAllListeners(); const closers = []; this._closers.forEach(closerList => closerList.forEach(closer => { const promise = closer(); if (promise instanceof Promise) closers.push(promise); })); this._streams.forEach(stream => stream.destroy()); this._userIgnored = undefined; this._readyCount = 0; this._readyEmitted = false; this._watched.forEach(dirent => dirent.dispose()); ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => { this[`_${key}`].clear(); }); this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve(); return this._closePromise; } /** * Expose list of watched paths * @returns {Object} for chaining */ getWatched() { const watchList = {}; this._watched.forEach((entry, dir) => { const key = this.options.cwd ? path__default['default'].relative(this.options.cwd, dir) : dir; watchList[key || ONE_DOT] = entry.getChildren().sort(); }); return watchList; } emitWithAll(event, args) { this.emit(...args); if (event !== EV_ERROR$2) this.emit(EV_ALL, ...args); } // Common helpers // -------------- /** * Normalize and emit events. * Calling _emit DOES NOT MEAN emit() would be called! * @param {EventName} event Type of event * @param {Path} path File or directory path * @param {*=} val1 arguments to be passed with event * @param {*=} val2 * @param {*=} val3 * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag */ async _emit(event, path, val1, val2, val3) { if (this.closed) return; const opts = this.options; if (isWindows$2) path = path__default['default'].normalize(path); if (opts.cwd) path = path__default['default'].relative(opts.cwd, path); /** @type Array */ const args = [event, path]; if (val3 !== undefined) args.push(val1, val2, val3); else if (val2 !== undefined) args.push(val1, val2); else if (val1 !== undefined) args.push(val1); const awf = opts.awaitWriteFinish; let pw; if (awf && (pw = this._pendingWrites.get(path))) { pw.lastChange = new Date(); return this; } if (opts.atomic) { if (event === EV_UNLINK$1) { this._pendingUnlinks.set(path, args); setTimeout(() => { this._pendingUnlinks.forEach((entry, path) => { this.emit(...entry); this.emit(EV_ALL, ...entry); this._pendingUnlinks.delete(path); }); }, typeof opts.atomic === 'number' ? opts.atomic : 100); return this; } if (event === EV_ADD$2 && this._pendingUnlinks.has(path)) { event = args[0] = EV_CHANGE$2; this._pendingUnlinks.delete(path); } } if (awf && (event === EV_ADD$2 || event === EV_CHANGE$2) && this._readyEmitted) { const awfEmit = (err, stats) => { if (err) { event = args[0] = EV_ERROR$2; args[1] = err; this.emitWithAll(event, args); } else if (stats) { // if stats doesn't exist the file must have been deleted if (args.length > 2) { args[2] = stats; } else { args.push(stats); } this.emitWithAll(event, args); } }; this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit); return this; } if (event === EV_CHANGE$2) { const isThrottled = !this._throttle(EV_CHANGE$2, path, 50); if (isThrottled) return this; } if (opts.alwaysStat && val1 === undefined && (event === EV_ADD$2 || event === EV_ADD_DIR$2 || event === EV_CHANGE$2) ) { const fullPath = opts.cwd ? path__default['default'].join(opts.cwd, path) : path; let stats; try { stats = await stat$5(fullPath); } catch (err) {} // Suppress event when fs_stat fails, to avoid sending undefined 'stat' if (!stats || this.closed) return; args.push(stats); } this.emitWithAll(event, args); return this; } /** * Common handler for errors * @param {Error} error * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag */ _handleError(error) { const code = error && error.code; if (error && code !== 'ENOENT' && code !== 'ENOTDIR' && (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES')) ) { this.emit(EV_ERROR$2, error); } return error || this.closed; } /** * Helper utility for throttling * @param {ThrottleType} actionType type being throttled * @param {Path} path being acted upon * @param {Number} timeout duration of time to suppress duplicate actions * @returns {Object|false} tracking object or false if action should be suppressed */ _throttle(actionType, path, timeout) { if (!this._throttled.has(actionType)) { this._throttled.set(actionType, new Map()); } /** @type {Map} */ const action = this._throttled.get(actionType); /** @type {Object} */ const actionPath = action.get(path); if (actionPath) { actionPath.count++; return false; } let timeoutObject; const clear = () => { const item = action.get(path); const count = item ? item.count : 0; action.delete(path); clearTimeout(timeoutObject); if (item) clearTimeout(item.timeoutObject); return count; }; timeoutObject = setTimeout(clear, timeout); const thr = {timeoutObject, clear, count: 0}; action.set(path, thr); return thr; } _incrReadyCount() { return this._readyCount++; } /** * Awaits write operation to finish. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. * @param {Path} path being acted upon * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished * @param {EventName} event * @param {Function} awfEmit Callback to be called when ready for event to be emitted. */ _awaitWriteFinish(path, threshold, event, awfEmit) { let timeoutHandler; let fullPath = path; if (this.options.cwd && !path__default['default'].isAbsolute(path)) { fullPath = path__default['default'].join(this.options.cwd, path); } const now = new Date(); const awaitWriteFinish = (prevStat) => { fs__default['default'].stat(fullPath, (err, curStat) => { if (err || !this._pendingWrites.has(path)) { if (err && err.code !== 'ENOENT') awfEmit(err); return; } const now = Number(new Date()); if (prevStat && curStat.size !== prevStat.size) { this._pendingWrites.get(path).lastChange = now; } const pw = this._pendingWrites.get(path); const df = now - pw.lastChange; if (df >= threshold) { this._pendingWrites.delete(path); awfEmit(undefined, curStat); } else { timeoutHandler = setTimeout( awaitWriteFinish, this.options.awaitWriteFinish.pollInterval, curStat ); } }); }; if (!this._pendingWrites.has(path)) { this._pendingWrites.set(path, { lastChange: now, cancelWait: () => { this._pendingWrites.delete(path); clearTimeout(timeoutHandler); return event; } }); timeoutHandler = setTimeout( awaitWriteFinish, this.options.awaitWriteFinish.pollInterval ); } } _getGlobIgnored() { return [...this._ignoredPaths.values()]; } /** * Determines whether user has asked to ignore this path. * @param {Path} path filepath or dir * @param {fs.Stats=} stats result of fs.stat * @returns {Boolean} */ _isIgnored(path, stats) { if (this.options.atomic && DOT_RE.test(path)) return true; if (!this._userIgnored) { const {cwd} = this.options; const ign = this.options.ignored; const ignored = ign && ign.map(normalizeIgnored(cwd)); const paths = arrify(ignored) .filter((path) => typeof path === STRING_TYPE && !isGlob(path)) .map((path) => path + SLASH_GLOBSTAR); const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths); this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS); } return this._userIgnored([path, stats]); } _isntIgnored(path, stat) { return !this._isIgnored(path, stat); } /** * Provides a set of common helpers and properties relating to symlink and glob handling. * @param {Path} path file, directory, or glob pattern being watched * @param {Number=} depth at any depth > 0, this isn't a glob * @returns {WatchHelper} object containing helpers for this path */ _getWatchHelpers(path, depth) { const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path); const follow = this.options.followSymlinks; return new WatchHelper(path, watchPath, follow, this); } // Directory helpers // ----------------- /** * Provides directory tracking objects * @param {String} directory path of the directory * @returns {DirEntry} the directory's tracking object */ _getWatchedDir(directory) { if (!this._boundRemove) this._boundRemove = this._remove.bind(this); const dir = path__default['default'].resolve(directory); if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove)); return this._watched.get(dir); } // File helpers // ------------ /** * Check for read permissions. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405 * @param {fs.Stats} stats - object, result of fs_stat * @returns {Boolean} indicates whether the file can be read */ _hasReadPermissions(stats) { if (this.options.ignorePermissionErrors) return true; // stats.mode may be bigint const md = stats && Number.parseInt(stats.mode, 10); const st = md & 0o777; const it = Number.parseInt(st.toString(8)[0], 10); return Boolean(4 & it); } /** * Handles emitting unlink events for * files and directories, and via recursion, for * files and directories within directories that are unlinked * @param {String} directory within which the following item is located * @param {String} item base path of item/directory * @returns {void} */ _remove(directory, item, isDirectory) { // if what is being deleted is a directory, get that directory's paths // for recursive deleting and cleaning of watched object // if it is not a directory, nestedDirectoryChildren will be empty array const path = path__default['default'].join(directory, item); const fullPath = path__default['default'].resolve(path); isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath); // prevent duplicate handling in case of arriving here nearly simultaneously // via multiple paths (such as _handleFile and _handleDir) if (!this._throttle('remove', path, 100)) return; // if the only watched file is removed, watch for its return if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) { this.add(directory, item, true); } // This will create a new entry in the watched object in either case // so we got to do the directory check beforehand const wp = this._getWatchedDir(path); const nestedDirectoryChildren = wp.getChildren(); // Recursively remove children directories / files. nestedDirectoryChildren.forEach(nested => this._remove(path, nested)); // Check if item was on the watched list and remove it const parent = this._getWatchedDir(directory); const wasTracked = parent.has(item); parent.remove(item); // If we wait for this file to be fully written, cancel the wait. let relPath = path; if (this.options.cwd) relPath = path__default['default'].relative(this.options.cwd, path); if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { const event = this._pendingWrites.get(relPath).cancelWait(); if (event === EV_ADD$2) return; } // The Entry will either be a directory that just got removed // or a bogus entry to a file, in either case we have to remove it this._watched.delete(path); this._watched.delete(fullPath); const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK$1; if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path); // Avoid conflicts if we later create another file with the same name if (!this.options.useFsEvents) { this._closePath(path); } } /** * Closes all watchers for a path * @param {Path} path */ _closePath(path) { this._closeFile(path); const dir = path__default['default'].dirname(path); this._getWatchedDir(dir).remove(path__default['default'].basename(path)); } /** * Closes only file-specific watchers * @param {Path} path */ _closeFile(path) { const closers = this._closers.get(path); if (!closers) return; closers.forEach(closer => closer()); this._closers.delete(path); } /** * * @param {Path} path * @param {Function} closer */ _addPathCloser(path, closer) { if (!closer) return; let list = this._closers.get(path); if (!list) { list = []; this._closers.set(path, list); } list.push(closer); } _readdirp(root, opts) { if (this.closed) return; const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts}; let stream = readdirp_1(root, options); this._streams.add(stream); stream.once(STR_CLOSE, () => { stream = undefined; }); stream.once(STR_END$2, () => { if (stream) { this._streams.delete(stream); stream = undefined; } }); return stream; } } // Export FSWatcher class var FSWatcher_1 = FSWatcher; /** * Instantiates watcher with paths to be tracked. * @param {String|Array} paths file/directory paths and/or globs * @param {Object=} options chokidar opts * @returns an instance of FSWatcher for chaining. */ const watch = (paths, options) => { const watcher = new FSWatcher(options); watcher.add(paths); return watcher; }; var watch_1 = watch; var chokidar = { FSWatcher: FSWatcher_1, watch: watch_1 }; var textTable = function (rows_, opts) { if (!opts) opts = {}; var hsep = opts.hsep === undefined ? ' ' : opts.hsep; var align = opts.align || []; var stringLength = opts.stringLength || function (s) { return String(s).length; } ; var dotsizes = reduce(rows_, function (acc, row) { forEach(row, function (c, ix) { var n = dotindex(c); if (!acc[ix] || n > acc[ix]) acc[ix] = n; }); return acc; }, []); var rows = map$1(rows_, function (row) { return map$1(row, function (c_, ix) { var c = String(c_); if (align[ix] === '.') { var index = dotindex(c); var size = dotsizes[ix] + (/\./.test(c) ? 1 : 2) - (stringLength(c) - index) ; return c + Array(size).join(' '); } else return c; }); }); var sizes = reduce(rows, function (acc, row) { forEach(row, function (c, ix) { var n = stringLength(c); if (!acc[ix] || n > acc[ix]) acc[ix] = n; }); return acc; }, []); return map$1(rows, function (row) { return map$1(row, function (c, ix) { var n = (sizes[ix] - stringLength(c)) || 0; var s = Array(Math.max(n + 1, 1)).join(' '); if (align[ix] === 'r' || align[ix] === '.') { return s + c; } if (align[ix] === 'c') { return Array(Math.ceil(n / 2 + 1)).join(' ') + c + Array(Math.floor(n / 2 + 1)).join(' ') ; } return c + s; }).join(hsep).replace(/\s+$/, ''); }).join('\n'); }; function dotindex (c) { var m = /\.[^.]*$/.exec(c); return m ? m.index + 1 : c.length; } function reduce (xs, f, init) { if (xs.reduce) return xs.reduce(f, init); var i = 0; var acc = arguments.length >= 3 ? init : xs[i++]; for (; i < xs.length; i++) { f(acc, xs[i], i); } return acc; } function forEach (xs, f) { if (xs.forEach) return xs.forEach(f); for (var i = 0; i < xs.length; i++) { f.call(xs, xs[i], i); } } function map$1 (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f.call(xs, xs[i], i)); } return res; } const preserveCamelCase = string => { let isLastCharLower = false; let isLastCharUpper = false; let isLastLastCharUpper = false; for (let i = 0; i < string.length; i++) { const character = string[i]; if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) { string = string.slice(0, i) + '-' + string.slice(i); isLastCharLower = false; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = true; i++; } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) { string = string.slice(0, i - 1) + '-' + string.slice(i - 1); isLastLastCharUpper = isLastCharUpper; isLastCharUpper = false; isLastCharLower = true; } else { isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character; } } return string; }; const camelCase = (input, options) => { if (!(typeof input === 'string' || Array.isArray(input))) { throw new TypeError('Expected the input to be `string | string[]`'); } options = Object.assign({ pascalCase: false }, options); const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; if (Array.isArray(input)) { input = input.map(x => x.trim()) .filter(x => x.length) .join('-'); } else { input = input.trim(); } if (input.length === 0) { return ''; } if (input.length === 1) { return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); } const hasUpperCase = input !== input.toLowerCase(); if (hasUpperCase) { input = preserveCamelCase(input); } input = input .replace(/^[_.\- ]+/, '') .toLowerCase() .replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase()) .replace(/\d+(\w|$)/g, m => m.toUpperCase()); return postProcess(input); }; var camelcase = camelCase; // TODO: Remove this for the next major release var _default$4 = camelCase; camelcase.default = _default$4; var minimist = function (args, opts) { if (!opts) opts = {}; var flags = { bools : {}, strings : {}, unknownFn: null }; if (typeof opts['unknown'] === 'function') { flags.unknownFn = opts['unknown']; } if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { flags.allBools = true; } else { [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { flags.bools[key] = true; }); } var aliases = {}; Object.keys(opts.alias || {}).forEach(function (key) { aliases[key] = [].concat(opts.alias[key]); aliases[key].forEach(function (x) { aliases[x] = [key].concat(aliases[key].filter(function (y) { return x !== y; })); }); }); [].concat(opts.string).filter(Boolean).forEach(function (key) { flags.strings[key] = true; if (aliases[key]) { flags.strings[aliases[key]] = true; } }); var defaults = opts['default'] || {}; var argv = { _ : [] }; Object.keys(flags.bools).forEach(function (key) { setArg(key, defaults[key] === undefined ? false : defaults[key]); }); var notFlags = []; if (args.indexOf('--') !== -1) { notFlags = args.slice(args.indexOf('--')+1); args = args.slice(0, args.indexOf('--')); } function argDefined(key, arg) { return (flags.allBools && /^--[^=]+$/.test(arg)) || flags.strings[key] || flags.bools[key] || aliases[key]; } function setArg (key, val, arg) { if (arg && flags.unknownFn && !argDefined(key, arg)) { if (flags.unknownFn(arg) === false) return; } var value = !flags.strings[key] && isNumber$2(val) ? Number(val) : val ; setKey(argv, key.split('.'), value); (aliases[key] || []).forEach(function (x) { setKey(argv, x.split('.'), value); }); } function setKey (obj, keys, value) { var o = obj; for (var i = 0; i < keys.length-1; i++) { var key = keys[i]; if (key === '__proto__') return; if (o[key] === undefined) o[key] = {}; if (o[key] === Object.prototype || o[key] === Number.prototype || o[key] === String.prototype) o[key] = {}; if (o[key] === Array.prototype) o[key] = []; o = o[key]; } var key = keys[keys.length - 1]; if (key === '__proto__') return; if (o === Object.prototype || o === Number.prototype || o === String.prototype) o = {}; if (o === Array.prototype) o = []; if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { o[key] = value; } else if (Array.isArray(o[key])) { o[key].push(value); } else { o[key] = [ o[key], value ]; } } function aliasIsBoolean(key) { return aliases[key].some(function (x) { return flags.bools[x]; }); } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (/^--.+=/.test(arg)) { // Using [\s\S] instead of . because js doesn't support the // 'dotall' regex modifier. See: // http://stackoverflow.com/a/1068308/13216 var m = arg.match(/^--([^=]+)=([\s\S]*)$/); var key = m[1]; var value = m[2]; if (flags.bools[key]) { value = value !== 'false'; } setArg(key, value, arg); } else if (/^--no-.+/.test(arg)) { var key = arg.match(/^--no-(.+)/)[1]; setArg(key, false, arg); } else if (/^--.+/.test(arg)) { var key = arg.match(/^--(.+)/)[1]; var next = args[i + 1]; if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) { setArg(key, next, arg); i++; } else if (/^(true|false)$/.test(next)) { setArg(key, next === 'true', arg); i++; } else { setArg(key, flags.strings[key] ? '' : true, arg); } } else if (/^-[^-]+/.test(arg)) { var letters = arg.slice(1,-1).split(''); var broken = false; for (var j = 0; j < letters.length; j++) { var next = arg.slice(j+2); if (next === '-') { setArg(letters[j], next, arg); continue; } if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { setArg(letters[j], next.split('=')[1], arg); broken = true; break; } if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { setArg(letters[j], next, arg); broken = true; break; } if (letters[j+1] && letters[j+1].match(/\W/)) { setArg(letters[j], arg.slice(j+2), arg); broken = true; break; } else { setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); } } var key = arg.slice(-1)[0]; if (!broken && key !== '-') { if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) { setArg(key, args[i+1], arg); i++; } else if (args[i+1] && /^(true|false)$/.test(args[i+1])) { setArg(key, args[i+1] === 'true', arg); i++; } else { setArg(key, flags.strings[key] ? '' : true, arg); } } } else { if (!flags.unknownFn || flags.unknownFn(arg) !== false) { argv._.push( flags.strings['_'] || !isNumber$2(arg) ? arg : Number(arg) ); } if (opts.stopEarly) { argv._.push.apply(argv._, args.slice(i + 1)); break; } } } Object.keys(defaults).forEach(function (key) { if (!hasKey(argv, key.split('.'))) { setKey(argv, key.split('.'), defaults[key]); (aliases[key] || []).forEach(function (x) { setKey(argv, x.split('.'), defaults[key]); }); } }); if (opts['--']) { argv['--'] = new Array(); notFlags.forEach(function(key) { argv['--'].push(key); }); } else { notFlags.forEach(function(key) { argv._.push(key); }); } return argv; }; function hasKey (obj, keys) { var o = obj; keys.slice(0,-1).forEach(function (key) { o = (o[key] || {}); }); var key = keys[keys.length - 1]; return key in o; } function isNumber$2 (x) { if (typeof x === 'number') return true; if (/^0x[0-9a-f]+$/i.test(x)) return true; return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); } // This is a generated file. Do not edit. var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; var unicode = { Space_Separator: Space_Separator, ID_Start: ID_Start, ID_Continue: ID_Continue }; var util$1 = { isSpaceSeparator (c) { return typeof c === 'string' && unicode.Space_Separator.test(c) }, isIdStartChar (c) { return typeof c === 'string' && ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c === '$') || (c === '_') || unicode.ID_Start.test(c) ) }, isIdContinueChar (c) { return typeof c === 'string' && ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c === '$') || (c === '_') || (c === '\u200C') || (c === '\u200D') || unicode.ID_Continue.test(c) ) }, isDigit (c) { return typeof c === 'string' && /[0-9]/.test(c) }, isHexDigit (c) { return typeof c === 'string' && /[0-9A-Fa-f]/.test(c) }, }; let source$1; let parseState; let stack; let pos; let line; let column; let token; let key; let root; var parse$7 = function parse (text, reviver) { source$1 = String(text); parseState = 'start'; stack = []; pos = 0; line = 1; column = 0; token = undefined; key = undefined; root = undefined; do { token = lex(); // This code is unreachable. // if (!parseStates[parseState]) { // throw invalidParseState() // } parseStates[parseState](); } while (token.type !== 'eof') if (typeof reviver === 'function') { return internalize({'': root}, '', reviver) } return root }; function internalize (holder, name, reviver) { const value = holder[name]; if (value != null && typeof value === 'object') { for (const key in value) { const replacement = internalize(value, key, reviver); if (replacement === undefined) { delete value[key]; } else { value[key] = replacement; } } } return reviver.call(holder, name, value) } let lexState; let buffer; let doubleQuote; let sign; let c; function lex () { lexState = 'default'; buffer = ''; doubleQuote = false; sign = 1; for (;;) { c = peek(); // This code is unreachable. // if (!lexStates[lexState]) { // throw invalidLexState(lexState) // } const token = lexStates[lexState](); if (token) { return token } } } function peek () { if (source$1[pos]) { return String.fromCodePoint(source$1.codePointAt(pos)) } } function read$5 () { const c = peek(); if (c === '\n') { line++; column = 0; } else if (c) { column += c.length; } else { column++; } if (c) { pos += c.length; } return c } const lexStates = { default () { switch (c) { case '\t': case '\v': case '\f': case ' ': case '\u00A0': case '\uFEFF': case '\n': case '\r': case '\u2028': case '\u2029': read$5(); return case '/': read$5(); lexState = 'comment'; return case undefined: read$5(); return newToken('eof') } if (util$1.isSpaceSeparator(c)) { read$5(); return } // This code is unreachable. // if (!lexStates[parseState]) { // throw invalidLexState(parseState) // } return lexStates[parseState]() }, comment () { switch (c) { case '*': read$5(); lexState = 'multiLineComment'; return case '/': read$5(); lexState = 'singleLineComment'; return } throw invalidChar(read$5()) }, multiLineComment () { switch (c) { case '*': read$5(); lexState = 'multiLineCommentAsterisk'; return case undefined: throw invalidChar(read$5()) } read$5(); }, multiLineCommentAsterisk () { switch (c) { case '*': read$5(); return case '/': read$5(); lexState = 'default'; return case undefined: throw invalidChar(read$5()) } read$5(); lexState = 'multiLineComment'; }, singleLineComment () { switch (c) { case '\n': case '\r': case '\u2028': case '\u2029': read$5(); lexState = 'default'; return case undefined: read$5(); return newToken('eof') } read$5(); }, value () { switch (c) { case '{': case '[': return newToken('punctuator', read$5()) case 'n': read$5(); literal('ull'); return newToken('null', null) case 't': read$5(); literal('rue'); return newToken('boolean', true) case 'f': read$5(); literal('alse'); return newToken('boolean', false) case '-': case '+': if (read$5() === '-') { sign = -1; } lexState = 'sign'; return case '.': buffer = read$5(); lexState = 'decimalPointLeading'; return case '0': buffer = read$5(); lexState = 'zero'; return case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer = read$5(); lexState = 'decimalInteger'; return case 'I': read$5(); literal('nfinity'); return newToken('numeric', Infinity) case 'N': read$5(); literal('aN'); return newToken('numeric', NaN) case '"': case "'": doubleQuote = (read$5() === '"'); buffer = ''; lexState = 'string'; return } throw invalidChar(read$5()) }, identifierNameStartEscape () { if (c !== 'u') { throw invalidChar(read$5()) } read$5(); const u = unicodeEscape(); switch (u) { case '$': case '_': break default: if (!util$1.isIdStartChar(u)) { throw invalidIdentifier() } break } buffer += u; lexState = 'identifierName'; }, identifierName () { switch (c) { case '$': case '_': case '\u200C': case '\u200D': buffer += read$5(); return case '\\': read$5(); lexState = 'identifierNameEscape'; return } if (util$1.isIdContinueChar(c)) { buffer += read$5(); return } return newToken('identifier', buffer) }, identifierNameEscape () { if (c !== 'u') { throw invalidChar(read$5()) } read$5(); const u = unicodeEscape(); switch (u) { case '$': case '_': case '\u200C': case '\u200D': break default: if (!util$1.isIdContinueChar(u)) { throw invalidIdentifier() } break } buffer += u; lexState = 'identifierName'; }, sign () { switch (c) { case '.': buffer = read$5(); lexState = 'decimalPointLeading'; return case '0': buffer = read$5(); lexState = 'zero'; return case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer = read$5(); lexState = 'decimalInteger'; return case 'I': read$5(); literal('nfinity'); return newToken('numeric', sign * Infinity) case 'N': read$5(); literal('aN'); return newToken('numeric', NaN) } throw invalidChar(read$5()) }, zero () { switch (c) { case '.': buffer += read$5(); lexState = 'decimalPoint'; return case 'e': case 'E': buffer += read$5(); lexState = 'decimalExponent'; return case 'x': case 'X': buffer += read$5(); lexState = 'hexadecimal'; return } return newToken('numeric', sign * 0) }, decimalInteger () { switch (c) { case '.': buffer += read$5(); lexState = 'decimalPoint'; return case 'e': case 'E': buffer += read$5(); lexState = 'decimalExponent'; return } if (util$1.isDigit(c)) { buffer += read$5(); return } return newToken('numeric', sign * Number(buffer)) }, decimalPointLeading () { if (util$1.isDigit(c)) { buffer += read$5(); lexState = 'decimalFraction'; return } throw invalidChar(read$5()) }, decimalPoint () { switch (c) { case 'e': case 'E': buffer += read$5(); lexState = 'decimalExponent'; return } if (util$1.isDigit(c)) { buffer += read$5(); lexState = 'decimalFraction'; return } return newToken('numeric', sign * Number(buffer)) }, decimalFraction () { switch (c) { case 'e': case 'E': buffer += read$5(); lexState = 'decimalExponent'; return } if (util$1.isDigit(c)) { buffer += read$5(); return } return newToken('numeric', sign * Number(buffer)) }, decimalExponent () { switch (c) { case '+': case '-': buffer += read$5(); lexState = 'decimalExponentSign'; return } if (util$1.isDigit(c)) { buffer += read$5(); lexState = 'decimalExponentInteger'; return } throw invalidChar(read$5()) }, decimalExponentSign () { if (util$1.isDigit(c)) { buffer += read$5(); lexState = 'decimalExponentInteger'; return } throw invalidChar(read$5()) }, decimalExponentInteger () { if (util$1.isDigit(c)) { buffer += read$5(); return } return newToken('numeric', sign * Number(buffer)) }, hexadecimal () { if (util$1.isHexDigit(c)) { buffer += read$5(); lexState = 'hexadecimalInteger'; return } throw invalidChar(read$5()) }, hexadecimalInteger () { if (util$1.isHexDigit(c)) { buffer += read$5(); return } return newToken('numeric', sign * Number(buffer)) }, string () { switch (c) { case '\\': read$5(); buffer += escape(); return case '"': if (doubleQuote) { read$5(); return newToken('string', buffer) } buffer += read$5(); return case "'": if (!doubleQuote) { read$5(); return newToken('string', buffer) } buffer += read$5(); return case '\n': case '\r': throw invalidChar(read$5()) case '\u2028': case '\u2029': separatorChar(c); break case undefined: throw invalidChar(read$5()) } buffer += read$5(); }, start () { switch (c) { case '{': case '[': return newToken('punctuator', read$5()) // This code is unreachable since the default lexState handles eof. // case undefined: // return newToken('eof') } lexState = 'value'; }, beforePropertyName () { switch (c) { case '$': case '_': buffer = read$5(); lexState = 'identifierName'; return case '\\': read$5(); lexState = 'identifierNameStartEscape'; return case '}': return newToken('punctuator', read$5()) case '"': case "'": doubleQuote = (read$5() === '"'); lexState = 'string'; return } if (util$1.isIdStartChar(c)) { buffer += read$5(); lexState = 'identifierName'; return } throw invalidChar(read$5()) }, afterPropertyName () { if (c === ':') { return newToken('punctuator', read$5()) } throw invalidChar(read$5()) }, beforePropertyValue () { lexState = 'value'; }, afterPropertyValue () { switch (c) { case ',': case '}': return newToken('punctuator', read$5()) } throw invalidChar(read$5()) }, beforeArrayValue () { if (c === ']') { return newToken('punctuator', read$5()) } lexState = 'value'; }, afterArrayValue () { switch (c) { case ',': case ']': return newToken('punctuator', read$5()) } throw invalidChar(read$5()) }, end () { // This code is unreachable since it's handled by the default lexState. // if (c === undefined) { // read() // return newToken('eof') // } throw invalidChar(read$5()) }, }; function newToken (type, value) { return { type, value, line, column, } } function literal (s) { for (const c of s) { const p = peek(); if (p !== c) { throw invalidChar(read$5()) } read$5(); } } function escape () { const c = peek(); switch (c) { case 'b': read$5(); return '\b' case 'f': read$5(); return '\f' case 'n': read$5(); return '\n' case 'r': read$5(); return '\r' case 't': read$5(); return '\t' case 'v': read$5(); return '\v' case '0': read$5(); if (util$1.isDigit(peek())) { throw invalidChar(read$5()) } return '\0' case 'x': read$5(); return hexEscape() case 'u': read$5(); return unicodeEscape() case '\n': case '\u2028': case '\u2029': read$5(); return '' case '\r': read$5(); if (peek() === '\n') { read$5(); } return '' case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': throw invalidChar(read$5()) case undefined: throw invalidChar(read$5()) } return read$5() } function hexEscape () { let buffer = ''; let c = peek(); if (!util$1.isHexDigit(c)) { throw invalidChar(read$5()) } buffer += read$5(); c = peek(); if (!util$1.isHexDigit(c)) { throw invalidChar(read$5()) } buffer += read$5(); return String.fromCodePoint(parseInt(buffer, 16)) } function unicodeEscape () { let buffer = ''; let count = 4; while (count-- > 0) { const c = peek(); if (!util$1.isHexDigit(c)) { throw invalidChar(read$5()) } buffer += read$5(); } return String.fromCodePoint(parseInt(buffer, 16)) } const parseStates = { start () { if (token.type === 'eof') { throw invalidEOF() } push(); }, beforePropertyName () { switch (token.type) { case 'identifier': case 'string': key = token.value; parseState = 'afterPropertyName'; return case 'punctuator': // This code is unreachable since it's handled by the lexState. // if (token.value !== '}') { // throw invalidToken() // } pop(); return case 'eof': throw invalidEOF() } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, afterPropertyName () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator' || token.value !== ':') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF() } parseState = 'beforePropertyValue'; }, beforePropertyValue () { if (token.type === 'eof') { throw invalidEOF() } push(); }, beforeArrayValue () { if (token.type === 'eof') { throw invalidEOF() } if (token.type === 'punctuator' && token.value === ']') { pop(); return } push(); }, afterPropertyValue () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF() } switch (token.value) { case ',': parseState = 'beforePropertyName'; return case '}': pop(); } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, afterArrayValue () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF() } switch (token.value) { case ',': parseState = 'beforeArrayValue'; return case ']': pop(); } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, end () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'eof') { // throw invalidToken() // } }, }; function push () { let value; switch (token.type) { case 'punctuator': switch (token.value) { case '{': value = {}; break case '[': value = []; break } break case 'null': case 'boolean': case 'numeric': case 'string': value = token.value; break // This code is unreachable. // default: // throw invalidToken() } if (root === undefined) { root = value; } else { const parent = stack[stack.length - 1]; if (Array.isArray(parent)) { parent.push(value); } else { parent[key] = value; } } if (value !== null && typeof value === 'object') { stack.push(value); if (Array.isArray(value)) { parseState = 'beforeArrayValue'; } else { parseState = 'beforePropertyName'; } } else { const current = stack[stack.length - 1]; if (current == null) { parseState = 'end'; } else if (Array.isArray(current)) { parseState = 'afterArrayValue'; } else { parseState = 'afterPropertyValue'; } } } function pop () { stack.pop(); const current = stack[stack.length - 1]; if (current == null) { parseState = 'end'; } else if (Array.isArray(current)) { parseState = 'afterArrayValue'; } else { parseState = 'afterPropertyValue'; } } // This code is unreachable. // function invalidParseState () { // return new Error(`JSON5: invalid parse state '${parseState}'`) // } // This code is unreachable. // function invalidLexState (state) { // return new Error(`JSON5: invalid lex state '${state}'`) // } function invalidChar (c) { if (c === undefined) { return syntaxError$1(`JSON5: invalid end of input at ${line}:${column}`) } return syntaxError$1(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) } function invalidEOF () { return syntaxError$1(`JSON5: invalid end of input at ${line}:${column}`) } // This code is unreachable. // function invalidToken () { // if (token.type === 'eof') { // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) // } // const c = String.fromCodePoint(token.value.codePointAt(0)) // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) // } function invalidIdentifier () { column -= 5; return syntaxError$1(`JSON5: invalid identifier character at ${line}:${column}`) } function separatorChar (c) { console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`); } function formatChar (c) { const replacements = { "'": "\\'", '"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\v': '\\v', '\0': '\\0', '\u2028': '\\u2028', '\u2029': '\\u2029', }; if (replacements[c]) { return replacements[c] } if (c < ' ') { const hexString = c.charCodeAt(0).toString(16); return '\\x' + ('00' + hexString).substring(hexString.length) } return c } function syntaxError$1 (message) { const err = new SyntaxError(message); err.lineNumber = line; err.columnNumber = column; return err } var stringify$5 = function stringify (value, replacer, space) { const stack = []; let indent = ''; let propertyList; let replacerFunc; let gap = ''; let quote; if ( replacer != null && typeof replacer === 'object' && !Array.isArray(replacer) ) { space = replacer.space; quote = replacer.quote; replacer = replacer.replacer; } if (typeof replacer === 'function') { replacerFunc = replacer; } else if (Array.isArray(replacer)) { propertyList = []; for (const v of replacer) { let item; if (typeof v === 'string') { item = v; } else if ( typeof v === 'number' || v instanceof String || v instanceof Number ) { item = String(v); } if (item !== undefined && propertyList.indexOf(item) < 0) { propertyList.push(item); } } } if (space instanceof Number) { space = Number(space); } else if (space instanceof String) { space = String(space); } if (typeof space === 'number') { if (space > 0) { space = Math.min(10, Math.floor(space)); gap = ' '.substr(0, space); } } else if (typeof space === 'string') { gap = space.substr(0, 10); } return serializeProperty('', {'': value}) function serializeProperty (key, holder) { let value = holder[key]; if (value != null) { if (typeof value.toJSON5 === 'function') { value = value.toJSON5(key); } else if (typeof value.toJSON === 'function') { value = value.toJSON(key); } } if (replacerFunc) { value = replacerFunc.call(holder, key, value); } if (value instanceof Number) { value = Number(value); } else if (value instanceof String) { value = String(value); } else if (value instanceof Boolean) { value = value.valueOf(); } switch (value) { case null: return 'null' case true: return 'true' case false: return 'false' } if (typeof value === 'string') { return quoteString(value) } if (typeof value === 'number') { return String(value) } if (typeof value === 'object') { return Array.isArray(value) ? serializeArray(value) : serializeObject(value) } return undefined } function quoteString (value) { const quotes = { "'": 0.1, '"': 0.2, }; const replacements = { "'": "\\'", '"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\v': '\\v', '\0': '\\0', '\u2028': '\\u2028', '\u2029': '\\u2029', }; let product = ''; for (let i = 0; i < value.length; i++) { const c = value[i]; switch (c) { case "'": case '"': quotes[c]++; product += c; continue case '\0': if (util$1.isDigit(value[i + 1])) { product += '\\x00'; continue } } if (replacements[c]) { product += replacements[c]; continue } if (c < ' ') { let hexString = c.charCodeAt(0).toString(16); product += '\\x' + ('00' + hexString).substring(hexString.length); continue } product += c; } const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b); product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]); return quoteChar + product + quoteChar } function serializeObject (value) { if (stack.indexOf(value) >= 0) { throw TypeError('Converting circular structure to JSON5') } stack.push(value); let stepback = indent; indent = indent + gap; let keys = propertyList || Object.keys(value); let partial = []; for (const key of keys) { const propertyString = serializeProperty(key, value); if (propertyString !== undefined) { let member = serializeKey(key) + ':'; if (gap !== '') { member += ' '; } member += propertyString; partial.push(member); } } let final; if (partial.length === 0) { final = '{}'; } else { let properties; if (gap === '') { properties = partial.join(','); final = '{' + properties + '}'; } else { let separator = ',\n' + indent; properties = partial.join(separator); final = '{\n' + indent + properties + ',\n' + stepback + '}'; } } stack.pop(); indent = stepback; return final } function serializeKey (key) { if (key.length === 0) { return quoteString(key) } const firstChar = String.fromCodePoint(key.codePointAt(0)); if (!util$1.isIdStartChar(firstChar)) { return quoteString(key) } for (let i = firstChar.length; i < key.length; i++) { if (!util$1.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { return quoteString(key) } } return key } function serializeArray (value) { if (stack.indexOf(value) >= 0) { throw TypeError('Converting circular structure to JSON5') } stack.push(value); let stepback = indent; indent = indent + gap; let partial = []; for (let i = 0; i < value.length; i++) { const propertyString = serializeProperty(String(i), value); partial.push((propertyString !== undefined) ? propertyString : 'null'); } let final; if (partial.length === 0) { final = '[]'; } else { if (gap === '') { let properties = partial.join(','); final = '[' + properties + ']'; } else { let separator = ',\n' + indent; let properties = partial.join(separator); final = '[\n' + indent + properties + ',\n' + stepback + ']'; } } stack.pop(); indent = stepback; return final } }; const JSON5 = { parse: parse$7, stringify: stringify$5, }; var lib$5 = JSON5; var dist$1 = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': lib$5 }); var schema$1 = [ { long: "help", description: "output usage information", short: "h", type: "boolean", "default": false }, { long: "version", description: "output version number", short: "v", type: "boolean", "default": false }, { long: "output", description: "specify output location", short: "o", value: "[path]" }, { long: "rc-path", description: "specify configuration file", short: "r", type: "string", value: "" }, { long: "ignore-path", description: "specify ignore file", short: "i", type: "string", value: "" }, { long: "setting", description: "specify settings", short: "s", type: "string", value: "" }, { long: "ext", description: "specify extensions", short: "e", type: "string", value: "" }, { long: "use", description: "use plugins", short: "u", type: "string", value: "" }, { long: "watch", description: "watch for changes and reprocess", short: "w", type: "boolean", "default": false }, { long: "quiet", description: "output only warnings and errors", short: "q", type: "boolean", "default": false }, { long: "silent", description: "output only errors", short: "S", type: "boolean", "default": false }, { long: "frail", description: "exit with 1 on warnings", short: "f", type: "boolean", "default": false }, { long: "tree", description: "specify input and output as syntax tree", short: "t", type: "boolean", "default": false }, { long: "report", description: "specify reporter", type: "string", value: "" }, { long: "file-path", description: "specify path to process as", type: "string", value: "" }, { long: "ignore-path-resolve-from", description: "resolve patterns in `ignore-path` from its directory or cwd", type: "string", value: "dir|cwd", "default": "dir" }, { long: "ignore-pattern", description: "specify ignore patterns", type: "string", value: "" }, { long: "silently-ignore", description: "do not fail when given ignored files", type: "boolean" }, { long: "tree-in", description: "specify input as syntax tree", type: "boolean" }, { long: "tree-out", description: "output syntax tree", type: "boolean" }, { long: "inspect", description: "output formatted syntax tree", type: "boolean" }, { long: "stdout", description: "specify writing to stdout", type: "boolean", truelike: true }, { long: "color", description: "specify color in report", type: "boolean", "default": true }, { long: "config", description: "search for configuration files", type: "boolean", "default": true }, { long: "ignore", description: "search for ignore files", type: "boolean", "default": true } ]; var schema$2 = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': schema$1 }); var json5 = getCjsExportFromNamespace(dist$1); var schema$3 = getCjsExportFromNamespace(schema$2); var options_1 = options; // Schema for `minimist`. var minischema = { unknown: handleUnknownArgument, default: {}, alias: {}, string: [], boolean: [] }; schema$3.forEach(addEach); // Parse CLI options. function options(flags, configuration) { var extension = configuration.extensions[0]; var name = configuration.name; var config = toCamelCase(minimist(flags, minischema)); var help; var ext; var report; schema$3.forEach(function (option) { if (option.type === 'string' && config[option.long] === '') { throw fault_1('Missing value:%s', inspect$1(option).join(' ')) } }); ext = commaSeparated(config.ext); report = reporter$1(config.report); help = [ inspectAll(schema$3), '', 'Examples:', '', ' # Process `input.' + extension + '`', ' $ ' + name + ' input.' + extension + ' -o output.' + extension, '', ' # Pipe', ' $ ' + name + ' < input.' + extension + ' > output.' + extension, '', ' # Rewrite all applicable files', ' $ ' + name + ' . -o' ].join('\n'); return { helpMessage: help, // “hidden” feature, makes testing easier. cwd: configuration.cwd, processor: configuration.processor, help: config.help, version: config.version, files: config._, filePath: config.filePath, watch: config.watch, extensions: ext.length === 0 ? configuration.extensions : ext, output: config.output, out: config.stdout, tree: config.tree, treeIn: config.treeIn, treeOut: config.treeOut, inspect: config.inspect, rcName: configuration.rcName, packageField: configuration.packageField, rcPath: config.rcPath, detectConfig: config.config, settings: settings(config.setting), ignoreName: configuration.ignoreName, ignorePath: config.ignorePath, ignorePathResolveFrom: config.ignorePathResolveFrom, ignorePatterns: commaSeparated(config.ignorePattern), silentlyIgnore: config.silentlyIgnore, detectIgnore: config.ignore, pluginPrefix: configuration.pluginPrefix, plugins: plugins(config.use), reporter: report[0], reporterOptions: report[1], color: config.color, silent: config.silent, quiet: config.quiet, frail: config.frail } } function addEach(option) { var value = option.default; minischema.default[option.long] = value === undefined ? null : value; if (option.type in minischema) { minischema[option.type].push(option.long); } if (option.short) { minischema.alias[option.short] = option.long; } } // Parse `extensions`. function commaSeparated(value) { return flatten$1(normalize$1(value).map(splitList)) } // Parse `plugins`. function plugins(value) { var result = {}; normalize$1(value) .map(splitOptions) .forEach(function (value) { result[value[0]] = value[1] ? parseConfig(value[1], {}) : null; }); return result } // Parse `reporter`: only one is accepted. function reporter$1(value) { var all = normalize$1(value) .map(splitOptions) .map(function (value) { return [value[0], value[1] ? parseConfig(value[1], {}) : null] }); return all[all.length - 1] || [] } // Parse `settings`. function settings(value) { var cache = {}; normalize$1(value).forEach(function (value) { parseConfig(value, cache); }); return cache } // Parse configuration. function parseConfig(flags, cache) { var flag; var message; try { flags = toCamelCase(parseJSON(flags)); } catch (error) { // Fix position message = error.message.replace(/at(?= position)/, 'around'); throw fault_1('Cannot parse `%s` as JSON: %s', flags, message) } for (flag in flags) { cache[flag] = flags[flag]; } return cache } // Handle an unknown flag. function handleUnknownArgument(flag) { // Glob. if (flag.charAt(0) !== '-') { return } // Long options, always unknown. if (flag.charAt(1) === '-') { throw fault_1('Unknown option `%s`, expected:\n%s', flag, inspectAll(schema$3)) } // Short options, can be grouped. flag.slice(1).split('').forEach(each); function each(key) { var length = schema$3.length; var index = -1; var option; while (++index < length) { option = schema$3[index]; if (option.short === key) { return } } throw fault_1( 'Unknown short option `-%s`, expected:\n%s', key, inspectAll(schema$3.filter(short)) ) } function short(option) { return option.short } } // Inspect all `options`. function inspectAll(options) { return textTable(options.map(inspect$1)) } // Inspect one `option`. function inspect$1(option) { var description = option.description; var long = option.long; if (option.default === true || option.truelike) { description += ' (on by default)'; long = '[no-]' + long; } return [ '', option.short ? '-' + option.short : '', '--' + long + (option.value ? ' ' + option.value : ''), description ] } // Normalize `value`. function normalize$1(value) { if (!value) { return [] } if (typeof value === 'string') { return [value] } return flatten$1(value.map(normalize$1)) } // Flatten `values`. function flatten$1(values) { return [].concat.apply([], values) } function splitOptions(value) { return value.split('=') } function splitList(value) { return value.split(',') } // Transform the keys on an object to camel-case, recursivly. function toCamelCase(object) { var result = {}; var value; var key; for (key in object) { value = object[key]; if (value && typeof value === 'object' && !('length' in value)) { value = toCamelCase(value); } result[camelcase(key)] = value; } return result } // Parse a (lazy?) JSON config. function parseJSON(value) { return json5.parse('{' + value + '}') } var lib$6 = start; var noop$1 = Function.prototype; // Fake TTY stream. var ttyStream = new stream__default['default'].Readable(); ttyStream.isTTY = true; // Exit, lazily, with the correct exit status code. var exitStatus = 0; process.on('exit', onexit); // Handle uncaught errors, such as from unexpected async behaviour. process.on('uncaughtException', fail$1); // Start the CLI. function start(cliConfig) { var config; var output; var watcher; try { config = options_1(process.argv.slice(2), cliConfig); } catch (error) { return fail$1(error, true) } if (config.help) { process.stdout.write( [ 'Usage: ' + cliConfig.name + ' [options] [path | glob ...]', '', ' ' + cliConfig.description, '', 'Options:', '', config.helpMessage, '' ].join('\n'), noop$1 ); return } if (config.version) { process.stdout.write(cliConfig.version + '\n', noop$1); return } // Modify `config` for watching. if (config.watch) { output = config.output; // Do not read from stdin(4). config.streamIn = ttyStream; // Do not write to stdout(4). config.out = false; process.stderr.write( source.bold('Watching...') + ' (press CTRL+C to exit)\n', noop$1 ); // Prevent infinite loop if set to regeneration. if (output === true) { config.output = false; process.stderr.write( source.yellow('Note') + ': Ignoring `--output` until exit.\n', noop$1 ); } } // Initial run. lib$4(config, done); // Handle complete run. function done(err, code, context) { if (err) { clean(); fail$1(err); } else { exitStatus = code; if (config.watch && !watcher) { subscribe(context); } } } // Clean the watcher. function clean() { if (watcher) { watcher.close(); watcher = null; } } // Subscribe a chokidar watcher to all processed files. function subscribe(context) { watcher = chokidar .watch(context.fileSet.origins, {cwd: config.cwd, ignoreInitial: true}) .on('error', done) .on('change', onchange); process.on('SIGINT', onsigint); function onchange(filePath) { config.files = [filePath]; lib$4(config, done); } function onsigint() { // Hide the `^C` in terminal. process.stderr.write('\n', noop$1); clean(); // Do another process if `output` specified regeneration. if (output === true) { config.output = output; config.watch = false; lib$4(config, done); } } } } // Print an error, optionally with stack. function fail$1(err, pretty) { var message = (pretty ? String(err).trim() : err.stack) || /* istanbul ignore next - Old versions of Node */ err; exitStatus = 1; process.stderr.write(message.trim() + '\n', noop$1); } function onexit() { /* eslint-disable unicorn/no-process-exit */ process.exit(exitStatus); /* eslint-enable unicorn/no-process-exit */ } var unifiedArgs = lib$6; var markdownExtensions = [ "md", "markdown", "mdown", "mkdn", "mkd", "mdwn", "mkdown", "ron" ]; var markdownExtensions$1 = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': markdownExtensions }); var require$$0$2 = getCjsExportFromNamespace(markdownExtensions$1); var markdownExtensions$2 = require$$0$2; var bail_1 = bail; function bail(err) { if (err) { throw err } } var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var defineProperty = Object.defineProperty; var gOPD = Object.getOwnPropertyDescriptor; var isArray$1 = function isArray(arr) { if (typeof Array.isArray === 'function') { return Array.isArray(arr); } return toStr.call(arr) === '[object Array]'; }; var isPlainObject = function isPlainObject(obj) { if (!obj || toStr.call(obj) !== '[object Object]') { return false; } var hasOwnConstructor = hasOwn.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) { /**/ } return typeof key === 'undefined' || hasOwn.call(obj, key); }; // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target var setProperty = function setProperty(target, options) { if (defineProperty && options.name === '__proto__') { defineProperty(target, options.name, { enumerable: true, configurable: true, value: options.newValue, writable: true }); } else { target[options.name] = options.newValue; } }; // Return undefined instead of __proto__ if '__proto__' is not an own property var getProperty = function getProperty(obj, name) { if (name === '__proto__') { if (!hasOwn.call(obj, name)) { return void 0; } else if (gOPD) { // In early versions of node, obj['__proto__'] is buggy when obj has // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. return gOPD(obj, name).value; } } return obj[name]; }; var extend$2 = function extend() { var options, name, src, copy, copyIsArray, clone; var target = arguments[0]; var i = 1; var length = arguments.length; var deep = false; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { target = {}; } for (; i < length; ++i) { options = arguments[i]; // Only deal with non-null/undefined values if (options != null) { // Extend the base object for (name in options) { src = getProperty(target, name); copy = getProperty(options, name); // Prevent never-ending loop if (target !== copy) { // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray$1(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray$1(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { setProperty(target, { name: name, newValue: copy }); } } } } } // Return the modified object return target; }; // Expose a frozen processor. var unified_1 = unified().freeze(); var slice$3 = [].slice; var own$2 = {}.hasOwnProperty; // Process pipeline. var pipeline = trough_1() .use(pipelineParse) .use(pipelineRun) .use(pipelineStringify); function pipelineParse(p, ctx) { ctx.tree = p.parse(ctx.file); } function pipelineRun(p, ctx, next) { p.run(ctx.tree, ctx.file, done); function done(err, tree, file) { if (err) { next(err); } else { ctx.tree = tree; ctx.file = file; next(); } } } function pipelineStringify(p, ctx) { var result = p.stringify(ctx.tree, ctx.file); var file = ctx.file; if (result === undefined || result === null) ; else if (typeof result === 'string' || isBuffer(result)) { file.contents = result; } else { file.result = result; } } // Function to create the first processor. function unified() { var attachers = []; var transformers = trough_1(); var namespace = {}; var frozen = false; var freezeIndex = -1; // Data management. processor.data = data; // Lock. processor.freeze = freeze; // Plugins. processor.attachers = attachers; processor.use = use; // API. processor.parse = parse; processor.stringify = stringify; processor.run = run; processor.runSync = runSync; processor.process = process; processor.processSync = processSync; // Expose. return processor // Create a new processor based on the processor in the current scope. function processor() { var destination = unified(); var length = attachers.length; var index = -1; while (++index < length) { destination.use.apply(null, attachers[index]); } destination.data(extend$2(true, {}, namespace)); return destination } // Freeze: used to signal a processor that has finished configuration. // // For example, take unified itself: it’s frozen. // Plugins should not be added to it. // Rather, it should be extended, by invoking it, before modifying it. // // In essence, always invoke this when exporting a processor. function freeze() { var values; var plugin; var options; var transformer; if (frozen) { return processor } while (++freezeIndex < attachers.length) { values = attachers[freezeIndex]; plugin = values[0]; options = values[1]; transformer = null; if (options === false) { continue } if (options === true) { values[1] = undefined; } transformer = plugin.apply(processor, values.slice(1)); if (typeof transformer === 'function') { transformers.use(transformer); } } frozen = true; freezeIndex = Infinity; return processor } // Data management. // Getter / setter for processor-specific informtion. function data(key, value) { if (typeof key === 'string') { // Set `key`. if (arguments.length === 2) { assertUnfrozen('data', frozen); namespace[key] = value; return processor } // Get `key`. return (own$2.call(namespace, key) && namespace[key]) || null } // Set space. if (key) { assertUnfrozen('data', frozen); namespace = key; return processor } // Get space. return namespace } // Plugin management. // // Pass it: // * an attacher and options, // * a preset, // * a list of presets, attachers, and arguments (list of attachers and // options). function use(value) { var settings; assertUnfrozen('use', frozen); if (value === null || value === undefined) ; else if (typeof value === 'function') { addPlugin.apply(null, arguments); } else if (typeof value === 'object') { if ('length' in value) { addList(value); } else { addPreset(value); } } else { throw new Error('Expected usable value, not `' + value + '`') } if (settings) { namespace.settings = extend$2(namespace.settings || {}, settings); } return processor function addPreset(result) { addList(result.plugins); if (result.settings) { settings = extend$2(settings || {}, result.settings); } } function add(value) { if (typeof value === 'function') { addPlugin(value); } else if (typeof value === 'object') { if ('length' in value) { addPlugin.apply(null, value); } else { addPreset(value); } } else { throw new Error('Expected usable value, not `' + value + '`') } } function addList(plugins) { var length; var index; if (plugins === null || plugins === undefined) ; else if (typeof plugins === 'object' && 'length' in plugins) { length = plugins.length; index = -1; while (++index < length) { add(plugins[index]); } } else { throw new Error('Expected a list of plugins, not `' + plugins + '`') } } function addPlugin(plugin, value) { var entry = find(plugin); if (entry) { if (isPlainObj(entry[1]) && isPlainObj(value)) { value = extend$2(entry[1], value); } entry[1] = value; } else { attachers.push(slice$3.call(arguments)); } } } function find(plugin) { var length = attachers.length; var index = -1; var entry; while (++index < length) { entry = attachers[index]; if (entry[0] === plugin) { return entry } } } // Parse a file (in string or vfile representation) into a unist node using // the `Parser` on the processor. function parse(doc) { var file = vfile(doc); var Parser; freeze(); Parser = processor.Parser; assertParser('parse', Parser); if (newable(Parser, 'parse')) { return new Parser(String(file), file).parse() } return Parser(String(file), file) // eslint-disable-line new-cap } // Run transforms on a unist node representation of a file (in string or // vfile representation), async. function run(node, file, cb) { assertNode(node); freeze(); if (!cb && typeof file === 'function') { cb = file; file = null; } if (!cb) { return new Promise(executor) } executor(null, cb); function executor(resolve, reject) { transformers.run(node, vfile(file), done); function done(err, tree, file) { tree = tree || node; if (err) { reject(err); } else if (resolve) { resolve(tree); } else { cb(null, tree, file); } } } } // Run transforms on a unist node representation of a file (in string or // vfile representation), sync. function runSync(node, file) { var complete = false; var result; run(node, file, done); assertDone('runSync', 'run', complete); return result function done(err, tree) { complete = true; bail_1(err); result = tree; } } // Stringify a unist node representation of a file (in string or vfile // representation) into a string using the `Compiler` on the processor. function stringify(node, doc) { var file = vfile(doc); var Compiler; freeze(); Compiler = processor.Compiler; assertCompiler('stringify', Compiler); assertNode(node); if (newable(Compiler, 'compile')) { return new Compiler(node, file).compile() } return Compiler(node, file) // eslint-disable-line new-cap } // Parse a file (in string or vfile representation) into a unist node using // the `Parser` on the processor, then run transforms on that node, and // compile the resulting node using the `Compiler` on the processor, and // store that result on the vfile. function process(doc, cb) { freeze(); assertParser('process', processor.Parser); assertCompiler('process', processor.Compiler); if (!cb) { return new Promise(executor) } executor(null, cb); function executor(resolve, reject) { var file = vfile(doc); pipeline.run(processor, {file: file}, done); function done(err) { if (err) { reject(err); } else if (resolve) { resolve(file); } else { cb(null, file); } } } } // Process the given document (in string or vfile representation), sync. function processSync(doc) { var complete = false; var file; freeze(); assertParser('processSync', processor.Parser); assertCompiler('processSync', processor.Compiler); file = vfile(doc); process(file, done); assertDone('processSync', 'process', complete); return file function done(err) { complete = true; bail_1(err); } } } // Check if `value` is a constructor. function newable(value, name) { return ( typeof value === 'function' && value.prototype && // A function with keys in its prototype is probably a constructor. // Classes’ prototype methods are not enumerable, so we check if some value // exists in the prototype. (keys(value.prototype) || name in value.prototype) ) } // Check if `value` is an object with keys. function keys(value) { var key; for (key in value) { return true } return false } // Assert a parser is available. function assertParser(name, Parser) { if (typeof Parser !== 'function') { throw new Error('Cannot `' + name + '` without `Parser`') } } // Assert a compiler is available. function assertCompiler(name, Compiler) { if (typeof Compiler !== 'function') { throw new Error('Cannot `' + name + '` without `Compiler`') } } // Assert the processor is not frozen. function assertUnfrozen(name, frozen) { if (frozen) { throw new Error( 'Cannot invoke `' + name + '` on a frozen processor.\nCreate a new processor first, by invoking it: use `processor()` instead of `processor`.' ) } } // Assert `node` is a unist node. function assertNode(node) { if (!node || typeof node.type !== 'string') { throw new Error('Expected node, got `' + node + '`') } } // Assert that `complete` is `true`. function assertDone(name, asyncName, complete) { if (!complete) { throw new Error( '`' + name + '` finished async. Use `' + asyncName + '` instead' ) } } const AEli = "Æ"; const AElig = "Æ"; const AM = "&"; const AMP = "&"; const Aacut = "Á"; const Aacute = "Á"; const Abreve = "Ă"; const Acir = "Â"; const Acirc = "Â"; const Acy = "А"; const Afr = "𝔄"; const Agrav = "À"; const Agrave = "À"; const Alpha = "Α"; const Amacr = "Ā"; const And = "⩓"; const Aogon = "Ą"; const Aopf = "𝔸"; const ApplyFunction = "⁡"; const Arin = "Å"; const Aring = "Å"; const Ascr = "𝒜"; const Assign = "≔"; const Atild = "Ã"; const Atilde = "Ã"; const Aum = "Ä"; const Auml = "Ä"; const Backslash = "∖"; const Barv = "⫧"; const Barwed = "⌆"; const Bcy = "Б"; const Because = "∵"; const Bernoullis = "ℬ"; const Beta = "Β"; const Bfr = "𝔅"; const Bopf = "𝔹"; const Breve = "˘"; const Bscr = "ℬ"; const Bumpeq = "≎"; const CHcy = "Ч"; const COP = "©"; const COPY = "©"; const Cacute = "Ć"; const Cap = "⋒"; const CapitalDifferentialD = "ⅅ"; const Cayleys = "ℭ"; const Ccaron = "Č"; const Ccedi = "Ç"; const Ccedil = "Ç"; const Ccirc = "Ĉ"; const Cconint = "∰"; const Cdot = "Ċ"; const Cedilla = "¸"; const CenterDot = "·"; const Cfr = "ℭ"; const Chi = "Χ"; const CircleDot = "⊙"; const CircleMinus = "⊖"; const CirclePlus = "⊕"; const CircleTimes = "⊗"; const ClockwiseContourIntegral = "∲"; const CloseCurlyDoubleQuote = "”"; const CloseCurlyQuote = "’"; const Colon = "∷"; const Colone = "⩴"; const Congruent = "≡"; const Conint = "∯"; const ContourIntegral = "∮"; const Copf = "ℂ"; const Coproduct = "∐"; const CounterClockwiseContourIntegral = "∳"; const Cross = "⨯"; const Cscr = "𝒞"; const Cup = "⋓"; const CupCap = "≍"; const DD = "ⅅ"; const DDotrahd = "⤑"; const DJcy = "Ђ"; const DScy = "Ѕ"; const DZcy = "Џ"; const Dagger = "‡"; const Darr = "↡"; const Dashv = "⫤"; const Dcaron = "Ď"; const Dcy = "Д"; const Del = "∇"; const Delta = "Δ"; const Dfr = "𝔇"; const DiacriticalAcute = "´"; const DiacriticalDot = "˙"; const DiacriticalDoubleAcute = "˝"; const DiacriticalGrave = "`"; const DiacriticalTilde = "˜"; const Diamond = "⋄"; const DifferentialD = "ⅆ"; const Dopf = "𝔻"; const Dot = "¨"; const DotDot = "⃜"; const DotEqual = "≐"; const DoubleContourIntegral = "∯"; const DoubleDot = "¨"; const DoubleDownArrow = "⇓"; const DoubleLeftArrow = "⇐"; const DoubleLeftRightArrow = "⇔"; const DoubleLeftTee = "⫤"; const DoubleLongLeftArrow = "⟸"; const DoubleLongLeftRightArrow = "⟺"; const DoubleLongRightArrow = "⟹"; const DoubleRightArrow = "⇒"; const DoubleRightTee = "⊨"; const DoubleUpArrow = "⇑"; const DoubleUpDownArrow = "⇕"; const DoubleVerticalBar = "∥"; const DownArrow = "↓"; const DownArrowBar = "⤓"; const DownArrowUpArrow = "⇵"; const DownBreve = "̑"; const DownLeftRightVector = "⥐"; const DownLeftTeeVector = "⥞"; const DownLeftVector = "↽"; const DownLeftVectorBar = "⥖"; const DownRightTeeVector = "⥟"; const DownRightVector = "⇁"; const DownRightVectorBar = "⥗"; const DownTee = "⊤"; const DownTeeArrow = "↧"; const Downarrow = "⇓"; const Dscr = "𝒟"; const Dstrok = "Đ"; const ENG = "Ŋ"; const ET = "Ð"; const ETH = "Ð"; const Eacut = "É"; const Eacute = "É"; const Ecaron = "Ě"; const Ecir = "Ê"; const Ecirc = "Ê"; const Ecy = "Э"; const Edot = "Ė"; const Efr = "𝔈"; const Egrav = "È"; const Egrave = "È"; const Element = "∈"; const Emacr = "Ē"; const EmptySmallSquare = "◻"; const EmptyVerySmallSquare = "▫"; const Eogon = "Ę"; const Eopf = "𝔼"; const Epsilon = "Ε"; const Equal = "⩵"; const EqualTilde = "≂"; const Equilibrium = "⇌"; const Escr = "ℰ"; const Esim = "⩳"; const Eta = "Η"; const Eum = "Ë"; const Euml = "Ë"; const Exists = "∃"; const ExponentialE = "ⅇ"; const Fcy = "Ф"; const Ffr = "𝔉"; const FilledSmallSquare = "◼"; const FilledVerySmallSquare = "▪"; const Fopf = "𝔽"; const ForAll = "∀"; const Fouriertrf = "ℱ"; const Fscr = "ℱ"; const GJcy = "Ѓ"; const G = ">"; const GT = ">"; const Gamma = "Γ"; const Gammad = "Ϝ"; const Gbreve = "Ğ"; const Gcedil = "Ģ"; const Gcirc = "Ĝ"; const Gcy = "Г"; const Gdot = "Ġ"; const Gfr = "𝔊"; const Gg = "⋙"; const Gopf = "𝔾"; const GreaterEqual = "≥"; const GreaterEqualLess = "⋛"; const GreaterFullEqual = "≧"; const GreaterGreater = "⪢"; const GreaterLess = "≷"; const GreaterSlantEqual = "⩾"; const GreaterTilde = "≳"; const Gscr = "𝒢"; const Gt = "≫"; const HARDcy = "Ъ"; const Hacek = "ˇ"; const Hat = "^"; const Hcirc = "Ĥ"; const Hfr = "ℌ"; const HilbertSpace = "ℋ"; const Hopf = "ℍ"; const HorizontalLine = "─"; const Hscr = "ℋ"; const Hstrok = "Ħ"; const HumpDownHump = "≎"; const HumpEqual = "≏"; const IEcy = "Е"; const IJlig = "IJ"; const IOcy = "Ё"; const Iacut = "Í"; const Iacute = "Í"; const Icir = "Î"; const Icirc = "Î"; const Icy = "И"; const Idot = "İ"; const Ifr = "ℑ"; const Igrav = "Ì"; const Igrave = "Ì"; const Im = "ℑ"; const Imacr = "Ī"; const ImaginaryI = "ⅈ"; const Implies = "⇒"; const Int = "∬"; const Integral = "∫"; const Intersection = "⋂"; const InvisibleComma = "⁣"; const InvisibleTimes = "⁢"; const Iogon = "Į"; const Iopf = "𝕀"; const Iota = "Ι"; const Iscr = "ℐ"; const Itilde = "Ĩ"; const Iukcy = "І"; const Ium = "Ï"; const Iuml = "Ï"; const Jcirc = "Ĵ"; const Jcy = "Й"; const Jfr = "𝔍"; const Jopf = "𝕁"; const Jscr = "𝒥"; const Jsercy = "Ј"; const Jukcy = "Є"; const KHcy = "Х"; const KJcy = "Ќ"; const Kappa = "Κ"; const Kcedil = "Ķ"; const Kcy = "К"; const Kfr = "𝔎"; const Kopf = "𝕂"; const Kscr = "𝒦"; const LJcy = "Љ"; const L = "<"; const LT = "<"; const Lacute = "Ĺ"; const Lambda = "Λ"; const Lang = "⟪"; const Laplacetrf = "ℒ"; const Larr = "↞"; const Lcaron = "Ľ"; const Lcedil = "Ļ"; const Lcy = "Л"; const LeftAngleBracket = "⟨"; const LeftArrow = "←"; const LeftArrowBar = "⇤"; const LeftArrowRightArrow = "⇆"; const LeftCeiling = "⌈"; const LeftDoubleBracket = "⟦"; const LeftDownTeeVector = "⥡"; const LeftDownVector = "⇃"; const LeftDownVectorBar = "⥙"; const LeftFloor = "⌊"; const LeftRightArrow = "↔"; const LeftRightVector = "⥎"; const LeftTee = "⊣"; const LeftTeeArrow = "↤"; const LeftTeeVector = "⥚"; const LeftTriangle = "⊲"; const LeftTriangleBar = "⧏"; const LeftTriangleEqual = "⊴"; const LeftUpDownVector = "⥑"; const LeftUpTeeVector = "⥠"; const LeftUpVector = "↿"; const LeftUpVectorBar = "⥘"; const LeftVector = "↼"; const LeftVectorBar = "⥒"; const Leftarrow = "⇐"; const Leftrightarrow = "⇔"; const LessEqualGreater = "⋚"; const LessFullEqual = "≦"; const LessGreater = "≶"; const LessLess = "⪡"; const LessSlantEqual = "⩽"; const LessTilde = "≲"; const Lfr = "𝔏"; const Ll = "⋘"; const Lleftarrow = "⇚"; const Lmidot = "Ŀ"; const LongLeftArrow = "⟵"; const LongLeftRightArrow = "⟷"; const LongRightArrow = "⟶"; const Longleftarrow = "⟸"; const Longleftrightarrow = "⟺"; const Longrightarrow = "⟹"; const Lopf = "𝕃"; const LowerLeftArrow = "↙"; const LowerRightArrow = "↘"; const Lscr = "ℒ"; const Lsh = "↰"; const Lstrok = "Ł"; const Lt = "≪"; const Mcy = "М"; const MediumSpace = " "; const Mellintrf = "ℳ"; const Mfr = "𝔐"; const MinusPlus = "∓"; const Mopf = "𝕄"; const Mscr = "ℳ"; const Mu = "Μ"; const NJcy = "Њ"; const Nacute = "Ń"; const Ncaron = "Ň"; const Ncedil = "Ņ"; const Ncy = "Н"; const NegativeMediumSpace = "​"; const NegativeThickSpace = "​"; const NegativeThinSpace = "​"; const NegativeVeryThinSpace = "​"; const NestedGreaterGreater = "≫"; const NestedLessLess = "≪"; const NewLine = "\n"; const Nfr = "𝔑"; const NoBreak = "⁠"; const NonBreakingSpace = " "; const Nopf = "ℕ"; const Not = "⫬"; const NotCongruent = "≢"; const NotCupCap = "≭"; const NotDoubleVerticalBar = "∦"; const NotElement = "∉"; const NotEqual = "≠"; const NotEqualTilde = "≂̸"; const NotExists = "∄"; const NotGreater = "≯"; const NotGreaterEqual = "≱"; const NotGreaterFullEqual = "≧̸"; const NotGreaterGreater = "≫̸"; const NotGreaterLess = "≹"; const NotGreaterSlantEqual = "⩾̸"; const NotGreaterTilde = "≵"; const NotHumpDownHump = "≎̸"; const NotHumpEqual = "≏̸"; const NotLeftTriangle = "⋪"; const NotLeftTriangleBar = "⧏̸"; const NotLeftTriangleEqual = "⋬"; const NotLess = "≮"; const NotLessEqual = "≰"; const NotLessGreater = "≸"; const NotLessLess = "≪̸"; const NotLessSlantEqual = "⩽̸"; const NotLessTilde = "≴"; const NotNestedGreaterGreater = "⪢̸"; const NotNestedLessLess = "⪡̸"; const NotPrecedes = "⊀"; const NotPrecedesEqual = "⪯̸"; const NotPrecedesSlantEqual = "⋠"; const NotReverseElement = "∌"; const NotRightTriangle = "⋫"; const NotRightTriangleBar = "⧐̸"; const NotRightTriangleEqual = "⋭"; const NotSquareSubset = "⊏̸"; const NotSquareSubsetEqual = "⋢"; const NotSquareSuperset = "⊐̸"; const NotSquareSupersetEqual = "⋣"; const NotSubset = "⊂⃒"; const NotSubsetEqual = "⊈"; const NotSucceeds = "⊁"; const NotSucceedsEqual = "⪰̸"; const NotSucceedsSlantEqual = "⋡"; const NotSucceedsTilde = "≿̸"; const NotSuperset = "⊃⃒"; const NotSupersetEqual = "⊉"; const NotTilde = "≁"; const NotTildeEqual = "≄"; const NotTildeFullEqual = "≇"; const NotTildeTilde = "≉"; const NotVerticalBar = "∤"; const Nscr = "𝒩"; const Ntild = "Ñ"; const Ntilde = "Ñ"; const Nu = "Ν"; const OElig = "Œ"; const Oacut = "Ó"; const Oacute = "Ó"; const Ocir = "Ô"; const Ocirc = "Ô"; const Ocy = "О"; const Odblac = "Ő"; const Ofr = "𝔒"; const Ograv = "Ò"; const Ograve = "Ò"; const Omacr = "Ō"; const Omega = "Ω"; const Omicron = "Ο"; const Oopf = "𝕆"; const OpenCurlyDoubleQuote = "“"; const OpenCurlyQuote = "‘"; const Or = "⩔"; const Oscr = "𝒪"; const Oslas = "Ø"; const Oslash = "Ø"; const Otild = "Õ"; const Otilde = "Õ"; const Otimes = "⨷"; const Oum = "Ö"; const Ouml = "Ö"; const OverBar = "‾"; const OverBrace = "⏞"; const OverBracket = "⎴"; const OverParenthesis = "⏜"; const PartialD = "∂"; const Pcy = "П"; const Pfr = "𝔓"; const Phi = "Φ"; const Pi = "Π"; const PlusMinus = "±"; const Poincareplane = "ℌ"; const Popf = "ℙ"; const Pr = "⪻"; const Precedes = "≺"; const PrecedesEqual = "⪯"; const PrecedesSlantEqual = "≼"; const PrecedesTilde = "≾"; const Prime = "″"; const Product = "∏"; const Proportion = "∷"; const Proportional = "∝"; const Pscr = "𝒫"; const Psi = "Ψ"; const QUO = "\""; const QUOT = "\""; const Qfr = "𝔔"; const Qopf = "ℚ"; const Qscr = "𝒬"; const RBarr = "⤐"; const RE = "®"; const REG = "®"; const Racute = "Ŕ"; const Rang = "⟫"; const Rarr = "↠"; const Rarrtl = "⤖"; const Rcaron = "Ř"; const Rcedil = "Ŗ"; const Rcy = "Р"; const Re = "ℜ"; const ReverseElement = "∋"; const ReverseEquilibrium = "⇋"; const ReverseUpEquilibrium = "⥯"; const Rfr = "ℜ"; const Rho = "Ρ"; const RightAngleBracket = "⟩"; const RightArrow = "→"; const RightArrowBar = "⇥"; const RightArrowLeftArrow = "⇄"; const RightCeiling = "⌉"; const RightDoubleBracket = "⟧"; const RightDownTeeVector = "⥝"; const RightDownVector = "⇂"; const RightDownVectorBar = "⥕"; const RightFloor = "⌋"; const RightTee = "⊢"; const RightTeeArrow = "↦"; const RightTeeVector = "⥛"; const RightTriangle = "⊳"; const RightTriangleBar = "⧐"; const RightTriangleEqual = "⊵"; const RightUpDownVector = "⥏"; const RightUpTeeVector = "⥜"; const RightUpVector = "↾"; const RightUpVectorBar = "⥔"; const RightVector = "⇀"; const RightVectorBar = "⥓"; const Rightarrow = "⇒"; const Ropf = "ℝ"; const RoundImplies = "⥰"; const Rrightarrow = "⇛"; const Rscr = "ℛ"; const Rsh = "↱"; const RuleDelayed = "⧴"; const SHCHcy = "Щ"; const SHcy = "Ш"; const SOFTcy = "Ь"; const Sacute = "Ś"; const Sc = "⪼"; const Scaron = "Š"; const Scedil = "Ş"; const Scirc = "Ŝ"; const Scy = "С"; const Sfr = "𝔖"; const ShortDownArrow = "↓"; const ShortLeftArrow = "←"; const ShortRightArrow = "→"; const ShortUpArrow = "↑"; const Sigma = "Σ"; const SmallCircle = "∘"; const Sopf = "𝕊"; const Sqrt = "√"; const Square = "□"; const SquareIntersection = "⊓"; const SquareSubset = "⊏"; const SquareSubsetEqual = "⊑"; const SquareSuperset = "⊐"; const SquareSupersetEqual = "⊒"; const SquareUnion = "⊔"; const Sscr = "𝒮"; const Star = "⋆"; const Sub = "⋐"; const Subset = "⋐"; const SubsetEqual = "⊆"; const Succeeds = "≻"; const SucceedsEqual = "⪰"; const SucceedsSlantEqual = "≽"; const SucceedsTilde = "≿"; const SuchThat = "∋"; const Sum = "∑"; const Sup = "⋑"; const Superset = "⊃"; const SupersetEqual = "⊇"; const Supset = "⋑"; const THOR = "Þ"; const THORN = "Þ"; const TRADE = "™"; const TSHcy = "Ћ"; const TScy = "Ц"; const Tab = "\t"; const Tau = "Τ"; const Tcaron = "Ť"; const Tcedil = "Ţ"; const Tcy = "Т"; const Tfr = "𝔗"; const Therefore = "∴"; const Theta = "Θ"; const ThickSpace = "  "; const ThinSpace = " "; const Tilde = "∼"; const TildeEqual = "≃"; const TildeFullEqual = "≅"; const TildeTilde = "≈"; const Topf = "𝕋"; const TripleDot = "⃛"; const Tscr = "𝒯"; const Tstrok = "Ŧ"; const Uacut = "Ú"; const Uacute = "Ú"; const Uarr = "↟"; const Uarrocir = "⥉"; const Ubrcy = "Ў"; const Ubreve = "Ŭ"; const Ucir = "Û"; const Ucirc = "Û"; const Ucy = "У"; const Udblac = "Ű"; const Ufr = "𝔘"; const Ugrav = "Ù"; const Ugrave = "Ù"; const Umacr = "Ū"; const UnderBar = "_"; const UnderBrace = "⏟"; const UnderBracket = "⎵"; const UnderParenthesis = "⏝"; const Union = "⋃"; const UnionPlus = "⊎"; const Uogon = "Ų"; const Uopf = "𝕌"; const UpArrow = "↑"; const UpArrowBar = "⤒"; const UpArrowDownArrow = "⇅"; const UpDownArrow = "↕"; const UpEquilibrium = "⥮"; const UpTee = "⊥"; const UpTeeArrow = "↥"; const Uparrow = "⇑"; const Updownarrow = "⇕"; const UpperLeftArrow = "↖"; const UpperRightArrow = "↗"; const Upsi = "ϒ"; const Upsilon = "Υ"; const Uring = "Ů"; const Uscr = "𝒰"; const Utilde = "Ũ"; const Uum = "Ü"; const Uuml = "Ü"; const VDash = "⊫"; const Vbar = "⫫"; const Vcy = "В"; const Vdash = "⊩"; const Vdashl = "⫦"; const Vee = "⋁"; const Verbar = "‖"; const Vert = "‖"; const VerticalBar = "∣"; const VerticalLine = "|"; const VerticalSeparator = "❘"; const VerticalTilde = "≀"; const VeryThinSpace = " "; const Vfr = "𝔙"; const Vopf = "𝕍"; const Vscr = "𝒱"; const Vvdash = "⊪"; const Wcirc = "Ŵ"; const Wedge = "⋀"; const Wfr = "𝔚"; const Wopf = "𝕎"; const Wscr = "𝒲"; const Xfr = "𝔛"; const Xi = "Ξ"; const Xopf = "𝕏"; const Xscr = "𝒳"; const YAcy = "Я"; const YIcy = "Ї"; const YUcy = "Ю"; const Yacut = "Ý"; const Yacute = "Ý"; const Ycirc = "Ŷ"; const Ycy = "Ы"; const Yfr = "𝔜"; const Yopf = "𝕐"; const Yscr = "𝒴"; const Yuml = "Ÿ"; const ZHcy = "Ж"; const Zacute = "Ź"; const Zcaron = "Ž"; const Zcy = "З"; const Zdot = "Ż"; const ZeroWidthSpace = "​"; const Zeta = "Ζ"; const Zfr = "ℨ"; const Zopf = "ℤ"; const Zscr = "𝒵"; const aacut = "á"; const aacute = "á"; const abreve = "ă"; const ac = "∾"; const acE = "∾̳"; const acd = "∿"; const acir = "â"; const acirc = "â"; const acut = "´"; const acute = "´"; const acy = "а"; const aeli = "æ"; const aelig = "æ"; const af = "⁡"; const afr = "𝔞"; const agrav = "à"; const agrave = "à"; const alefsym = "ℵ"; const aleph = "ℵ"; const alpha = "α"; const amacr = "ā"; const amalg = "⨿"; const am = "&"; const amp = "&"; const and = "∧"; const andand = "⩕"; const andd = "⩜"; const andslope = "⩘"; const andv = "⩚"; const ang = "∠"; const ange = "⦤"; const angle = "∠"; const angmsd = "∡"; const angmsdaa = "⦨"; const angmsdab = "⦩"; const angmsdac = "⦪"; const angmsdad = "⦫"; const angmsdae = "⦬"; const angmsdaf = "⦭"; const angmsdag = "⦮"; const angmsdah = "⦯"; const angrt = "∟"; const angrtvb = "⊾"; const angrtvbd = "⦝"; const angsph = "∢"; const angst = "Å"; const angzarr = "⍼"; const aogon = "ą"; const aopf = "𝕒"; const ap = "≈"; const apE = "⩰"; const apacir = "⩯"; const ape = "≊"; const apid = "≋"; const apos = "'"; const approx = "≈"; const approxeq = "≊"; const arin = "å"; const aring = "å"; const ascr = "𝒶"; const ast = "*"; const asymp = "≈"; const asympeq = "≍"; const atild = "ã"; const atilde = "ã"; const aum = "ä"; const auml = "ä"; const awconint = "∳"; const awint = "⨑"; const bNot = "⫭"; const backcong = "≌"; const backepsilon = "϶"; const backprime = "‵"; const backsim = "∽"; const backsimeq = "⋍"; const barvee = "⊽"; const barwed = "⌅"; const barwedge = "⌅"; const bbrk = "⎵"; const bbrktbrk = "⎶"; const bcong = "≌"; const bcy = "б"; const bdquo = "„"; const becaus = "∵"; const because = "∵"; const bemptyv = "⦰"; const bepsi = "϶"; const bernou = "ℬ"; const beta = "β"; const beth = "ℶ"; const between = "≬"; const bfr = "𝔟"; const bigcap = "⋂"; const bigcirc = "◯"; const bigcup = "⋃"; const bigodot = "⨀"; const bigoplus = "⨁"; const bigotimes = "⨂"; const bigsqcup = "⨆"; const bigstar = "★"; const bigtriangledown = "▽"; const bigtriangleup = "△"; const biguplus = "⨄"; const bigvee = "⋁"; const bigwedge = "⋀"; const bkarow = "⤍"; const blacklozenge = "⧫"; const blacksquare = "▪"; const blacktriangle = "▴"; const blacktriangledown = "▾"; const blacktriangleleft = "◂"; const blacktriangleright = "▸"; const blank = "␣"; const blk12 = "▒"; const blk14 = "░"; const blk34 = "▓"; const block = "█"; const bne = "=⃥"; const bnequiv = "≡⃥"; const bnot = "⌐"; const bopf = "𝕓"; const bot = "⊥"; const bottom = "⊥"; const bowtie = "⋈"; const boxDL = "╗"; const boxDR = "╔"; const boxDl = "╖"; const boxDr = "╓"; const boxH = "═"; const boxHD = "╦"; const boxHU = "╩"; const boxHd = "╤"; const boxHu = "╧"; const boxUL = "╝"; const boxUR = "╚"; const boxUl = "╜"; const boxUr = "╙"; const boxV = "║"; const boxVH = "╬"; const boxVL = "╣"; const boxVR = "╠"; const boxVh = "╫"; const boxVl = "╢"; const boxVr = "╟"; const boxbox = "⧉"; const boxdL = "╕"; const boxdR = "╒"; const boxdl = "┐"; const boxdr = "┌"; const boxh = "─"; const boxhD = "╥"; const boxhU = "╨"; const boxhd = "┬"; const boxhu = "┴"; const boxminus = "⊟"; const boxplus = "⊞"; const boxtimes = "⊠"; const boxuL = "╛"; const boxuR = "╘"; const boxul = "┘"; const boxur = "└"; const boxv = "│"; const boxvH = "╪"; const boxvL = "╡"; const boxvR = "╞"; const boxvh = "┼"; const boxvl = "┤"; const boxvr = "├"; const bprime = "‵"; const breve = "˘"; const brvba = "¦"; const brvbar = "¦"; const bscr = "𝒷"; const bsemi = "⁏"; const bsim = "∽"; const bsime = "⋍"; const bsol = "\\"; const bsolb = "⧅"; const bsolhsub = "⟈"; const bull = "•"; const bullet = "•"; const bump = "≎"; const bumpE = "⪮"; const bumpe = "≏"; const bumpeq = "≏"; const cacute = "ć"; const cap = "∩"; const capand = "⩄"; const capbrcup = "⩉"; const capcap = "⩋"; const capcup = "⩇"; const capdot = "⩀"; const caps = "∩︀"; const caret = "⁁"; const caron = "ˇ"; const ccaps = "⩍"; const ccaron = "č"; const ccedi = "ç"; const ccedil = "ç"; const ccirc = "ĉ"; const ccups = "⩌"; const ccupssm = "⩐"; const cdot = "ċ"; const cedi = "¸"; const cedil = "¸"; const cemptyv = "⦲"; const cen = "¢"; const cent = "¢"; const centerdot = "·"; const cfr = "𝔠"; const chcy = "ч"; const check$2 = "✓"; const checkmark = "✓"; const chi = "χ"; const cir = "○"; const cirE = "⧃"; const circ = "ˆ"; const circeq = "≗"; const circlearrowleft = "↺"; const circlearrowright = "↻"; const circledR = "®"; const circledS = "Ⓢ"; const circledast = "⊛"; const circledcirc = "⊚"; const circleddash = "⊝"; const cire = "≗"; const cirfnint = "⨐"; const cirmid = "⫯"; const cirscir = "⧂"; const clubs = "♣"; const clubsuit = "♣"; const colon = ":"; const colone = "≔"; const coloneq = "≔"; const comma = ","; const commat = "@"; const comp = "∁"; const compfn = "∘"; const complement = "∁"; const complexes = "ℂ"; const cong = "≅"; const congdot = "⩭"; const conint = "∮"; const copf = "𝕔"; const coprod = "∐"; const cop = "©"; const copy$1 = "©"; const copysr = "℗"; const crarr = "↵"; const cross = "✗"; const cscr = "𝒸"; const csub = "⫏"; const csube = "⫑"; const csup = "⫐"; const csupe = "⫒"; const ctdot = "⋯"; const cudarrl = "⤸"; const cudarrr = "⤵"; const cuepr = "⋞"; const cuesc = "⋟"; const cularr = "↶"; const cularrp = "⤽"; const cup = "∪"; const cupbrcap = "⩈"; const cupcap = "⩆"; const cupcup = "⩊"; const cupdot = "⊍"; const cupor = "⩅"; const cups = "∪︀"; const curarr = "↷"; const curarrm = "⤼"; const curlyeqprec = "⋞"; const curlyeqsucc = "⋟"; const curlyvee = "⋎"; const curlywedge = "⋏"; const curre = "¤"; const curren = "¤"; const curvearrowleft = "↶"; const curvearrowright = "↷"; const cuvee = "⋎"; const cuwed = "⋏"; const cwconint = "∲"; const cwint = "∱"; const cylcty = "⌭"; const dArr = "⇓"; const dHar = "⥥"; const dagger = "†"; const daleth = "ℸ"; const darr = "↓"; const dash = "‐"; const dashv = "⊣"; const dbkarow = "⤏"; const dblac = "˝"; const dcaron = "ď"; const dcy = "д"; const dd = "ⅆ"; const ddagger = "‡"; const ddarr = "⇊"; const ddotseq = "⩷"; const de = "°"; const deg = "°"; const delta = "δ"; const demptyv = "⦱"; const dfisht = "⥿"; const dfr = "𝔡"; const dharl = "⇃"; const dharr = "⇂"; const diam = "⋄"; const diamond = "⋄"; const diamondsuit = "♦"; const diams = "♦"; const die = "¨"; const digamma = "ϝ"; const disin = "⋲"; const div = "÷"; const divid = "÷"; const divide = "÷"; const divideontimes = "⋇"; const divonx = "⋇"; const djcy = "ђ"; const dlcorn = "⌞"; const dlcrop = "⌍"; const dollar = "$"; const dopf = "𝕕"; const dot = "˙"; const doteq = "≐"; const doteqdot = "≑"; const dotminus = "∸"; const dotplus = "∔"; const dotsquare = "⊡"; const doublebarwedge = "⌆"; const downarrow = "↓"; const downdownarrows = "⇊"; const downharpoonleft = "⇃"; const downharpoonright = "⇂"; const drbkarow = "⤐"; const drcorn = "⌟"; const drcrop = "⌌"; const dscr = "𝒹"; const dscy = "ѕ"; const dsol = "⧶"; const dstrok = "đ"; const dtdot = "⋱"; const dtri = "▿"; const dtrif = "▾"; const duarr = "⇵"; const duhar = "⥯"; const dwangle = "⦦"; const dzcy = "џ"; const dzigrarr = "⟿"; const eDDot = "⩷"; const eDot = "≑"; const eacut = "é"; const eacute = "é"; const easter = "⩮"; const ecaron = "ě"; const ecir = "ê"; const ecirc = "ê"; const ecolon = "≕"; const ecy = "э"; const edot = "ė"; const ee = "ⅇ"; const efDot = "≒"; const efr = "𝔢"; const eg = "⪚"; const egrav = "è"; const egrave = "è"; const egs = "⪖"; const egsdot = "⪘"; const el = "⪙"; const elinters = "⏧"; const ell = "ℓ"; const els = "⪕"; const elsdot = "⪗"; const emacr = "ē"; const empty = "∅"; const emptyset = "∅"; const emptyv = "∅"; const emsp13 = " "; const emsp14 = " "; const emsp = " "; const eng = "ŋ"; const ensp = " "; const eogon = "ę"; const eopf = "𝕖"; const epar = "⋕"; const eparsl = "⧣"; const eplus = "⩱"; const epsi = "ε"; const epsilon = "ε"; const epsiv = "ϵ"; const eqcirc = "≖"; const eqcolon = "≕"; const eqsim = "≂"; const eqslantgtr = "⪖"; const eqslantless = "⪕"; const equals = "="; const equest = "≟"; const equiv = "≡"; const equivDD = "⩸"; const eqvparsl = "⧥"; const erDot = "≓"; const erarr = "⥱"; const escr = "ℯ"; const esdot = "≐"; const esim = "≂"; const eta = "η"; const et = "ð"; const eth = "ð"; const eum = "ë"; const euml = "ë"; const euro = "€"; const excl = "!"; const exist = "∃"; const expectation = "ℰ"; const exponentiale = "ⅇ"; const fallingdotseq = "≒"; const fcy = "ф"; const female = "♀"; const ffilig = "ffi"; const fflig = "ff"; const ffllig = "ffl"; const ffr = "𝔣"; const filig = "fi"; const fjlig = "fj"; const flat = "♭"; const fllig = "fl"; const fltns = "▱"; const fnof = "ƒ"; const fopf = "𝕗"; const forall = "∀"; const fork = "⋔"; const forkv = "⫙"; const fpartint = "⨍"; const frac1 = "¼"; const frac12 = "½"; const frac13 = "⅓"; const frac14 = "¼"; const frac15 = "⅕"; const frac16 = "⅙"; const frac18 = "⅛"; const frac23 = "⅔"; const frac25 = "⅖"; const frac3 = "¾"; const frac34 = "¾"; const frac35 = "⅗"; const frac38 = "⅜"; const frac45 = "⅘"; const frac56 = "⅚"; const frac58 = "⅝"; const frac78 = "⅞"; const frasl = "⁄"; const frown = "⌢"; const fscr = "𝒻"; const gE = "≧"; const gEl = "⪌"; const gacute = "ǵ"; const gamma = "γ"; const gammad = "ϝ"; const gap = "⪆"; const gbreve = "ğ"; const gcirc = "ĝ"; const gcy = "г"; const gdot = "ġ"; const ge = "≥"; const gel = "⋛"; const geq = "≥"; const geqq = "≧"; const geqslant = "⩾"; const ges = "⩾"; const gescc = "⪩"; const gesdot = "⪀"; const gesdoto = "⪂"; const gesdotol = "⪄"; const gesl = "⋛︀"; const gesles = "⪔"; const gfr = "𝔤"; const gg = "≫"; const ggg = "⋙"; const gimel = "ℷ"; const gjcy = "ѓ"; const gl = "≷"; const glE = "⪒"; const gla = "⪥"; const glj = "⪤"; const gnE = "≩"; const gnap = "⪊"; const gnapprox = "⪊"; const gne = "⪈"; const gneq = "⪈"; const gneqq = "≩"; const gnsim = "⋧"; const gopf = "𝕘"; const grave = "`"; const gscr = "ℊ"; const gsim = "≳"; const gsime = "⪎"; const gsiml = "⪐"; const g = ">"; const gt = ">"; const gtcc = "⪧"; const gtcir = "⩺"; const gtdot = "⋗"; const gtlPar = "⦕"; const gtquest = "⩼"; const gtrapprox = "⪆"; const gtrarr = "⥸"; const gtrdot = "⋗"; const gtreqless = "⋛"; const gtreqqless = "⪌"; const gtrless = "≷"; const gtrsim = "≳"; const gvertneqq = "≩︀"; const gvnE = "≩︀"; const hArr = "⇔"; const hairsp = " "; const half = "½"; const hamilt = "ℋ"; const hardcy = "ъ"; const harr = "↔"; const harrcir = "⥈"; const harrw = "↭"; const hbar = "ℏ"; const hcirc = "ĥ"; const hearts = "♥"; const heartsuit = "♥"; const hellip = "…"; const hercon = "⊹"; const hfr = "𝔥"; const hksearow = "⤥"; const hkswarow = "⤦"; const hoarr = "⇿"; const homtht = "∻"; const hookleftarrow = "↩"; const hookrightarrow = "↪"; const hopf = "𝕙"; const horbar = "―"; const hscr = "𝒽"; const hslash = "ℏ"; const hstrok = "ħ"; const hybull = "⁃"; const hyphen = "‐"; const iacut = "í"; const iacute = "í"; const ic = "⁣"; const icir = "î"; const icirc = "î"; const icy = "и"; const iecy = "е"; const iexc = "¡"; const iexcl = "¡"; const iff = "⇔"; const ifr = "𝔦"; const igrav = "ì"; const igrave = "ì"; const ii = "ⅈ"; const iiiint = "⨌"; const iiint = "∭"; const iinfin = "⧜"; const iiota = "℩"; const ijlig = "ij"; const imacr = "ī"; const image = "ℑ"; const imagline = "ℐ"; const imagpart = "ℑ"; const imath = "ı"; const imof = "⊷"; const imped = "Ƶ"; const incare = "℅"; const infin = "∞"; const infintie = "⧝"; const inodot = "ı"; const int = "∫"; const intcal = "⊺"; const integers = "ℤ"; const intercal = "⊺"; const intlarhk = "⨗"; const intprod = "⨼"; const iocy = "ё"; const iogon = "į"; const iopf = "𝕚"; const iota = "ι"; const iprod = "⨼"; const iques = "¿"; const iquest = "¿"; const iscr = "𝒾"; const isin = "∈"; const isinE = "⋹"; const isindot = "⋵"; const isins = "⋴"; const isinsv = "⋳"; const isinv = "∈"; const it = "⁢"; const itilde = "ĩ"; const iukcy = "і"; const ium = "ï"; const iuml = "ï"; const jcirc = "ĵ"; const jcy = "й"; const jfr = "𝔧"; const jmath = "ȷ"; const jopf = "𝕛"; const jscr = "𝒿"; const jsercy = "ј"; const jukcy = "є"; const kappa = "κ"; const kappav = "ϰ"; const kcedil = "ķ"; const kcy = "к"; const kfr = "𝔨"; const kgreen = "ĸ"; const khcy = "х"; const kjcy = "ќ"; const kopf = "𝕜"; const kscr = "𝓀"; const lAarr = "⇚"; const lArr = "⇐"; const lAtail = "⤛"; const lBarr = "⤎"; const lE = "≦"; const lEg = "⪋"; const lHar = "⥢"; const lacute = "ĺ"; const laemptyv = "⦴"; const lagran = "ℒ"; const lambda = "λ"; const lang = "⟨"; const langd = "⦑"; const langle = "⟨"; const lap = "⪅"; const laqu = "«"; const laquo = "«"; const larr = "←"; const larrb = "⇤"; const larrbfs = "⤟"; const larrfs = "⤝"; const larrhk = "↩"; const larrlp = "↫"; const larrpl = "⤹"; const larrsim = "⥳"; const larrtl = "↢"; const lat = "⪫"; const latail = "⤙"; const late = "⪭"; const lates = "⪭︀"; const lbarr = "⤌"; const lbbrk = "❲"; const lbrace = "{"; const lbrack = "["; const lbrke = "⦋"; const lbrksld = "⦏"; const lbrkslu = "⦍"; const lcaron = "ľ"; const lcedil = "ļ"; const lceil = "⌈"; const lcub = "{"; const lcy = "л"; const ldca = "⤶"; const ldquo = "“"; const ldquor = "„"; const ldrdhar = "⥧"; const ldrushar = "⥋"; const ldsh = "↲"; const le = "≤"; const leftarrow = "←"; const leftarrowtail = "↢"; const leftharpoondown = "↽"; const leftharpoonup = "↼"; const leftleftarrows = "⇇"; const leftrightarrow = "↔"; const leftrightarrows = "⇆"; const leftrightharpoons = "⇋"; const leftrightsquigarrow = "↭"; const leftthreetimes = "⋋"; const leg = "⋚"; const leq = "≤"; const leqq = "≦"; const leqslant = "⩽"; const les = "⩽"; const lescc = "⪨"; const lesdot = "⩿"; const lesdoto = "⪁"; const lesdotor = "⪃"; const lesg = "⋚︀"; const lesges = "⪓"; const lessapprox = "⪅"; const lessdot = "⋖"; const lesseqgtr = "⋚"; const lesseqqgtr = "⪋"; const lessgtr = "≶"; const lesssim = "≲"; const lfisht = "⥼"; const lfloor = "⌊"; const lfr = "𝔩"; const lg = "≶"; const lgE = "⪑"; const lhard = "↽"; const lharu = "↼"; const lharul = "⥪"; const lhblk = "▄"; const ljcy = "љ"; const ll = "≪"; const llarr = "⇇"; const llcorner = "⌞"; const llhard = "⥫"; const lltri = "◺"; const lmidot = "ŀ"; const lmoust = "⎰"; const lmoustache = "⎰"; const lnE = "≨"; const lnap = "⪉"; const lnapprox = "⪉"; const lne = "⪇"; const lneq = "⪇"; const lneqq = "≨"; const lnsim = "⋦"; const loang = "⟬"; const loarr = "⇽"; const lobrk = "⟦"; const longleftarrow = "⟵"; const longleftrightarrow = "⟷"; const longmapsto = "⟼"; const longrightarrow = "⟶"; const looparrowleft = "↫"; const looparrowright = "↬"; const lopar = "⦅"; const lopf = "𝕝"; const loplus = "⨭"; const lotimes = "⨴"; const lowast = "∗"; const lowbar = "_"; const loz = "◊"; const lozenge = "◊"; const lozf = "⧫"; const lpar = "("; const lparlt = "⦓"; const lrarr = "⇆"; const lrcorner = "⌟"; const lrhar = "⇋"; const lrhard = "⥭"; const lrm = "‎"; const lrtri = "⊿"; const lsaquo = "‹"; const lscr = "𝓁"; const lsh = "↰"; const lsim = "≲"; const lsime = "⪍"; const lsimg = "⪏"; const lsqb = "["; const lsquo = "‘"; const lsquor = "‚"; const lstrok = "ł"; const l = "<"; const lt = "<"; const ltcc = "⪦"; const ltcir = "⩹"; const ltdot = "⋖"; const lthree = "⋋"; const ltimes = "⋉"; const ltlarr = "⥶"; const ltquest = "⩻"; const ltrPar = "⦖"; const ltri = "◃"; const ltrie = "⊴"; const ltrif = "◂"; const lurdshar = "⥊"; const luruhar = "⥦"; const lvertneqq = "≨︀"; const lvnE = "≨︀"; const mDDot = "∺"; const mac = "¯"; const macr = "¯"; const male = "♂"; const malt = "✠"; const maltese = "✠"; const map$2 = "↦"; const mapsto = "↦"; const mapstodown = "↧"; const mapstoleft = "↤"; const mapstoup = "↥"; const marker = "▮"; const mcomma = "⨩"; const mcy = "м"; const mdash = "—"; const measuredangle = "∡"; const mfr = "𝔪"; const mho = "℧"; const micr = "µ"; const micro = "µ"; const mid = "∣"; const midast = "*"; const midcir = "⫰"; const middo = "·"; const middot = "·"; const minus = "−"; const minusb = "⊟"; const minusd = "∸"; const minusdu = "⨪"; const mlcp = "⫛"; const mldr = "…"; const mnplus = "∓"; const models$2 = "⊧"; const mopf = "𝕞"; const mp = "∓"; const mscr = "𝓂"; const mstpos = "∾"; const mu = "μ"; const multimap = "⊸"; const mumap = "⊸"; const nGg = "⋙̸"; const nGt = "≫⃒"; const nGtv = "≫̸"; const nLeftarrow = "⇍"; const nLeftrightarrow = "⇎"; const nLl = "⋘̸"; const nLt = "≪⃒"; const nLtv = "≪̸"; const nRightarrow = "⇏"; const nVDash = "⊯"; const nVdash = "⊮"; const nabla = "∇"; const nacute = "ń"; const nang = "∠⃒"; const nap = "≉"; const napE = "⩰̸"; const napid = "≋̸"; const napos = "ʼn"; const napprox = "≉"; const natur = "♮"; const natural = "♮"; const naturals = "ℕ"; const nbs = " "; const nbsp = " "; const nbump = "≎̸"; const nbumpe = "≏̸"; const ncap = "⩃"; const ncaron = "ň"; const ncedil = "ņ"; const ncong = "≇"; const ncongdot = "⩭̸"; const ncup = "⩂"; const ncy = "н"; const ndash = "–"; const ne = "≠"; const neArr = "⇗"; const nearhk = "⤤"; const nearr = "↗"; const nearrow = "↗"; const nedot = "≐̸"; const nequiv = "≢"; const nesear = "⤨"; const nesim = "≂̸"; const nexist = "∄"; const nexists = "∄"; const nfr = "𝔫"; const ngE = "≧̸"; const nge = "≱"; const ngeq = "≱"; const ngeqq = "≧̸"; const ngeqslant = "⩾̸"; const nges = "⩾̸"; const ngsim = "≵"; const ngt = "≯"; const ngtr = "≯"; const nhArr = "⇎"; const nharr = "↮"; const nhpar = "⫲"; const ni = "∋"; const nis = "⋼"; const nisd = "⋺"; const niv = "∋"; const njcy = "њ"; const nlArr = "⇍"; const nlE = "≦̸"; const nlarr = "↚"; const nldr = "‥"; const nle = "≰"; const nleftarrow = "↚"; const nleftrightarrow = "↮"; const nleq = "≰"; const nleqq = "≦̸"; const nleqslant = "⩽̸"; const nles = "⩽̸"; const nless = "≮"; const nlsim = "≴"; const nlt = "≮"; const nltri = "⋪"; const nltrie = "⋬"; const nmid = "∤"; const nopf = "𝕟"; const no = "¬"; const not = "¬"; const notin = "∉"; const notinE = "⋹̸"; const notindot = "⋵̸"; const notinva = "∉"; const notinvb = "⋷"; const notinvc = "⋶"; const notni = "∌"; const notniva = "∌"; const notnivb = "⋾"; const notnivc = "⋽"; const npar = "∦"; const nparallel = "∦"; const nparsl = "⫽⃥"; const npart = "∂̸"; const npolint = "⨔"; const npr = "⊀"; const nprcue = "⋠"; const npre = "⪯̸"; const nprec = "⊀"; const npreceq = "⪯̸"; const nrArr = "⇏"; const nrarr = "↛"; const nrarrc = "⤳̸"; const nrarrw = "↝̸"; const nrightarrow = "↛"; const nrtri = "⋫"; const nrtrie = "⋭"; const nsc = "⊁"; const nsccue = "⋡"; const nsce = "⪰̸"; const nscr = "𝓃"; const nshortmid = "∤"; const nshortparallel = "∦"; const nsim = "≁"; const nsime = "≄"; const nsimeq = "≄"; const nsmid = "∤"; const nspar = "∦"; const nsqsube = "⋢"; const nsqsupe = "⋣"; const nsub = "⊄"; const nsubE = "⫅̸"; const nsube = "⊈"; const nsubset = "⊂⃒"; const nsubseteq = "⊈"; const nsubseteqq = "⫅̸"; const nsucc = "⊁"; const nsucceq = "⪰̸"; const nsup = "⊅"; const nsupE = "⫆̸"; const nsupe = "⊉"; const nsupset = "⊃⃒"; const nsupseteq = "⊉"; const nsupseteqq = "⫆̸"; const ntgl = "≹"; const ntild = "ñ"; const ntilde = "ñ"; const ntlg = "≸"; const ntriangleleft = "⋪"; const ntrianglelefteq = "⋬"; const ntriangleright = "⋫"; const ntrianglerighteq = "⋭"; const nu = "ν"; const num = "#"; const numero = "№"; const numsp = " "; const nvDash = "⊭"; const nvHarr = "⤄"; const nvap = "≍⃒"; const nvdash = "⊬"; const nvge = "≥⃒"; const nvgt = ">⃒"; const nvinfin = "⧞"; const nvlArr = "⤂"; const nvle = "≤⃒"; const nvlt = "<⃒"; const nvltrie = "⊴⃒"; const nvrArr = "⤃"; const nvrtrie = "⊵⃒"; const nvsim = "∼⃒"; const nwArr = "⇖"; const nwarhk = "⤣"; const nwarr = "↖"; const nwarrow = "↖"; const nwnear = "⤧"; const oS = "Ⓢ"; const oacut = "ó"; const oacute = "ó"; const oast = "⊛"; const ocir = "ô"; const ocirc = "ô"; const ocy = "о"; const odash = "⊝"; const odblac = "ő"; const odiv = "⨸"; const odot = "⊙"; const odsold = "⦼"; const oelig = "œ"; const ofcir = "⦿"; const ofr = "𝔬"; const ogon = "˛"; const ograv = "ò"; const ograve = "ò"; const ogt = "⧁"; const ohbar = "⦵"; const ohm = "Ω"; const oint = "∮"; const olarr = "↺"; const olcir = "⦾"; const olcross = "⦻"; const oline = "‾"; const olt = "⧀"; const omacr = "ō"; const omega = "ω"; const omicron = "ο"; const omid = "⦶"; const ominus = "⊖"; const oopf = "𝕠"; const opar = "⦷"; const operp = "⦹"; const oplus = "⊕"; const or = "∨"; const orarr = "↻"; const ord = "º"; const order$1 = "ℴ"; const orderof = "ℴ"; const ordf = "ª"; const ordm = "º"; const origof = "⊶"; const oror = "⩖"; const orslope = "⩗"; const orv = "⩛"; const oscr = "ℴ"; const oslas = "ø"; const oslash = "ø"; const osol = "⊘"; const otild = "õ"; const otilde = "õ"; const otimes = "⊗"; const otimesas = "⨶"; const oum = "ö"; const ouml = "ö"; const ovbar = "⌽"; const par = "¶"; const para = "¶"; const parallel = "∥"; const parsim = "⫳"; const parsl = "⫽"; const part = "∂"; const pcy = "п"; const percnt = "%"; const period = "."; const permil = "‰"; const perp = "⊥"; const pertenk = "‱"; const pfr = "𝔭"; const phi = "φ"; const phiv = "ϕ"; const phmmat = "ℳ"; const phone = "☎"; const pi = "π"; const pitchfork = "⋔"; const piv = "ϖ"; const planck = "ℏ"; const planckh = "ℎ"; const plankv = "ℏ"; const plus = "+"; const plusacir = "⨣"; const plusb = "⊞"; const pluscir = "⨢"; const plusdo = "∔"; const plusdu = "⨥"; const pluse = "⩲"; const plusm = "±"; const plusmn = "±"; const plussim = "⨦"; const plustwo = "⨧"; const pm = "±"; const pointint = "⨕"; const popf = "𝕡"; const poun = "£"; const pound = "£"; const pr = "≺"; const prE = "⪳"; const prap = "⪷"; const prcue = "≼"; const pre = "⪯"; const prec = "≺"; const precapprox = "⪷"; const preccurlyeq = "≼"; const preceq = "⪯"; const precnapprox = "⪹"; const precneqq = "⪵"; const precnsim = "⋨"; const precsim = "≾"; const prime = "′"; const primes = "ℙ"; const prnE = "⪵"; const prnap = "⪹"; const prnsim = "⋨"; const prod = "∏"; const profalar = "⌮"; const profline = "⌒"; const profsurf = "⌓"; const prop = "∝"; const propto = "∝"; const prsim = "≾"; const prurel = "⊰"; const pscr = "𝓅"; const psi = "ψ"; const puncsp = " "; const qfr = "𝔮"; const qint = "⨌"; const qopf = "𝕢"; const qprime = "⁗"; const qscr = "𝓆"; const quaternions = "ℍ"; const quatint = "⨖"; const quest = "?"; const questeq = "≟"; const quo = "\""; const quot = "\""; const rAarr = "⇛"; const rArr = "⇒"; const rAtail = "⤜"; const rBarr = "⤏"; const rHar = "⥤"; const race = "∽̱"; const racute = "ŕ"; const radic = "√"; const raemptyv = "⦳"; const rang = "⟩"; const rangd = "⦒"; const range$1 = "⦥"; const rangle = "⟩"; const raqu = "»"; const raquo = "»"; const rarr = "→"; const rarrap = "⥵"; const rarrb = "⇥"; const rarrbfs = "⤠"; const rarrc = "⤳"; const rarrfs = "⤞"; const rarrhk = "↪"; const rarrlp = "↬"; const rarrpl = "⥅"; const rarrsim = "⥴"; const rarrtl = "↣"; const rarrw = "↝"; const ratail = "⤚"; const ratio = "∶"; const rationals = "ℚ"; const rbarr = "⤍"; const rbbrk = "❳"; const rbrace = "}"; const rbrack = "]"; const rbrke = "⦌"; const rbrksld = "⦎"; const rbrkslu = "⦐"; const rcaron = "ř"; const rcedil = "ŗ"; const rceil = "⌉"; const rcub = "}"; const rcy = "р"; const rdca = "⤷"; const rdldhar = "⥩"; const rdquo = "”"; const rdquor = "”"; const rdsh = "↳"; const real = "ℜ"; const realine = "ℛ"; const realpart = "ℜ"; const reals = "ℝ"; const rect = "▭"; const re = "®"; const reg = "®"; const rfisht = "⥽"; const rfloor = "⌋"; const rfr = "𝔯"; const rhard = "⇁"; const rharu = "⇀"; const rharul = "⥬"; const rho = "ρ"; const rhov = "ϱ"; const rightarrow = "→"; const rightarrowtail = "↣"; const rightharpoondown = "⇁"; const rightharpoonup = "⇀"; const rightleftarrows = "⇄"; const rightleftharpoons = "⇌"; const rightrightarrows = "⇉"; const rightsquigarrow = "↝"; const rightthreetimes = "⋌"; const ring = "˚"; const risingdotseq = "≓"; const rlarr = "⇄"; const rlhar = "⇌"; const rlm = "‏"; const rmoust = "⎱"; const rmoustache = "⎱"; const rnmid = "⫮"; const roang = "⟭"; const roarr = "⇾"; const robrk = "⟧"; const ropar = "⦆"; const ropf = "𝕣"; const roplus = "⨮"; const rotimes = "⨵"; const rpar = ")"; const rpargt = "⦔"; const rppolint = "⨒"; const rrarr = "⇉"; const rsaquo = "›"; const rscr = "𝓇"; const rsh = "↱"; const rsqb = "]"; const rsquo = "’"; const rsquor = "’"; const rthree = "⋌"; const rtimes = "⋊"; const rtri = "▹"; const rtrie = "⊵"; const rtrif = "▸"; const rtriltri = "⧎"; const ruluhar = "⥨"; const rx = "℞"; const sacute = "ś"; const sbquo = "‚"; const sc = "≻"; const scE = "⪴"; const scap = "⪸"; const scaron = "š"; const sccue = "≽"; const sce = "⪰"; const scedil = "ş"; const scirc = "ŝ"; const scnE = "⪶"; const scnap = "⪺"; const scnsim = "⋩"; const scpolint = "⨓"; const scsim = "≿"; const scy = "с"; const sdot = "⋅"; const sdotb = "⊡"; const sdote = "⩦"; const seArr = "⇘"; const searhk = "⤥"; const searr = "↘"; const searrow = "↘"; const sec = "§"; const sect = "§"; const semi = ";"; const seswar = "⤩"; const setminus = "∖"; const setmn = "∖"; const sext = "✶"; const sfr = "𝔰"; const sfrown = "⌢"; const sharp = "♯"; const shchcy = "щ"; const shcy = "ш"; const shortmid = "∣"; const shortparallel = "∥"; const sh = "­"; const shy = "­"; const sigma = "σ"; const sigmaf = "ς"; const sigmav = "ς"; const sim = "∼"; const simdot = "⩪"; const sime = "≃"; const simeq = "≃"; const simg = "⪞"; const simgE = "⪠"; const siml = "⪝"; const simlE = "⪟"; const simne = "≆"; const simplus = "⨤"; const simrarr = "⥲"; const slarr = "←"; const smallsetminus = "∖"; const smashp = "⨳"; const smeparsl = "⧤"; const smid = "∣"; const smile = "⌣"; const smt = "⪪"; const smte = "⪬"; const smtes = "⪬︀"; const softcy = "ь"; const sol = "/"; const solb = "⧄"; const solbar = "⌿"; const sopf = "𝕤"; const spades = "♠"; const spadesuit = "♠"; const spar = "∥"; const sqcap = "⊓"; const sqcaps = "⊓︀"; const sqcup = "⊔"; const sqcups = "⊔︀"; const sqsub = "⊏"; const sqsube = "⊑"; const sqsubset = "⊏"; const sqsubseteq = "⊑"; const sqsup = "⊐"; const sqsupe = "⊒"; const sqsupset = "⊐"; const sqsupseteq = "⊒"; const squ = "□"; const square = "□"; const squarf = "▪"; const squf = "▪"; const srarr = "→"; const sscr = "𝓈"; const ssetmn = "∖"; const ssmile = "⌣"; const sstarf = "⋆"; const star$1 = "☆"; const starf = "★"; const straightepsilon = "ϵ"; const straightphi = "ϕ"; const strns = "¯"; const sub = "⊂"; const subE = "⫅"; const subdot = "⪽"; const sube = "⊆"; const subedot = "⫃"; const submult = "⫁"; const subnE = "⫋"; const subne = "⊊"; const subplus = "⪿"; const subrarr = "⥹"; const subset = "⊂"; const subseteq = "⊆"; const subseteqq = "⫅"; const subsetneq = "⊊"; const subsetneqq = "⫋"; const subsim = "⫇"; const subsub = "⫕"; const subsup = "⫓"; const succ = "≻"; const succapprox = "⪸"; const succcurlyeq = "≽"; const succeq = "⪰"; const succnapprox = "⪺"; const succneqq = "⪶"; const succnsim = "⋩"; const succsim = "≿"; const sum = "∑"; const sung = "♪"; const sup = "⊃"; const sup1 = "¹"; const sup2 = "²"; const sup3 = "³"; const supE = "⫆"; const supdot = "⪾"; const supdsub = "⫘"; const supe = "⊇"; const supedot = "⫄"; const suphsol = "⟉"; const suphsub = "⫗"; const suplarr = "⥻"; const supmult = "⫂"; const supnE = "⫌"; const supne = "⊋"; const supplus = "⫀"; const supset = "⊃"; const supseteq = "⊇"; const supseteqq = "⫆"; const supsetneq = "⊋"; const supsetneqq = "⫌"; const supsim = "⫈"; const supsub = "⫔"; const supsup = "⫖"; const swArr = "⇙"; const swarhk = "⤦"; const swarr = "↙"; const swarrow = "↙"; const swnwar = "⤪"; const szli = "ß"; const szlig = "ß"; const target = "⌖"; const tau = "τ"; const tbrk = "⎴"; const tcaron = "ť"; const tcedil = "ţ"; const tcy = "т"; const tdot = "⃛"; const telrec = "⌕"; const tfr = "𝔱"; const there4 = "∴"; const therefore = "∴"; const theta = "θ"; const thetasym = "ϑ"; const thetav = "ϑ"; const thickapprox = "≈"; const thicksim = "∼"; const thinsp = " "; const thkap = "≈"; const thksim = "∼"; const thor = "þ"; const thorn = "þ"; const tilde = "˜"; const time = "×"; const times = "×"; const timesb = "⊠"; const timesbar = "⨱"; const timesd = "⨰"; const tint = "∭"; const toea = "⤨"; const top = "⊤"; const topbot = "⌶"; const topcir = "⫱"; const topf = "𝕥"; const topfork = "⫚"; const tosa = "⤩"; const tprime = "‴"; const trade = "™"; const triangle = "▵"; const triangledown = "▿"; const triangleleft = "◃"; const trianglelefteq = "⊴"; const triangleq = "≜"; const triangleright = "▹"; const trianglerighteq = "⊵"; const tridot = "◬"; const trie = "≜"; const triminus = "⨺"; const triplus = "⨹"; const trisb = "⧍"; const tritime = "⨻"; const trpezium = "⏢"; const tscr = "𝓉"; const tscy = "ц"; const tshcy = "ћ"; const tstrok = "ŧ"; const twixt = "≬"; const twoheadleftarrow = "↞"; const twoheadrightarrow = "↠"; const uArr = "⇑"; const uHar = "⥣"; const uacut = "ú"; const uacute = "ú"; const uarr = "↑"; const ubrcy = "ў"; const ubreve = "ŭ"; const ucir = "û"; const ucirc = "û"; const ucy = "у"; const udarr = "⇅"; const udblac = "ű"; const udhar = "⥮"; const ufisht = "⥾"; const ufr = "𝔲"; const ugrav = "ù"; const ugrave = "ù"; const uharl = "↿"; const uharr = "↾"; const uhblk = "▀"; const ulcorn = "⌜"; const ulcorner = "⌜"; const ulcrop = "⌏"; const ultri = "◸"; const umacr = "ū"; const um = "¨"; const uml = "¨"; const uogon = "ų"; const uopf = "𝕦"; const uparrow = "↑"; const updownarrow = "↕"; const upharpoonleft = "↿"; const upharpoonright = "↾"; const uplus = "⊎"; const upsi = "υ"; const upsih = "ϒ"; const upsilon = "υ"; const upuparrows = "⇈"; const urcorn = "⌝"; const urcorner = "⌝"; const urcrop = "⌎"; const uring = "ů"; const urtri = "◹"; const uscr = "𝓊"; const utdot = "⋰"; const utilde = "ũ"; const utri = "▵"; const utrif = "▴"; const uuarr = "⇈"; const uum = "ü"; const uuml = "ü"; const uwangle = "⦧"; const vArr = "⇕"; const vBar = "⫨"; const vBarv = "⫩"; const vDash = "⊨"; const vangrt = "⦜"; const varepsilon = "ϵ"; const varkappa = "ϰ"; const varnothing = "∅"; const varphi = "ϕ"; const varpi = "ϖ"; const varpropto = "∝"; const varr = "↕"; const varrho = "ϱ"; const varsigma = "ς"; const varsubsetneq = "⊊︀"; const varsubsetneqq = "⫋︀"; const varsupsetneq = "⊋︀"; const varsupsetneqq = "⫌︀"; const vartheta = "ϑ"; const vartriangleleft = "⊲"; const vartriangleright = "⊳"; const vcy = "в"; const vdash = "⊢"; const vee = "∨"; const veebar = "⊻"; const veeeq = "≚"; const vellip = "⋮"; const verbar = "|"; const vert = "|"; const vfr = "𝔳"; const vltri = "⊲"; const vnsub = "⊂⃒"; const vnsup = "⊃⃒"; const vopf = "𝕧"; const vprop = "∝"; const vrtri = "⊳"; const vscr = "𝓋"; const vsubnE = "⫋︀"; const vsubne = "⊊︀"; const vsupnE = "⫌︀"; const vsupne = "⊋︀"; const vzigzag = "⦚"; const wcirc = "ŵ"; const wedbar = "⩟"; const wedge = "∧"; const wedgeq = "≙"; const weierp = "℘"; const wfr = "𝔴"; const wopf = "𝕨"; const wp = "℘"; const wr = "≀"; const wreath = "≀"; const wscr = "𝓌"; const xcap = "⋂"; const xcirc = "◯"; const xcup = "⋃"; const xdtri = "▽"; const xfr = "𝔵"; const xhArr = "⟺"; const xharr = "⟷"; const xi = "ξ"; const xlArr = "⟸"; const xlarr = "⟵"; const xmap = "⟼"; const xnis = "⋻"; const xodot = "⨀"; const xopf = "𝕩"; const xoplus = "⨁"; const xotime = "⨂"; const xrArr = "⟹"; const xrarr = "⟶"; const xscr = "𝓍"; const xsqcup = "⨆"; const xuplus = "⨄"; const xutri = "△"; const xvee = "⋁"; const xwedge = "⋀"; const yacut = "ý"; const yacute = "ý"; const yacy = "я"; const ycirc = "ŷ"; const ycy = "ы"; const ye = "¥"; const yen = "¥"; const yfr = "𝔶"; const yicy = "ї"; const yopf = "𝕪"; const yscr = "𝓎"; const yucy = "ю"; const yum = "ÿ"; const yuml = "ÿ"; const zacute = "ź"; const zcaron = "ž"; const zcy = "з"; const zdot = "ż"; const zeetrf = "ℨ"; const zeta = "ζ"; const zfr = "𝔷"; const zhcy = "ж"; const zigrarr = "⇝"; const zopf = "𝕫"; const zscr = "𝓏"; const zwj = "‍"; const zwnj = "‌"; var index$1 = { AEli: AEli, AElig: AElig, AM: AM, AMP: AMP, Aacut: Aacut, Aacute: Aacute, Abreve: Abreve, Acir: Acir, Acirc: Acirc, Acy: Acy, Afr: Afr, Agrav: Agrav, Agrave: Agrave, Alpha: Alpha, Amacr: Amacr, And: And, Aogon: Aogon, Aopf: Aopf, ApplyFunction: ApplyFunction, Arin: Arin, Aring: Aring, Ascr: Ascr, Assign: Assign, Atild: Atild, Atilde: Atilde, Aum: Aum, Auml: Auml, Backslash: Backslash, Barv: Barv, Barwed: Barwed, Bcy: Bcy, Because: Because, Bernoullis: Bernoullis, Beta: Beta, Bfr: Bfr, Bopf: Bopf, Breve: Breve, Bscr: Bscr, Bumpeq: Bumpeq, CHcy: CHcy, COP: COP, COPY: COPY, Cacute: Cacute, Cap: Cap, CapitalDifferentialD: CapitalDifferentialD, Cayleys: Cayleys, Ccaron: Ccaron, Ccedi: Ccedi, Ccedil: Ccedil, Ccirc: Ccirc, Cconint: Cconint, Cdot: Cdot, Cedilla: Cedilla, CenterDot: CenterDot, Cfr: Cfr, Chi: Chi, CircleDot: CircleDot, CircleMinus: CircleMinus, CirclePlus: CirclePlus, CircleTimes: CircleTimes, ClockwiseContourIntegral: ClockwiseContourIntegral, CloseCurlyDoubleQuote: CloseCurlyDoubleQuote, CloseCurlyQuote: CloseCurlyQuote, Colon: Colon, Colone: Colone, Congruent: Congruent, Conint: Conint, ContourIntegral: ContourIntegral, Copf: Copf, Coproduct: Coproduct, CounterClockwiseContourIntegral: CounterClockwiseContourIntegral, Cross: Cross, Cscr: Cscr, Cup: Cup, CupCap: CupCap, DD: DD, DDotrahd: DDotrahd, DJcy: DJcy, DScy: DScy, DZcy: DZcy, Dagger: Dagger, Darr: Darr, Dashv: Dashv, Dcaron: Dcaron, Dcy: Dcy, Del: Del, Delta: Delta, Dfr: Dfr, DiacriticalAcute: DiacriticalAcute, DiacriticalDot: DiacriticalDot, DiacriticalDoubleAcute: DiacriticalDoubleAcute, DiacriticalGrave: DiacriticalGrave, DiacriticalTilde: DiacriticalTilde, Diamond: Diamond, DifferentialD: DifferentialD, Dopf: Dopf, Dot: Dot, DotDot: DotDot, DotEqual: DotEqual, DoubleContourIntegral: DoubleContourIntegral, DoubleDot: DoubleDot, DoubleDownArrow: DoubleDownArrow, DoubleLeftArrow: DoubleLeftArrow, DoubleLeftRightArrow: DoubleLeftRightArrow, DoubleLeftTee: DoubleLeftTee, DoubleLongLeftArrow: DoubleLongLeftArrow, DoubleLongLeftRightArrow: DoubleLongLeftRightArrow, DoubleLongRightArrow: DoubleLongRightArrow, DoubleRightArrow: DoubleRightArrow, DoubleRightTee: DoubleRightTee, DoubleUpArrow: DoubleUpArrow, DoubleUpDownArrow: DoubleUpDownArrow, DoubleVerticalBar: DoubleVerticalBar, DownArrow: DownArrow, DownArrowBar: DownArrowBar, DownArrowUpArrow: DownArrowUpArrow, DownBreve: DownBreve, DownLeftRightVector: DownLeftRightVector, DownLeftTeeVector: DownLeftTeeVector, DownLeftVector: DownLeftVector, DownLeftVectorBar: DownLeftVectorBar, DownRightTeeVector: DownRightTeeVector, DownRightVector: DownRightVector, DownRightVectorBar: DownRightVectorBar, DownTee: DownTee, DownTeeArrow: DownTeeArrow, Downarrow: Downarrow, Dscr: Dscr, Dstrok: Dstrok, ENG: ENG, ET: ET, ETH: ETH, Eacut: Eacut, Eacute: Eacute, Ecaron: Ecaron, Ecir: Ecir, Ecirc: Ecirc, Ecy: Ecy, Edot: Edot, Efr: Efr, Egrav: Egrav, Egrave: Egrave, Element: Element, Emacr: Emacr, EmptySmallSquare: EmptySmallSquare, EmptyVerySmallSquare: EmptyVerySmallSquare, Eogon: Eogon, Eopf: Eopf, Epsilon: Epsilon, Equal: Equal, EqualTilde: EqualTilde, Equilibrium: Equilibrium, Escr: Escr, Esim: Esim, Eta: Eta, Eum: Eum, Euml: Euml, Exists: Exists, ExponentialE: ExponentialE, Fcy: Fcy, Ffr: Ffr, FilledSmallSquare: FilledSmallSquare, FilledVerySmallSquare: FilledVerySmallSquare, Fopf: Fopf, ForAll: ForAll, Fouriertrf: Fouriertrf, Fscr: Fscr, GJcy: GJcy, G: G, GT: GT, Gamma: Gamma, Gammad: Gammad, Gbreve: Gbreve, Gcedil: Gcedil, Gcirc: Gcirc, Gcy: Gcy, Gdot: Gdot, Gfr: Gfr, Gg: Gg, Gopf: Gopf, GreaterEqual: GreaterEqual, GreaterEqualLess: GreaterEqualLess, GreaterFullEqual: GreaterFullEqual, GreaterGreater: GreaterGreater, GreaterLess: GreaterLess, GreaterSlantEqual: GreaterSlantEqual, GreaterTilde: GreaterTilde, Gscr: Gscr, Gt: Gt, HARDcy: HARDcy, Hacek: Hacek, Hat: Hat, Hcirc: Hcirc, Hfr: Hfr, HilbertSpace: HilbertSpace, Hopf: Hopf, HorizontalLine: HorizontalLine, Hscr: Hscr, Hstrok: Hstrok, HumpDownHump: HumpDownHump, HumpEqual: HumpEqual, IEcy: IEcy, IJlig: IJlig, IOcy: IOcy, Iacut: Iacut, Iacute: Iacute, Icir: Icir, Icirc: Icirc, Icy: Icy, Idot: Idot, Ifr: Ifr, Igrav: Igrav, Igrave: Igrave, Im: Im, Imacr: Imacr, ImaginaryI: ImaginaryI, Implies: Implies, Int: Int, Integral: Integral, Intersection: Intersection, InvisibleComma: InvisibleComma, InvisibleTimes: InvisibleTimes, Iogon: Iogon, Iopf: Iopf, Iota: Iota, Iscr: Iscr, Itilde: Itilde, Iukcy: Iukcy, Ium: Ium, Iuml: Iuml, Jcirc: Jcirc, Jcy: Jcy, Jfr: Jfr, Jopf: Jopf, Jscr: Jscr, Jsercy: Jsercy, Jukcy: Jukcy, KHcy: KHcy, KJcy: KJcy, Kappa: Kappa, Kcedil: Kcedil, Kcy: Kcy, Kfr: Kfr, Kopf: Kopf, Kscr: Kscr, LJcy: LJcy, L: L, LT: LT, Lacute: Lacute, Lambda: Lambda, Lang: Lang, Laplacetrf: Laplacetrf, Larr: Larr, Lcaron: Lcaron, Lcedil: Lcedil, Lcy: Lcy, LeftAngleBracket: LeftAngleBracket, LeftArrow: LeftArrow, LeftArrowBar: LeftArrowBar, LeftArrowRightArrow: LeftArrowRightArrow, LeftCeiling: LeftCeiling, LeftDoubleBracket: LeftDoubleBracket, LeftDownTeeVector: LeftDownTeeVector, LeftDownVector: LeftDownVector, LeftDownVectorBar: LeftDownVectorBar, LeftFloor: LeftFloor, LeftRightArrow: LeftRightArrow, LeftRightVector: LeftRightVector, LeftTee: LeftTee, LeftTeeArrow: LeftTeeArrow, LeftTeeVector: LeftTeeVector, LeftTriangle: LeftTriangle, LeftTriangleBar: LeftTriangleBar, LeftTriangleEqual: LeftTriangleEqual, LeftUpDownVector: LeftUpDownVector, LeftUpTeeVector: LeftUpTeeVector, LeftUpVector: LeftUpVector, LeftUpVectorBar: LeftUpVectorBar, LeftVector: LeftVector, LeftVectorBar: LeftVectorBar, Leftarrow: Leftarrow, Leftrightarrow: Leftrightarrow, LessEqualGreater: LessEqualGreater, LessFullEqual: LessFullEqual, LessGreater: LessGreater, LessLess: LessLess, LessSlantEqual: LessSlantEqual, LessTilde: LessTilde, Lfr: Lfr, Ll: Ll, Lleftarrow: Lleftarrow, Lmidot: Lmidot, LongLeftArrow: LongLeftArrow, LongLeftRightArrow: LongLeftRightArrow, LongRightArrow: LongRightArrow, Longleftarrow: Longleftarrow, Longleftrightarrow: Longleftrightarrow, Longrightarrow: Longrightarrow, Lopf: Lopf, LowerLeftArrow: LowerLeftArrow, LowerRightArrow: LowerRightArrow, Lscr: Lscr, Lsh: Lsh, Lstrok: Lstrok, Lt: Lt, "Map": "⤅", Mcy: Mcy, MediumSpace: MediumSpace, Mellintrf: Mellintrf, Mfr: Mfr, MinusPlus: MinusPlus, Mopf: Mopf, Mscr: Mscr, Mu: Mu, NJcy: NJcy, Nacute: Nacute, Ncaron: Ncaron, Ncedil: Ncedil, Ncy: Ncy, NegativeMediumSpace: NegativeMediumSpace, NegativeThickSpace: NegativeThickSpace, NegativeThinSpace: NegativeThinSpace, NegativeVeryThinSpace: NegativeVeryThinSpace, NestedGreaterGreater: NestedGreaterGreater, NestedLessLess: NestedLessLess, NewLine: NewLine, Nfr: Nfr, NoBreak: NoBreak, NonBreakingSpace: NonBreakingSpace, Nopf: Nopf, Not: Not, NotCongruent: NotCongruent, NotCupCap: NotCupCap, NotDoubleVerticalBar: NotDoubleVerticalBar, NotElement: NotElement, NotEqual: NotEqual, NotEqualTilde: NotEqualTilde, NotExists: NotExists, NotGreater: NotGreater, NotGreaterEqual: NotGreaterEqual, NotGreaterFullEqual: NotGreaterFullEqual, NotGreaterGreater: NotGreaterGreater, NotGreaterLess: NotGreaterLess, NotGreaterSlantEqual: NotGreaterSlantEqual, NotGreaterTilde: NotGreaterTilde, NotHumpDownHump: NotHumpDownHump, NotHumpEqual: NotHumpEqual, NotLeftTriangle: NotLeftTriangle, NotLeftTriangleBar: NotLeftTriangleBar, NotLeftTriangleEqual: NotLeftTriangleEqual, NotLess: NotLess, NotLessEqual: NotLessEqual, NotLessGreater: NotLessGreater, NotLessLess: NotLessLess, NotLessSlantEqual: NotLessSlantEqual, NotLessTilde: NotLessTilde, NotNestedGreaterGreater: NotNestedGreaterGreater, NotNestedLessLess: NotNestedLessLess, NotPrecedes: NotPrecedes, NotPrecedesEqual: NotPrecedesEqual, NotPrecedesSlantEqual: NotPrecedesSlantEqual, NotReverseElement: NotReverseElement, NotRightTriangle: NotRightTriangle, NotRightTriangleBar: NotRightTriangleBar, NotRightTriangleEqual: NotRightTriangleEqual, NotSquareSubset: NotSquareSubset, NotSquareSubsetEqual: NotSquareSubsetEqual, NotSquareSuperset: NotSquareSuperset, NotSquareSupersetEqual: NotSquareSupersetEqual, NotSubset: NotSubset, NotSubsetEqual: NotSubsetEqual, NotSucceeds: NotSucceeds, NotSucceedsEqual: NotSucceedsEqual, NotSucceedsSlantEqual: NotSucceedsSlantEqual, NotSucceedsTilde: NotSucceedsTilde, NotSuperset: NotSuperset, NotSupersetEqual: NotSupersetEqual, NotTilde: NotTilde, NotTildeEqual: NotTildeEqual, NotTildeFullEqual: NotTildeFullEqual, NotTildeTilde: NotTildeTilde, NotVerticalBar: NotVerticalBar, Nscr: Nscr, Ntild: Ntild, Ntilde: Ntilde, Nu: Nu, OElig: OElig, Oacut: Oacut, Oacute: Oacute, Ocir: Ocir, Ocirc: Ocirc, Ocy: Ocy, Odblac: Odblac, Ofr: Ofr, Ograv: Ograv, Ograve: Ograve, Omacr: Omacr, Omega: Omega, Omicron: Omicron, Oopf: Oopf, OpenCurlyDoubleQuote: OpenCurlyDoubleQuote, OpenCurlyQuote: OpenCurlyQuote, Or: Or, Oscr: Oscr, Oslas: Oslas, Oslash: Oslash, Otild: Otild, Otilde: Otilde, Otimes: Otimes, Oum: Oum, Ouml: Ouml, OverBar: OverBar, OverBrace: OverBrace, OverBracket: OverBracket, OverParenthesis: OverParenthesis, PartialD: PartialD, Pcy: Pcy, Pfr: Pfr, Phi: Phi, Pi: Pi, PlusMinus: PlusMinus, Poincareplane: Poincareplane, Popf: Popf, Pr: Pr, Precedes: Precedes, PrecedesEqual: PrecedesEqual, PrecedesSlantEqual: PrecedesSlantEqual, PrecedesTilde: PrecedesTilde, Prime: Prime, Product: Product, Proportion: Proportion, Proportional: Proportional, Pscr: Pscr, Psi: Psi, QUO: QUO, QUOT: QUOT, Qfr: Qfr, Qopf: Qopf, Qscr: Qscr, RBarr: RBarr, RE: RE, REG: REG, Racute: Racute, Rang: Rang, Rarr: Rarr, Rarrtl: Rarrtl, Rcaron: Rcaron, Rcedil: Rcedil, Rcy: Rcy, Re: Re, ReverseElement: ReverseElement, ReverseEquilibrium: ReverseEquilibrium, ReverseUpEquilibrium: ReverseUpEquilibrium, Rfr: Rfr, Rho: Rho, RightAngleBracket: RightAngleBracket, RightArrow: RightArrow, RightArrowBar: RightArrowBar, RightArrowLeftArrow: RightArrowLeftArrow, RightCeiling: RightCeiling, RightDoubleBracket: RightDoubleBracket, RightDownTeeVector: RightDownTeeVector, RightDownVector: RightDownVector, RightDownVectorBar: RightDownVectorBar, RightFloor: RightFloor, RightTee: RightTee, RightTeeArrow: RightTeeArrow, RightTeeVector: RightTeeVector, RightTriangle: RightTriangle, RightTriangleBar: RightTriangleBar, RightTriangleEqual: RightTriangleEqual, RightUpDownVector: RightUpDownVector, RightUpTeeVector: RightUpTeeVector, RightUpVector: RightUpVector, RightUpVectorBar: RightUpVectorBar, RightVector: RightVector, RightVectorBar: RightVectorBar, Rightarrow: Rightarrow, Ropf: Ropf, RoundImplies: RoundImplies, Rrightarrow: Rrightarrow, Rscr: Rscr, Rsh: Rsh, RuleDelayed: RuleDelayed, SHCHcy: SHCHcy, SHcy: SHcy, SOFTcy: SOFTcy, Sacute: Sacute, Sc: Sc, Scaron: Scaron, Scedil: Scedil, Scirc: Scirc, Scy: Scy, Sfr: Sfr, ShortDownArrow: ShortDownArrow, ShortLeftArrow: ShortLeftArrow, ShortRightArrow: ShortRightArrow, ShortUpArrow: ShortUpArrow, Sigma: Sigma, SmallCircle: SmallCircle, Sopf: Sopf, Sqrt: Sqrt, Square: Square, SquareIntersection: SquareIntersection, SquareSubset: SquareSubset, SquareSubsetEqual: SquareSubsetEqual, SquareSuperset: SquareSuperset, SquareSupersetEqual: SquareSupersetEqual, SquareUnion: SquareUnion, Sscr: Sscr, Star: Star, Sub: Sub, Subset: Subset, SubsetEqual: SubsetEqual, Succeeds: Succeeds, SucceedsEqual: SucceedsEqual, SucceedsSlantEqual: SucceedsSlantEqual, SucceedsTilde: SucceedsTilde, SuchThat: SuchThat, Sum: Sum, Sup: Sup, Superset: Superset, SupersetEqual: SupersetEqual, Supset: Supset, THOR: THOR, THORN: THORN, TRADE: TRADE, TSHcy: TSHcy, TScy: TScy, Tab: Tab, Tau: Tau, Tcaron: Tcaron, Tcedil: Tcedil, Tcy: Tcy, Tfr: Tfr, Therefore: Therefore, Theta: Theta, ThickSpace: ThickSpace, ThinSpace: ThinSpace, Tilde: Tilde, TildeEqual: TildeEqual, TildeFullEqual: TildeFullEqual, TildeTilde: TildeTilde, Topf: Topf, TripleDot: TripleDot, Tscr: Tscr, Tstrok: Tstrok, Uacut: Uacut, Uacute: Uacute, Uarr: Uarr, Uarrocir: Uarrocir, Ubrcy: Ubrcy, Ubreve: Ubreve, Ucir: Ucir, Ucirc: Ucirc, Ucy: Ucy, Udblac: Udblac, Ufr: Ufr, Ugrav: Ugrav, Ugrave: Ugrave, Umacr: Umacr, UnderBar: UnderBar, UnderBrace: UnderBrace, UnderBracket: UnderBracket, UnderParenthesis: UnderParenthesis, Union: Union, UnionPlus: UnionPlus, Uogon: Uogon, Uopf: Uopf, UpArrow: UpArrow, UpArrowBar: UpArrowBar, UpArrowDownArrow: UpArrowDownArrow, UpDownArrow: UpDownArrow, UpEquilibrium: UpEquilibrium, UpTee: UpTee, UpTeeArrow: UpTeeArrow, Uparrow: Uparrow, Updownarrow: Updownarrow, UpperLeftArrow: UpperLeftArrow, UpperRightArrow: UpperRightArrow, Upsi: Upsi, Upsilon: Upsilon, Uring: Uring, Uscr: Uscr, Utilde: Utilde, Uum: Uum, Uuml: Uuml, VDash: VDash, Vbar: Vbar, Vcy: Vcy, Vdash: Vdash, Vdashl: Vdashl, Vee: Vee, Verbar: Verbar, Vert: Vert, VerticalBar: VerticalBar, VerticalLine: VerticalLine, VerticalSeparator: VerticalSeparator, VerticalTilde: VerticalTilde, VeryThinSpace: VeryThinSpace, Vfr: Vfr, Vopf: Vopf, Vscr: Vscr, Vvdash: Vvdash, Wcirc: Wcirc, Wedge: Wedge, Wfr: Wfr, Wopf: Wopf, Wscr: Wscr, Xfr: Xfr, Xi: Xi, Xopf: Xopf, Xscr: Xscr, YAcy: YAcy, YIcy: YIcy, YUcy: YUcy, Yacut: Yacut, Yacute: Yacute, Ycirc: Ycirc, Ycy: Ycy, Yfr: Yfr, Yopf: Yopf, Yscr: Yscr, Yuml: Yuml, ZHcy: ZHcy, Zacute: Zacute, Zcaron: Zcaron, Zcy: Zcy, Zdot: Zdot, ZeroWidthSpace: ZeroWidthSpace, Zeta: Zeta, Zfr: Zfr, Zopf: Zopf, Zscr: Zscr, aacut: aacut, aacute: aacute, abreve: abreve, ac: ac, acE: acE, acd: acd, acir: acir, acirc: acirc, acut: acut, acute: acute, acy: acy, aeli: aeli, aelig: aelig, af: af, afr: afr, agrav: agrav, agrave: agrave, alefsym: alefsym, aleph: aleph, alpha: alpha, amacr: amacr, amalg: amalg, am: am, amp: amp, and: and, andand: andand, andd: andd, andslope: andslope, andv: andv, ang: ang, ange: ange, angle: angle, angmsd: angmsd, angmsdaa: angmsdaa, angmsdab: angmsdab, angmsdac: angmsdac, angmsdad: angmsdad, angmsdae: angmsdae, angmsdaf: angmsdaf, angmsdag: angmsdag, angmsdah: angmsdah, angrt: angrt, angrtvb: angrtvb, angrtvbd: angrtvbd, angsph: angsph, angst: angst, angzarr: angzarr, aogon: aogon, aopf: aopf, ap: ap, apE: apE, apacir: apacir, ape: ape, apid: apid, apos: apos, approx: approx, approxeq: approxeq, arin: arin, aring: aring, ascr: ascr, ast: ast, asymp: asymp, asympeq: asympeq, atild: atild, atilde: atilde, aum: aum, auml: auml, awconint: awconint, awint: awint, bNot: bNot, backcong: backcong, backepsilon: backepsilon, backprime: backprime, backsim: backsim, backsimeq: backsimeq, barvee: barvee, barwed: barwed, barwedge: barwedge, bbrk: bbrk, bbrktbrk: bbrktbrk, bcong: bcong, bcy: bcy, bdquo: bdquo, becaus: becaus, because: because, bemptyv: bemptyv, bepsi: bepsi, bernou: bernou, beta: beta, beth: beth, between: between, bfr: bfr, bigcap: bigcap, bigcirc: bigcirc, bigcup: bigcup, bigodot: bigodot, bigoplus: bigoplus, bigotimes: bigotimes, bigsqcup: bigsqcup, bigstar: bigstar, bigtriangledown: bigtriangledown, bigtriangleup: bigtriangleup, biguplus: biguplus, bigvee: bigvee, bigwedge: bigwedge, bkarow: bkarow, blacklozenge: blacklozenge, blacksquare: blacksquare, blacktriangle: blacktriangle, blacktriangledown: blacktriangledown, blacktriangleleft: blacktriangleleft, blacktriangleright: blacktriangleright, blank: blank, blk12: blk12, blk14: blk14, blk34: blk34, block: block, bne: bne, bnequiv: bnequiv, bnot: bnot, bopf: bopf, bot: bot, bottom: bottom, bowtie: bowtie, boxDL: boxDL, boxDR: boxDR, boxDl: boxDl, boxDr: boxDr, boxH: boxH, boxHD: boxHD, boxHU: boxHU, boxHd: boxHd, boxHu: boxHu, boxUL: boxUL, boxUR: boxUR, boxUl: boxUl, boxUr: boxUr, boxV: boxV, boxVH: boxVH, boxVL: boxVL, boxVR: boxVR, boxVh: boxVh, boxVl: boxVl, boxVr: boxVr, boxbox: boxbox, boxdL: boxdL, boxdR: boxdR, boxdl: boxdl, boxdr: boxdr, boxh: boxh, boxhD: boxhD, boxhU: boxhU, boxhd: boxhd, boxhu: boxhu, boxminus: boxminus, boxplus: boxplus, boxtimes: boxtimes, boxuL: boxuL, boxuR: boxuR, boxul: boxul, boxur: boxur, boxv: boxv, boxvH: boxvH, boxvL: boxvL, boxvR: boxvR, boxvh: boxvh, boxvl: boxvl, boxvr: boxvr, bprime: bprime, breve: breve, brvba: brvba, brvbar: brvbar, bscr: bscr, bsemi: bsemi, bsim: bsim, bsime: bsime, bsol: bsol, bsolb: bsolb, bsolhsub: bsolhsub, bull: bull, bullet: bullet, bump: bump, bumpE: bumpE, bumpe: bumpe, bumpeq: bumpeq, cacute: cacute, cap: cap, capand: capand, capbrcup: capbrcup, capcap: capcap, capcup: capcup, capdot: capdot, caps: caps, caret: caret, caron: caron, ccaps: ccaps, ccaron: ccaron, ccedi: ccedi, ccedil: ccedil, ccirc: ccirc, ccups: ccups, ccupssm: ccupssm, cdot: cdot, cedi: cedi, cedil: cedil, cemptyv: cemptyv, cen: cen, cent: cent, centerdot: centerdot, cfr: cfr, chcy: chcy, check: check$2, checkmark: checkmark, chi: chi, cir: cir, cirE: cirE, circ: circ, circeq: circeq, circlearrowleft: circlearrowleft, circlearrowright: circlearrowright, circledR: circledR, circledS: circledS, circledast: circledast, circledcirc: circledcirc, circleddash: circleddash, cire: cire, cirfnint: cirfnint, cirmid: cirmid, cirscir: cirscir, clubs: clubs, clubsuit: clubsuit, colon: colon, colone: colone, coloneq: coloneq, comma: comma, commat: commat, comp: comp, compfn: compfn, complement: complement, complexes: complexes, cong: cong, congdot: congdot, conint: conint, copf: copf, coprod: coprod, cop: cop, copy: copy$1, copysr: copysr, crarr: crarr, cross: cross, cscr: cscr, csub: csub, csube: csube, csup: csup, csupe: csupe, ctdot: ctdot, cudarrl: cudarrl, cudarrr: cudarrr, cuepr: cuepr, cuesc: cuesc, cularr: cularr, cularrp: cularrp, cup: cup, cupbrcap: cupbrcap, cupcap: cupcap, cupcup: cupcup, cupdot: cupdot, cupor: cupor, cups: cups, curarr: curarr, curarrm: curarrm, curlyeqprec: curlyeqprec, curlyeqsucc: curlyeqsucc, curlyvee: curlyvee, curlywedge: curlywedge, curre: curre, curren: curren, curvearrowleft: curvearrowleft, curvearrowright: curvearrowright, cuvee: cuvee, cuwed: cuwed, cwconint: cwconint, cwint: cwint, cylcty: cylcty, dArr: dArr, dHar: dHar, dagger: dagger, daleth: daleth, darr: darr, dash: dash, dashv: dashv, dbkarow: dbkarow, dblac: dblac, dcaron: dcaron, dcy: dcy, dd: dd, ddagger: ddagger, ddarr: ddarr, ddotseq: ddotseq, de: de, deg: deg, delta: delta, demptyv: demptyv, dfisht: dfisht, dfr: dfr, dharl: dharl, dharr: dharr, diam: diam, diamond: diamond, diamondsuit: diamondsuit, diams: diams, die: die, digamma: digamma, disin: disin, div: div, divid: divid, divide: divide, divideontimes: divideontimes, divonx: divonx, djcy: djcy, dlcorn: dlcorn, dlcrop: dlcrop, dollar: dollar, dopf: dopf, dot: dot, doteq: doteq, doteqdot: doteqdot, dotminus: dotminus, dotplus: dotplus, dotsquare: dotsquare, doublebarwedge: doublebarwedge, downarrow: downarrow, downdownarrows: downdownarrows, downharpoonleft: downharpoonleft, downharpoonright: downharpoonright, drbkarow: drbkarow, drcorn: drcorn, drcrop: drcrop, dscr: dscr, dscy: dscy, dsol: dsol, dstrok: dstrok, dtdot: dtdot, dtri: dtri, dtrif: dtrif, duarr: duarr, duhar: duhar, dwangle: dwangle, dzcy: dzcy, dzigrarr: dzigrarr, eDDot: eDDot, eDot: eDot, eacut: eacut, eacute: eacute, easter: easter, ecaron: ecaron, ecir: ecir, ecirc: ecirc, ecolon: ecolon, ecy: ecy, edot: edot, ee: ee, efDot: efDot, efr: efr, eg: eg, egrav: egrav, egrave: egrave, egs: egs, egsdot: egsdot, el: el, elinters: elinters, ell: ell, els: els, elsdot: elsdot, emacr: emacr, empty: empty, emptyset: emptyset, emptyv: emptyv, emsp13: emsp13, emsp14: emsp14, emsp: emsp, eng: eng, ensp: ensp, eogon: eogon, eopf: eopf, epar: epar, eparsl: eparsl, eplus: eplus, epsi: epsi, epsilon: epsilon, epsiv: epsiv, eqcirc: eqcirc, eqcolon: eqcolon, eqsim: eqsim, eqslantgtr: eqslantgtr, eqslantless: eqslantless, equals: equals, equest: equest, equiv: equiv, equivDD: equivDD, eqvparsl: eqvparsl, erDot: erDot, erarr: erarr, escr: escr, esdot: esdot, esim: esim, eta: eta, et: et, eth: eth, eum: eum, euml: euml, euro: euro, excl: excl, exist: exist, expectation: expectation, exponentiale: exponentiale, fallingdotseq: fallingdotseq, fcy: fcy, female: female, ffilig: ffilig, fflig: fflig, ffllig: ffllig, ffr: ffr, filig: filig, fjlig: fjlig, flat: flat, fllig: fllig, fltns: fltns, fnof: fnof, fopf: fopf, forall: forall, fork: fork, forkv: forkv, fpartint: fpartint, frac1: frac1, frac12: frac12, frac13: frac13, frac14: frac14, frac15: frac15, frac16: frac16, frac18: frac18, frac23: frac23, frac25: frac25, frac3: frac3, frac34: frac34, frac35: frac35, frac38: frac38, frac45: frac45, frac56: frac56, frac58: frac58, frac78: frac78, frasl: frasl, frown: frown, fscr: fscr, gE: gE, gEl: gEl, gacute: gacute, gamma: gamma, gammad: gammad, gap: gap, gbreve: gbreve, gcirc: gcirc, gcy: gcy, gdot: gdot, ge: ge, gel: gel, geq: geq, geqq: geqq, geqslant: geqslant, ges: ges, gescc: gescc, gesdot: gesdot, gesdoto: gesdoto, gesdotol: gesdotol, gesl: gesl, gesles: gesles, gfr: gfr, gg: gg, ggg: ggg, gimel: gimel, gjcy: gjcy, gl: gl, glE: glE, gla: gla, glj: glj, gnE: gnE, gnap: gnap, gnapprox: gnapprox, gne: gne, gneq: gneq, gneqq: gneqq, gnsim: gnsim, gopf: gopf, grave: grave, gscr: gscr, gsim: gsim, gsime: gsime, gsiml: gsiml, g: g, gt: gt, gtcc: gtcc, gtcir: gtcir, gtdot: gtdot, gtlPar: gtlPar, gtquest: gtquest, gtrapprox: gtrapprox, gtrarr: gtrarr, gtrdot: gtrdot, gtreqless: gtreqless, gtreqqless: gtreqqless, gtrless: gtrless, gtrsim: gtrsim, gvertneqq: gvertneqq, gvnE: gvnE, hArr: hArr, hairsp: hairsp, half: half, hamilt: hamilt, hardcy: hardcy, harr: harr, harrcir: harrcir, harrw: harrw, hbar: hbar, hcirc: hcirc, hearts: hearts, heartsuit: heartsuit, hellip: hellip, hercon: hercon, hfr: hfr, hksearow: hksearow, hkswarow: hkswarow, hoarr: hoarr, homtht: homtht, hookleftarrow: hookleftarrow, hookrightarrow: hookrightarrow, hopf: hopf, horbar: horbar, hscr: hscr, hslash: hslash, hstrok: hstrok, hybull: hybull, hyphen: hyphen, iacut: iacut, iacute: iacute, ic: ic, icir: icir, icirc: icirc, icy: icy, iecy: iecy, iexc: iexc, iexcl: iexcl, iff: iff, ifr: ifr, igrav: igrav, igrave: igrave, ii: ii, iiiint: iiiint, iiint: iiint, iinfin: iinfin, iiota: iiota, ijlig: ijlig, imacr: imacr, image: image, imagline: imagline, imagpart: imagpart, imath: imath, imof: imof, imped: imped, "in": "∈", incare: incare, infin: infin, infintie: infintie, inodot: inodot, int: int, intcal: intcal, integers: integers, intercal: intercal, intlarhk: intlarhk, intprod: intprod, iocy: iocy, iogon: iogon, iopf: iopf, iota: iota, iprod: iprod, iques: iques, iquest: iquest, iscr: iscr, isin: isin, isinE: isinE, isindot: isindot, isins: isins, isinsv: isinsv, isinv: isinv, it: it, itilde: itilde, iukcy: iukcy, ium: ium, iuml: iuml, jcirc: jcirc, jcy: jcy, jfr: jfr, jmath: jmath, jopf: jopf, jscr: jscr, jsercy: jsercy, jukcy: jukcy, kappa: kappa, kappav: kappav, kcedil: kcedil, kcy: kcy, kfr: kfr, kgreen: kgreen, khcy: khcy, kjcy: kjcy, kopf: kopf, kscr: kscr, lAarr: lAarr, lArr: lArr, lAtail: lAtail, lBarr: lBarr, lE: lE, lEg: lEg, lHar: lHar, lacute: lacute, laemptyv: laemptyv, lagran: lagran, lambda: lambda, lang: lang, langd: langd, langle: langle, lap: lap, laqu: laqu, laquo: laquo, larr: larr, larrb: larrb, larrbfs: larrbfs, larrfs: larrfs, larrhk: larrhk, larrlp: larrlp, larrpl: larrpl, larrsim: larrsim, larrtl: larrtl, lat: lat, latail: latail, late: late, lates: lates, lbarr: lbarr, lbbrk: lbbrk, lbrace: lbrace, lbrack: lbrack, lbrke: lbrke, lbrksld: lbrksld, lbrkslu: lbrkslu, lcaron: lcaron, lcedil: lcedil, lceil: lceil, lcub: lcub, lcy: lcy, ldca: ldca, ldquo: ldquo, ldquor: ldquor, ldrdhar: ldrdhar, ldrushar: ldrushar, ldsh: ldsh, le: le, leftarrow: leftarrow, leftarrowtail: leftarrowtail, leftharpoondown: leftharpoondown, leftharpoonup: leftharpoonup, leftleftarrows: leftleftarrows, leftrightarrow: leftrightarrow, leftrightarrows: leftrightarrows, leftrightharpoons: leftrightharpoons, leftrightsquigarrow: leftrightsquigarrow, leftthreetimes: leftthreetimes, leg: leg, leq: leq, leqq: leqq, leqslant: leqslant, les: les, lescc: lescc, lesdot: lesdot, lesdoto: lesdoto, lesdotor: lesdotor, lesg: lesg, lesges: lesges, lessapprox: lessapprox, lessdot: lessdot, lesseqgtr: lesseqgtr, lesseqqgtr: lesseqqgtr, lessgtr: lessgtr, lesssim: lesssim, lfisht: lfisht, lfloor: lfloor, lfr: lfr, lg: lg, lgE: lgE, lhard: lhard, lharu: lharu, lharul: lharul, lhblk: lhblk, ljcy: ljcy, ll: ll, llarr: llarr, llcorner: llcorner, llhard: llhard, lltri: lltri, lmidot: lmidot, lmoust: lmoust, lmoustache: lmoustache, lnE: lnE, lnap: lnap, lnapprox: lnapprox, lne: lne, lneq: lneq, lneqq: lneqq, lnsim: lnsim, loang: loang, loarr: loarr, lobrk: lobrk, longleftarrow: longleftarrow, longleftrightarrow: longleftrightarrow, longmapsto: longmapsto, longrightarrow: longrightarrow, looparrowleft: looparrowleft, looparrowright: looparrowright, lopar: lopar, lopf: lopf, loplus: loplus, lotimes: lotimes, lowast: lowast, lowbar: lowbar, loz: loz, lozenge: lozenge, lozf: lozf, lpar: lpar, lparlt: lparlt, lrarr: lrarr, lrcorner: lrcorner, lrhar: lrhar, lrhard: lrhard, lrm: lrm, lrtri: lrtri, lsaquo: lsaquo, lscr: lscr, lsh: lsh, lsim: lsim, lsime: lsime, lsimg: lsimg, lsqb: lsqb, lsquo: lsquo, lsquor: lsquor, lstrok: lstrok, l: l, lt: lt, ltcc: ltcc, ltcir: ltcir, ltdot: ltdot, lthree: lthree, ltimes: ltimes, ltlarr: ltlarr, ltquest: ltquest, ltrPar: ltrPar, ltri: ltri, ltrie: ltrie, ltrif: ltrif, lurdshar: lurdshar, luruhar: luruhar, lvertneqq: lvertneqq, lvnE: lvnE, mDDot: mDDot, mac: mac, macr: macr, male: male, malt: malt, maltese: maltese, map: map$2, mapsto: mapsto, mapstodown: mapstodown, mapstoleft: mapstoleft, mapstoup: mapstoup, marker: marker, mcomma: mcomma, mcy: mcy, mdash: mdash, measuredangle: measuredangle, mfr: mfr, mho: mho, micr: micr, micro: micro, mid: mid, midast: midast, midcir: midcir, middo: middo, middot: middot, minus: minus, minusb: minusb, minusd: minusd, minusdu: minusdu, mlcp: mlcp, mldr: mldr, mnplus: mnplus, models: models$2, mopf: mopf, mp: mp, mscr: mscr, mstpos: mstpos, mu: mu, multimap: multimap, mumap: mumap, nGg: nGg, nGt: nGt, nGtv: nGtv, nLeftarrow: nLeftarrow, nLeftrightarrow: nLeftrightarrow, nLl: nLl, nLt: nLt, nLtv: nLtv, nRightarrow: nRightarrow, nVDash: nVDash, nVdash: nVdash, nabla: nabla, nacute: nacute, nang: nang, nap: nap, napE: napE, napid: napid, napos: napos, napprox: napprox, natur: natur, natural: natural, naturals: naturals, nbs: nbs, nbsp: nbsp, nbump: nbump, nbumpe: nbumpe, ncap: ncap, ncaron: ncaron, ncedil: ncedil, ncong: ncong, ncongdot: ncongdot, ncup: ncup, ncy: ncy, ndash: ndash, ne: ne, neArr: neArr, nearhk: nearhk, nearr: nearr, nearrow: nearrow, nedot: nedot, nequiv: nequiv, nesear: nesear, nesim: nesim, nexist: nexist, nexists: nexists, nfr: nfr, ngE: ngE, nge: nge, ngeq: ngeq, ngeqq: ngeqq, ngeqslant: ngeqslant, nges: nges, ngsim: ngsim, ngt: ngt, ngtr: ngtr, nhArr: nhArr, nharr: nharr, nhpar: nhpar, ni: ni, nis: nis, nisd: nisd, niv: niv, njcy: njcy, nlArr: nlArr, nlE: nlE, nlarr: nlarr, nldr: nldr, nle: nle, nleftarrow: nleftarrow, nleftrightarrow: nleftrightarrow, nleq: nleq, nleqq: nleqq, nleqslant: nleqslant, nles: nles, nless: nless, nlsim: nlsim, nlt: nlt, nltri: nltri, nltrie: nltrie, nmid: nmid, nopf: nopf, no: no, not: not, notin: notin, notinE: notinE, notindot: notindot, notinva: notinva, notinvb: notinvb, notinvc: notinvc, notni: notni, notniva: notniva, notnivb: notnivb, notnivc: notnivc, npar: npar, nparallel: nparallel, nparsl: nparsl, npart: npart, npolint: npolint, npr: npr, nprcue: nprcue, npre: npre, nprec: nprec, npreceq: npreceq, nrArr: nrArr, nrarr: nrarr, nrarrc: nrarrc, nrarrw: nrarrw, nrightarrow: nrightarrow, nrtri: nrtri, nrtrie: nrtrie, nsc: nsc, nsccue: nsccue, nsce: nsce, nscr: nscr, nshortmid: nshortmid, nshortparallel: nshortparallel, nsim: nsim, nsime: nsime, nsimeq: nsimeq, nsmid: nsmid, nspar: nspar, nsqsube: nsqsube, nsqsupe: nsqsupe, nsub: nsub, nsubE: nsubE, nsube: nsube, nsubset: nsubset, nsubseteq: nsubseteq, nsubseteqq: nsubseteqq, nsucc: nsucc, nsucceq: nsucceq, nsup: nsup, nsupE: nsupE, nsupe: nsupe, nsupset: nsupset, nsupseteq: nsupseteq, nsupseteqq: nsupseteqq, ntgl: ntgl, ntild: ntild, ntilde: ntilde, ntlg: ntlg, ntriangleleft: ntriangleleft, ntrianglelefteq: ntrianglelefteq, ntriangleright: ntriangleright, ntrianglerighteq: ntrianglerighteq, nu: nu, num: num, numero: numero, numsp: numsp, nvDash: nvDash, nvHarr: nvHarr, nvap: nvap, nvdash: nvdash, nvge: nvge, nvgt: nvgt, nvinfin: nvinfin, nvlArr: nvlArr, nvle: nvle, nvlt: nvlt, nvltrie: nvltrie, nvrArr: nvrArr, nvrtrie: nvrtrie, nvsim: nvsim, nwArr: nwArr, nwarhk: nwarhk, nwarr: nwarr, nwarrow: nwarrow, nwnear: nwnear, oS: oS, oacut: oacut, oacute: oacute, oast: oast, ocir: ocir, ocirc: ocirc, ocy: ocy, odash: odash, odblac: odblac, odiv: odiv, odot: odot, odsold: odsold, oelig: oelig, ofcir: ofcir, ofr: ofr, ogon: ogon, ograv: ograv, ograve: ograve, ogt: ogt, ohbar: ohbar, ohm: ohm, oint: oint, olarr: olarr, olcir: olcir, olcross: olcross, oline: oline, olt: olt, omacr: omacr, omega: omega, omicron: omicron, omid: omid, ominus: ominus, oopf: oopf, opar: opar, operp: operp, oplus: oplus, or: or, orarr: orarr, ord: ord, order: order$1, orderof: orderof, ordf: ordf, ordm: ordm, origof: origof, oror: oror, orslope: orslope, orv: orv, oscr: oscr, oslas: oslas, oslash: oslash, osol: osol, otild: otild, otilde: otilde, otimes: otimes, otimesas: otimesas, oum: oum, ouml: ouml, ovbar: ovbar, par: par, para: para, parallel: parallel, parsim: parsim, parsl: parsl, part: part, pcy: pcy, percnt: percnt, period: period, permil: permil, perp: perp, pertenk: pertenk, pfr: pfr, phi: phi, phiv: phiv, phmmat: phmmat, phone: phone, pi: pi, pitchfork: pitchfork, piv: piv, planck: planck, planckh: planckh, plankv: plankv, plus: plus, plusacir: plusacir, plusb: plusb, pluscir: pluscir, plusdo: plusdo, plusdu: plusdu, pluse: pluse, plusm: plusm, plusmn: plusmn, plussim: plussim, plustwo: plustwo, pm: pm, pointint: pointint, popf: popf, poun: poun, pound: pound, pr: pr, prE: prE, prap: prap, prcue: prcue, pre: pre, prec: prec, precapprox: precapprox, preccurlyeq: preccurlyeq, preceq: preceq, precnapprox: precnapprox, precneqq: precneqq, precnsim: precnsim, precsim: precsim, prime: prime, primes: primes, prnE: prnE, prnap: prnap, prnsim: prnsim, prod: prod, profalar: profalar, profline: profline, profsurf: profsurf, prop: prop, propto: propto, prsim: prsim, prurel: prurel, pscr: pscr, psi: psi, puncsp: puncsp, qfr: qfr, qint: qint, qopf: qopf, qprime: qprime, qscr: qscr, quaternions: quaternions, quatint: quatint, quest: quest, questeq: questeq, quo: quo, quot: quot, rAarr: rAarr, rArr: rArr, rAtail: rAtail, rBarr: rBarr, rHar: rHar, race: race, racute: racute, radic: radic, raemptyv: raemptyv, rang: rang, rangd: rangd, range: range$1, rangle: rangle, raqu: raqu, raquo: raquo, rarr: rarr, rarrap: rarrap, rarrb: rarrb, rarrbfs: rarrbfs, rarrc: rarrc, rarrfs: rarrfs, rarrhk: rarrhk, rarrlp: rarrlp, rarrpl: rarrpl, rarrsim: rarrsim, rarrtl: rarrtl, rarrw: rarrw, ratail: ratail, ratio: ratio, rationals: rationals, rbarr: rbarr, rbbrk: rbbrk, rbrace: rbrace, rbrack: rbrack, rbrke: rbrke, rbrksld: rbrksld, rbrkslu: rbrkslu, rcaron: rcaron, rcedil: rcedil, rceil: rceil, rcub: rcub, rcy: rcy, rdca: rdca, rdldhar: rdldhar, rdquo: rdquo, rdquor: rdquor, rdsh: rdsh, real: real, realine: realine, realpart: realpart, reals: reals, rect: rect, re: re, reg: reg, rfisht: rfisht, rfloor: rfloor, rfr: rfr, rhard: rhard, rharu: rharu, rharul: rharul, rho: rho, rhov: rhov, rightarrow: rightarrow, rightarrowtail: rightarrowtail, rightharpoondown: rightharpoondown, rightharpoonup: rightharpoonup, rightleftarrows: rightleftarrows, rightleftharpoons: rightleftharpoons, rightrightarrows: rightrightarrows, rightsquigarrow: rightsquigarrow, rightthreetimes: rightthreetimes, ring: ring, risingdotseq: risingdotseq, rlarr: rlarr, rlhar: rlhar, rlm: rlm, rmoust: rmoust, rmoustache: rmoustache, rnmid: rnmid, roang: roang, roarr: roarr, robrk: robrk, ropar: ropar, ropf: ropf, roplus: roplus, rotimes: rotimes, rpar: rpar, rpargt: rpargt, rppolint: rppolint, rrarr: rrarr, rsaquo: rsaquo, rscr: rscr, rsh: rsh, rsqb: rsqb, rsquo: rsquo, rsquor: rsquor, rthree: rthree, rtimes: rtimes, rtri: rtri, rtrie: rtrie, rtrif: rtrif, rtriltri: rtriltri, ruluhar: ruluhar, rx: rx, sacute: sacute, sbquo: sbquo, sc: sc, scE: scE, scap: scap, scaron: scaron, sccue: sccue, sce: sce, scedil: scedil, scirc: scirc, scnE: scnE, scnap: scnap, scnsim: scnsim, scpolint: scpolint, scsim: scsim, scy: scy, sdot: sdot, sdotb: sdotb, sdote: sdote, seArr: seArr, searhk: searhk, searr: searr, searrow: searrow, sec: sec, sect: sect, semi: semi, seswar: seswar, setminus: setminus, setmn: setmn, sext: sext, sfr: sfr, sfrown: sfrown, sharp: sharp, shchcy: shchcy, shcy: shcy, shortmid: shortmid, shortparallel: shortparallel, sh: sh, shy: shy, sigma: sigma, sigmaf: sigmaf, sigmav: sigmav, sim: sim, simdot: simdot, sime: sime, simeq: simeq, simg: simg, simgE: simgE, siml: siml, simlE: simlE, simne: simne, simplus: simplus, simrarr: simrarr, slarr: slarr, smallsetminus: smallsetminus, smashp: smashp, smeparsl: smeparsl, smid: smid, smile: smile, smt: smt, smte: smte, smtes: smtes, softcy: softcy, sol: sol, solb: solb, solbar: solbar, sopf: sopf, spades: spades, spadesuit: spadesuit, spar: spar, sqcap: sqcap, sqcaps: sqcaps, sqcup: sqcup, sqcups: sqcups, sqsub: sqsub, sqsube: sqsube, sqsubset: sqsubset, sqsubseteq: sqsubseteq, sqsup: sqsup, sqsupe: sqsupe, sqsupset: sqsupset, sqsupseteq: sqsupseteq, squ: squ, square: square, squarf: squarf, squf: squf, srarr: srarr, sscr: sscr, ssetmn: ssetmn, ssmile: ssmile, sstarf: sstarf, star: star$1, starf: starf, straightepsilon: straightepsilon, straightphi: straightphi, strns: strns, sub: sub, subE: subE, subdot: subdot, sube: sube, subedot: subedot, submult: submult, subnE: subnE, subne: subne, subplus: subplus, subrarr: subrarr, subset: subset, subseteq: subseteq, subseteqq: subseteqq, subsetneq: subsetneq, subsetneqq: subsetneqq, subsim: subsim, subsub: subsub, subsup: subsup, succ: succ, succapprox: succapprox, succcurlyeq: succcurlyeq, succeq: succeq, succnapprox: succnapprox, succneqq: succneqq, succnsim: succnsim, succsim: succsim, sum: sum, sung: sung, sup: sup, sup1: sup1, sup2: sup2, sup3: sup3, supE: supE, supdot: supdot, supdsub: supdsub, supe: supe, supedot: supedot, suphsol: suphsol, suphsub: suphsub, suplarr: suplarr, supmult: supmult, supnE: supnE, supne: supne, supplus: supplus, supset: supset, supseteq: supseteq, supseteqq: supseteqq, supsetneq: supsetneq, supsetneqq: supsetneqq, supsim: supsim, supsub: supsub, supsup: supsup, swArr: swArr, swarhk: swarhk, swarr: swarr, swarrow: swarrow, swnwar: swnwar, szli: szli, szlig: szlig, target: target, tau: tau, tbrk: tbrk, tcaron: tcaron, tcedil: tcedil, tcy: tcy, tdot: tdot, telrec: telrec, tfr: tfr, there4: there4, therefore: therefore, theta: theta, thetasym: thetasym, thetav: thetav, thickapprox: thickapprox, thicksim: thicksim, thinsp: thinsp, thkap: thkap, thksim: thksim, thor: thor, thorn: thorn, tilde: tilde, time: time, times: times, timesb: timesb, timesbar: timesbar, timesd: timesd, tint: tint, toea: toea, top: top, topbot: topbot, topcir: topcir, topf: topf, topfork: topfork, tosa: tosa, tprime: tprime, trade: trade, triangle: triangle, triangledown: triangledown, triangleleft: triangleleft, trianglelefteq: trianglelefteq, triangleq: triangleq, triangleright: triangleright, trianglerighteq: trianglerighteq, tridot: tridot, trie: trie, triminus: triminus, triplus: triplus, trisb: trisb, tritime: tritime, trpezium: trpezium, tscr: tscr, tscy: tscy, tshcy: tshcy, tstrok: tstrok, twixt: twixt, twoheadleftarrow: twoheadleftarrow, twoheadrightarrow: twoheadrightarrow, uArr: uArr, uHar: uHar, uacut: uacut, uacute: uacute, uarr: uarr, ubrcy: ubrcy, ubreve: ubreve, ucir: ucir, ucirc: ucirc, ucy: ucy, udarr: udarr, udblac: udblac, udhar: udhar, ufisht: ufisht, ufr: ufr, ugrav: ugrav, ugrave: ugrave, uharl: uharl, uharr: uharr, uhblk: uhblk, ulcorn: ulcorn, ulcorner: ulcorner, ulcrop: ulcrop, ultri: ultri, umacr: umacr, um: um, uml: uml, uogon: uogon, uopf: uopf, uparrow: uparrow, updownarrow: updownarrow, upharpoonleft: upharpoonleft, upharpoonright: upharpoonright, uplus: uplus, upsi: upsi, upsih: upsih, upsilon: upsilon, upuparrows: upuparrows, urcorn: urcorn, urcorner: urcorner, urcrop: urcrop, uring: uring, urtri: urtri, uscr: uscr, utdot: utdot, utilde: utilde, utri: utri, utrif: utrif, uuarr: uuarr, uum: uum, uuml: uuml, uwangle: uwangle, vArr: vArr, vBar: vBar, vBarv: vBarv, vDash: vDash, vangrt: vangrt, varepsilon: varepsilon, varkappa: varkappa, varnothing: varnothing, varphi: varphi, varpi: varpi, varpropto: varpropto, varr: varr, varrho: varrho, varsigma: varsigma, varsubsetneq: varsubsetneq, varsubsetneqq: varsubsetneqq, varsupsetneq: varsupsetneq, varsupsetneqq: varsupsetneqq, vartheta: vartheta, vartriangleleft: vartriangleleft, vartriangleright: vartriangleright, vcy: vcy, vdash: vdash, vee: vee, veebar: veebar, veeeq: veeeq, vellip: vellip, verbar: verbar, vert: vert, vfr: vfr, vltri: vltri, vnsub: vnsub, vnsup: vnsup, vopf: vopf, vprop: vprop, vrtri: vrtri, vscr: vscr, vsubnE: vsubnE, vsubne: vsubne, vsupnE: vsupnE, vsupne: vsupne, vzigzag: vzigzag, wcirc: wcirc, wedbar: wedbar, wedge: wedge, wedgeq: wedgeq, weierp: weierp, wfr: wfr, wopf: wopf, wp: wp, wr: wr, wreath: wreath, wscr: wscr, xcap: xcap, xcirc: xcirc, xcup: xcup, xdtri: xdtri, xfr: xfr, xhArr: xhArr, xharr: xharr, xi: xi, xlArr: xlArr, xlarr: xlarr, xmap: xmap, xnis: xnis, xodot: xodot, xopf: xopf, xoplus: xoplus, xotime: xotime, xrArr: xrArr, xrarr: xrarr, xscr: xscr, xsqcup: xsqcup, xuplus: xuplus, xutri: xutri, xvee: xvee, xwedge: xwedge, yacut: yacut, yacute: yacute, yacy: yacy, ycirc: ycirc, ycy: ycy, ye: ye, yen: yen, yfr: yfr, yicy: yicy, yopf: yopf, yscr: yscr, yucy: yucy, yum: yum, yuml: yuml, zacute: zacute, zcaron: zcaron, zcy: zcy, zdot: zdot, zeetrf: zeetrf, zeta: zeta, zfr: zfr, zhcy: zhcy, zigrarr: zigrarr, zopf: zopf, zscr: zscr, zwj: zwj, zwnj: zwnj }; var characterEntities = /*#__PURE__*/Object.freeze({ __proto__: null, AEli: AEli, AElig: AElig, AM: AM, AMP: AMP, Aacut: Aacut, Aacute: Aacute, Abreve: Abreve, Acir: Acir, Acirc: Acirc, Acy: Acy, Afr: Afr, Agrav: Agrav, Agrave: Agrave, Alpha: Alpha, Amacr: Amacr, And: And, Aogon: Aogon, Aopf: Aopf, ApplyFunction: ApplyFunction, Arin: Arin, Aring: Aring, Ascr: Ascr, Assign: Assign, Atild: Atild, Atilde: Atilde, Aum: Aum, Auml: Auml, Backslash: Backslash, Barv: Barv, Barwed: Barwed, Bcy: Bcy, Because: Because, Bernoullis: Bernoullis, Beta: Beta, Bfr: Bfr, Bopf: Bopf, Breve: Breve, Bscr: Bscr, Bumpeq: Bumpeq, CHcy: CHcy, COP: COP, COPY: COPY, Cacute: Cacute, Cap: Cap, CapitalDifferentialD: CapitalDifferentialD, Cayleys: Cayleys, Ccaron: Ccaron, Ccedi: Ccedi, Ccedil: Ccedil, Ccirc: Ccirc, Cconint: Cconint, Cdot: Cdot, Cedilla: Cedilla, CenterDot: CenterDot, Cfr: Cfr, Chi: Chi, CircleDot: CircleDot, CircleMinus: CircleMinus, CirclePlus: CirclePlus, CircleTimes: CircleTimes, ClockwiseContourIntegral: ClockwiseContourIntegral, CloseCurlyDoubleQuote: CloseCurlyDoubleQuote, CloseCurlyQuote: CloseCurlyQuote, Colon: Colon, Colone: Colone, Congruent: Congruent, Conint: Conint, ContourIntegral: ContourIntegral, Copf: Copf, Coproduct: Coproduct, CounterClockwiseContourIntegral: CounterClockwiseContourIntegral, Cross: Cross, Cscr: Cscr, Cup: Cup, CupCap: CupCap, DD: DD, DDotrahd: DDotrahd, DJcy: DJcy, DScy: DScy, DZcy: DZcy, Dagger: Dagger, Darr: Darr, Dashv: Dashv, Dcaron: Dcaron, Dcy: Dcy, Del: Del, Delta: Delta, Dfr: Dfr, DiacriticalAcute: DiacriticalAcute, DiacriticalDot: DiacriticalDot, DiacriticalDoubleAcute: DiacriticalDoubleAcute, DiacriticalGrave: DiacriticalGrave, DiacriticalTilde: DiacriticalTilde, Diamond: Diamond, DifferentialD: DifferentialD, Dopf: Dopf, Dot: Dot, DotDot: DotDot, DotEqual: DotEqual, DoubleContourIntegral: DoubleContourIntegral, DoubleDot: DoubleDot, DoubleDownArrow: DoubleDownArrow, DoubleLeftArrow: DoubleLeftArrow, DoubleLeftRightArrow: DoubleLeftRightArrow, DoubleLeftTee: DoubleLeftTee, DoubleLongLeftArrow: DoubleLongLeftArrow, DoubleLongLeftRightArrow: DoubleLongLeftRightArrow, DoubleLongRightArrow: DoubleLongRightArrow, DoubleRightArrow: DoubleRightArrow, DoubleRightTee: DoubleRightTee, DoubleUpArrow: DoubleUpArrow, DoubleUpDownArrow: DoubleUpDownArrow, DoubleVerticalBar: DoubleVerticalBar, DownArrow: DownArrow, DownArrowBar: DownArrowBar, DownArrowUpArrow: DownArrowUpArrow, DownBreve: DownBreve, DownLeftRightVector: DownLeftRightVector, DownLeftTeeVector: DownLeftTeeVector, DownLeftVector: DownLeftVector, DownLeftVectorBar: DownLeftVectorBar, DownRightTeeVector: DownRightTeeVector, DownRightVector: DownRightVector, DownRightVectorBar: DownRightVectorBar, DownTee: DownTee, DownTeeArrow: DownTeeArrow, Downarrow: Downarrow, Dscr: Dscr, Dstrok: Dstrok, ENG: ENG, ET: ET, ETH: ETH, Eacut: Eacut, Eacute: Eacute, Ecaron: Ecaron, Ecir: Ecir, Ecirc: Ecirc, Ecy: Ecy, Edot: Edot, Efr: Efr, Egrav: Egrav, Egrave: Egrave, Element: Element, Emacr: Emacr, EmptySmallSquare: EmptySmallSquare, EmptyVerySmallSquare: EmptyVerySmallSquare, Eogon: Eogon, Eopf: Eopf, Epsilon: Epsilon, Equal: Equal, EqualTilde: EqualTilde, Equilibrium: Equilibrium, Escr: Escr, Esim: Esim, Eta: Eta, Eum: Eum, Euml: Euml, Exists: Exists, ExponentialE: ExponentialE, Fcy: Fcy, Ffr: Ffr, FilledSmallSquare: FilledSmallSquare, FilledVerySmallSquare: FilledVerySmallSquare, Fopf: Fopf, ForAll: ForAll, Fouriertrf: Fouriertrf, Fscr: Fscr, GJcy: GJcy, G: G, GT: GT, Gamma: Gamma, Gammad: Gammad, Gbreve: Gbreve, Gcedil: Gcedil, Gcirc: Gcirc, Gcy: Gcy, Gdot: Gdot, Gfr: Gfr, Gg: Gg, Gopf: Gopf, GreaterEqual: GreaterEqual, GreaterEqualLess: GreaterEqualLess, GreaterFullEqual: GreaterFullEqual, GreaterGreater: GreaterGreater, GreaterLess: GreaterLess, GreaterSlantEqual: GreaterSlantEqual, GreaterTilde: GreaterTilde, Gscr: Gscr, Gt: Gt, HARDcy: HARDcy, Hacek: Hacek, Hat: Hat, Hcirc: Hcirc, Hfr: Hfr, HilbertSpace: HilbertSpace, Hopf: Hopf, HorizontalLine: HorizontalLine, Hscr: Hscr, Hstrok: Hstrok, HumpDownHump: HumpDownHump, HumpEqual: HumpEqual, IEcy: IEcy, IJlig: IJlig, IOcy: IOcy, Iacut: Iacut, Iacute: Iacute, Icir: Icir, Icirc: Icirc, Icy: Icy, Idot: Idot, Ifr: Ifr, Igrav: Igrav, Igrave: Igrave, Im: Im, Imacr: Imacr, ImaginaryI: ImaginaryI, Implies: Implies, Int: Int, Integral: Integral, Intersection: Intersection, InvisibleComma: InvisibleComma, InvisibleTimes: InvisibleTimes, Iogon: Iogon, Iopf: Iopf, Iota: Iota, Iscr: Iscr, Itilde: Itilde, Iukcy: Iukcy, Ium: Ium, Iuml: Iuml, Jcirc: Jcirc, Jcy: Jcy, Jfr: Jfr, Jopf: Jopf, Jscr: Jscr, Jsercy: Jsercy, Jukcy: Jukcy, KHcy: KHcy, KJcy: KJcy, Kappa: Kappa, Kcedil: Kcedil, Kcy: Kcy, Kfr: Kfr, Kopf: Kopf, Kscr: Kscr, LJcy: LJcy, L: L, LT: LT, Lacute: Lacute, Lambda: Lambda, Lang: Lang, Laplacetrf: Laplacetrf, Larr: Larr, Lcaron: Lcaron, Lcedil: Lcedil, Lcy: Lcy, LeftAngleBracket: LeftAngleBracket, LeftArrow: LeftArrow, LeftArrowBar: LeftArrowBar, LeftArrowRightArrow: LeftArrowRightArrow, LeftCeiling: LeftCeiling, LeftDoubleBracket: LeftDoubleBracket, LeftDownTeeVector: LeftDownTeeVector, LeftDownVector: LeftDownVector, LeftDownVectorBar: LeftDownVectorBar, LeftFloor: LeftFloor, LeftRightArrow: LeftRightArrow, LeftRightVector: LeftRightVector, LeftTee: LeftTee, LeftTeeArrow: LeftTeeArrow, LeftTeeVector: LeftTeeVector, LeftTriangle: LeftTriangle, LeftTriangleBar: LeftTriangleBar, LeftTriangleEqual: LeftTriangleEqual, LeftUpDownVector: LeftUpDownVector, LeftUpTeeVector: LeftUpTeeVector, LeftUpVector: LeftUpVector, LeftUpVectorBar: LeftUpVectorBar, LeftVector: LeftVector, LeftVectorBar: LeftVectorBar, Leftarrow: Leftarrow, Leftrightarrow: Leftrightarrow, LessEqualGreater: LessEqualGreater, LessFullEqual: LessFullEqual, LessGreater: LessGreater, LessLess: LessLess, LessSlantEqual: LessSlantEqual, LessTilde: LessTilde, Lfr: Lfr, Ll: Ll, Lleftarrow: Lleftarrow, Lmidot: Lmidot, LongLeftArrow: LongLeftArrow, LongLeftRightArrow: LongLeftRightArrow, LongRightArrow: LongRightArrow, Longleftarrow: Longleftarrow, Longleftrightarrow: Longleftrightarrow, Longrightarrow: Longrightarrow, Lopf: Lopf, LowerLeftArrow: LowerLeftArrow, LowerRightArrow: LowerRightArrow, Lscr: Lscr, Lsh: Lsh, Lstrok: Lstrok, Lt: Lt, Mcy: Mcy, MediumSpace: MediumSpace, Mellintrf: Mellintrf, Mfr: Mfr, MinusPlus: MinusPlus, Mopf: Mopf, Mscr: Mscr, Mu: Mu, NJcy: NJcy, Nacute: Nacute, Ncaron: Ncaron, Ncedil: Ncedil, Ncy: Ncy, NegativeMediumSpace: NegativeMediumSpace, NegativeThickSpace: NegativeThickSpace, NegativeThinSpace: NegativeThinSpace, NegativeVeryThinSpace: NegativeVeryThinSpace, NestedGreaterGreater: NestedGreaterGreater, NestedLessLess: NestedLessLess, NewLine: NewLine, Nfr: Nfr, NoBreak: NoBreak, NonBreakingSpace: NonBreakingSpace, Nopf: Nopf, Not: Not, NotCongruent: NotCongruent, NotCupCap: NotCupCap, NotDoubleVerticalBar: NotDoubleVerticalBar, NotElement: NotElement, NotEqual: NotEqual, NotEqualTilde: NotEqualTilde, NotExists: NotExists, NotGreater: NotGreater, NotGreaterEqual: NotGreaterEqual, NotGreaterFullEqual: NotGreaterFullEqual, NotGreaterGreater: NotGreaterGreater, NotGreaterLess: NotGreaterLess, NotGreaterSlantEqual: NotGreaterSlantEqual, NotGreaterTilde: NotGreaterTilde, NotHumpDownHump: NotHumpDownHump, NotHumpEqual: NotHumpEqual, NotLeftTriangle: NotLeftTriangle, NotLeftTriangleBar: NotLeftTriangleBar, NotLeftTriangleEqual: NotLeftTriangleEqual, NotLess: NotLess, NotLessEqual: NotLessEqual, NotLessGreater: NotLessGreater, NotLessLess: NotLessLess, NotLessSlantEqual: NotLessSlantEqual, NotLessTilde: NotLessTilde, NotNestedGreaterGreater: NotNestedGreaterGreater, NotNestedLessLess: NotNestedLessLess, NotPrecedes: NotPrecedes, NotPrecedesEqual: NotPrecedesEqual, NotPrecedesSlantEqual: NotPrecedesSlantEqual, NotReverseElement: NotReverseElement, NotRightTriangle: NotRightTriangle, NotRightTriangleBar: NotRightTriangleBar, NotRightTriangleEqual: NotRightTriangleEqual, NotSquareSubset: NotSquareSubset, NotSquareSubsetEqual: NotSquareSubsetEqual, NotSquareSuperset: NotSquareSuperset, NotSquareSupersetEqual: NotSquareSupersetEqual, NotSubset: NotSubset, NotSubsetEqual: NotSubsetEqual, NotSucceeds: NotSucceeds, NotSucceedsEqual: NotSucceedsEqual, NotSucceedsSlantEqual: NotSucceedsSlantEqual, NotSucceedsTilde: NotSucceedsTilde, NotSuperset: NotSuperset, NotSupersetEqual: NotSupersetEqual, NotTilde: NotTilde, NotTildeEqual: NotTildeEqual, NotTildeFullEqual: NotTildeFullEqual, NotTildeTilde: NotTildeTilde, NotVerticalBar: NotVerticalBar, Nscr: Nscr, Ntild: Ntild, Ntilde: Ntilde, Nu: Nu, OElig: OElig, Oacut: Oacut, Oacute: Oacute, Ocir: Ocir, Ocirc: Ocirc, Ocy: Ocy, Odblac: Odblac, Ofr: Ofr, Ograv: Ograv, Ograve: Ograve, Omacr: Omacr, Omega: Omega, Omicron: Omicron, Oopf: Oopf, OpenCurlyDoubleQuote: OpenCurlyDoubleQuote, OpenCurlyQuote: OpenCurlyQuote, Or: Or, Oscr: Oscr, Oslas: Oslas, Oslash: Oslash, Otild: Otild, Otilde: Otilde, Otimes: Otimes, Oum: Oum, Ouml: Ouml, OverBar: OverBar, OverBrace: OverBrace, OverBracket: OverBracket, OverParenthesis: OverParenthesis, PartialD: PartialD, Pcy: Pcy, Pfr: Pfr, Phi: Phi, Pi: Pi, PlusMinus: PlusMinus, Poincareplane: Poincareplane, Popf: Popf, Pr: Pr, Precedes: Precedes, PrecedesEqual: PrecedesEqual, PrecedesSlantEqual: PrecedesSlantEqual, PrecedesTilde: PrecedesTilde, Prime: Prime, Product: Product, Proportion: Proportion, Proportional: Proportional, Pscr: Pscr, Psi: Psi, QUO: QUO, QUOT: QUOT, Qfr: Qfr, Qopf: Qopf, Qscr: Qscr, RBarr: RBarr, RE: RE, REG: REG, Racute: Racute, Rang: Rang, Rarr: Rarr, Rarrtl: Rarrtl, Rcaron: Rcaron, Rcedil: Rcedil, Rcy: Rcy, Re: Re, ReverseElement: ReverseElement, ReverseEquilibrium: ReverseEquilibrium, ReverseUpEquilibrium: ReverseUpEquilibrium, Rfr: Rfr, Rho: Rho, RightAngleBracket: RightAngleBracket, RightArrow: RightArrow, RightArrowBar: RightArrowBar, RightArrowLeftArrow: RightArrowLeftArrow, RightCeiling: RightCeiling, RightDoubleBracket: RightDoubleBracket, RightDownTeeVector: RightDownTeeVector, RightDownVector: RightDownVector, RightDownVectorBar: RightDownVectorBar, RightFloor: RightFloor, RightTee: RightTee, RightTeeArrow: RightTeeArrow, RightTeeVector: RightTeeVector, RightTriangle: RightTriangle, RightTriangleBar: RightTriangleBar, RightTriangleEqual: RightTriangleEqual, RightUpDownVector: RightUpDownVector, RightUpTeeVector: RightUpTeeVector, RightUpVector: RightUpVector, RightUpVectorBar: RightUpVectorBar, RightVector: RightVector, RightVectorBar: RightVectorBar, Rightarrow: Rightarrow, Ropf: Ropf, RoundImplies: RoundImplies, Rrightarrow: Rrightarrow, Rscr: Rscr, Rsh: Rsh, RuleDelayed: RuleDelayed, SHCHcy: SHCHcy, SHcy: SHcy, SOFTcy: SOFTcy, Sacute: Sacute, Sc: Sc, Scaron: Scaron, Scedil: Scedil, Scirc: Scirc, Scy: Scy, Sfr: Sfr, ShortDownArrow: ShortDownArrow, ShortLeftArrow: ShortLeftArrow, ShortRightArrow: ShortRightArrow, ShortUpArrow: ShortUpArrow, Sigma: Sigma, SmallCircle: SmallCircle, Sopf: Sopf, Sqrt: Sqrt, Square: Square, SquareIntersection: SquareIntersection, SquareSubset: SquareSubset, SquareSubsetEqual: SquareSubsetEqual, SquareSuperset: SquareSuperset, SquareSupersetEqual: SquareSupersetEqual, SquareUnion: SquareUnion, Sscr: Sscr, Star: Star, Sub: Sub, Subset: Subset, SubsetEqual: SubsetEqual, Succeeds: Succeeds, SucceedsEqual: SucceedsEqual, SucceedsSlantEqual: SucceedsSlantEqual, SucceedsTilde: SucceedsTilde, SuchThat: SuchThat, Sum: Sum, Sup: Sup, Superset: Superset, SupersetEqual: SupersetEqual, Supset: Supset, THOR: THOR, THORN: THORN, TRADE: TRADE, TSHcy: TSHcy, TScy: TScy, Tab: Tab, Tau: Tau, Tcaron: Tcaron, Tcedil: Tcedil, Tcy: Tcy, Tfr: Tfr, Therefore: Therefore, Theta: Theta, ThickSpace: ThickSpace, ThinSpace: ThinSpace, Tilde: Tilde, TildeEqual: TildeEqual, TildeFullEqual: TildeFullEqual, TildeTilde: TildeTilde, Topf: Topf, TripleDot: TripleDot, Tscr: Tscr, Tstrok: Tstrok, Uacut: Uacut, Uacute: Uacute, Uarr: Uarr, Uarrocir: Uarrocir, Ubrcy: Ubrcy, Ubreve: Ubreve, Ucir: Ucir, Ucirc: Ucirc, Ucy: Ucy, Udblac: Udblac, Ufr: Ufr, Ugrav: Ugrav, Ugrave: Ugrave, Umacr: Umacr, UnderBar: UnderBar, UnderBrace: UnderBrace, UnderBracket: UnderBracket, UnderParenthesis: UnderParenthesis, Union: Union, UnionPlus: UnionPlus, Uogon: Uogon, Uopf: Uopf, UpArrow: UpArrow, UpArrowBar: UpArrowBar, UpArrowDownArrow: UpArrowDownArrow, UpDownArrow: UpDownArrow, UpEquilibrium: UpEquilibrium, UpTee: UpTee, UpTeeArrow: UpTeeArrow, Uparrow: Uparrow, Updownarrow: Updownarrow, UpperLeftArrow: UpperLeftArrow, UpperRightArrow: UpperRightArrow, Upsi: Upsi, Upsilon: Upsilon, Uring: Uring, Uscr: Uscr, Utilde: Utilde, Uum: Uum, Uuml: Uuml, VDash: VDash, Vbar: Vbar, Vcy: Vcy, Vdash: Vdash, Vdashl: Vdashl, Vee: Vee, Verbar: Verbar, Vert: Vert, VerticalBar: VerticalBar, VerticalLine: VerticalLine, VerticalSeparator: VerticalSeparator, VerticalTilde: VerticalTilde, VeryThinSpace: VeryThinSpace, Vfr: Vfr, Vopf: Vopf, Vscr: Vscr, Vvdash: Vvdash, Wcirc: Wcirc, Wedge: Wedge, Wfr: Wfr, Wopf: Wopf, Wscr: Wscr, Xfr: Xfr, Xi: Xi, Xopf: Xopf, Xscr: Xscr, YAcy: YAcy, YIcy: YIcy, YUcy: YUcy, Yacut: Yacut, Yacute: Yacute, Ycirc: Ycirc, Ycy: Ycy, Yfr: Yfr, Yopf: Yopf, Yscr: Yscr, Yuml: Yuml, ZHcy: ZHcy, Zacute: Zacute, Zcaron: Zcaron, Zcy: Zcy, Zdot: Zdot, ZeroWidthSpace: ZeroWidthSpace, Zeta: Zeta, Zfr: Zfr, Zopf: Zopf, Zscr: Zscr, aacut: aacut, aacute: aacute, abreve: abreve, ac: ac, acE: acE, acd: acd, acir: acir, acirc: acirc, acut: acut, acute: acute, acy: acy, aeli: aeli, aelig: aelig, af: af, afr: afr, agrav: agrav, agrave: agrave, alefsym: alefsym, aleph: aleph, alpha: alpha, amacr: amacr, amalg: amalg, am: am, amp: amp, and: and, andand: andand, andd: andd, andslope: andslope, andv: andv, ang: ang, ange: ange, angle: angle, angmsd: angmsd, angmsdaa: angmsdaa, angmsdab: angmsdab, angmsdac: angmsdac, angmsdad: angmsdad, angmsdae: angmsdae, angmsdaf: angmsdaf, angmsdag: angmsdag, angmsdah: angmsdah, angrt: angrt, angrtvb: angrtvb, angrtvbd: angrtvbd, angsph: angsph, angst: angst, angzarr: angzarr, aogon: aogon, aopf: aopf, ap: ap, apE: apE, apacir: apacir, ape: ape, apid: apid, apos: apos, approx: approx, approxeq: approxeq, arin: arin, aring: aring, ascr: ascr, ast: ast, asymp: asymp, asympeq: asympeq, atild: atild, atilde: atilde, aum: aum, auml: auml, awconint: awconint, awint: awint, bNot: bNot, backcong: backcong, backepsilon: backepsilon, backprime: backprime, backsim: backsim, backsimeq: backsimeq, barvee: barvee, barwed: barwed, barwedge: barwedge, bbrk: bbrk, bbrktbrk: bbrktbrk, bcong: bcong, bcy: bcy, bdquo: bdquo, becaus: becaus, because: because, bemptyv: bemptyv, bepsi: bepsi, bernou: bernou, beta: beta, beth: beth, between: between, bfr: bfr, bigcap: bigcap, bigcirc: bigcirc, bigcup: bigcup, bigodot: bigodot, bigoplus: bigoplus, bigotimes: bigotimes, bigsqcup: bigsqcup, bigstar: bigstar, bigtriangledown: bigtriangledown, bigtriangleup: bigtriangleup, biguplus: biguplus, bigvee: bigvee, bigwedge: bigwedge, bkarow: bkarow, blacklozenge: blacklozenge, blacksquare: blacksquare, blacktriangle: blacktriangle, blacktriangledown: blacktriangledown, blacktriangleleft: blacktriangleleft, blacktriangleright: blacktriangleright, blank: blank, blk12: blk12, blk14: blk14, blk34: blk34, block: block, bne: bne, bnequiv: bnequiv, bnot: bnot, bopf: bopf, bot: bot, bottom: bottom, bowtie: bowtie, boxDL: boxDL, boxDR: boxDR, boxDl: boxDl, boxDr: boxDr, boxH: boxH, boxHD: boxHD, boxHU: boxHU, boxHd: boxHd, boxHu: boxHu, boxUL: boxUL, boxUR: boxUR, boxUl: boxUl, boxUr: boxUr, boxV: boxV, boxVH: boxVH, boxVL: boxVL, boxVR: boxVR, boxVh: boxVh, boxVl: boxVl, boxVr: boxVr, boxbox: boxbox, boxdL: boxdL, boxdR: boxdR, boxdl: boxdl, boxdr: boxdr, boxh: boxh, boxhD: boxhD, boxhU: boxhU, boxhd: boxhd, boxhu: boxhu, boxminus: boxminus, boxplus: boxplus, boxtimes: boxtimes, boxuL: boxuL, boxuR: boxuR, boxul: boxul, boxur: boxur, boxv: boxv, boxvH: boxvH, boxvL: boxvL, boxvR: boxvR, boxvh: boxvh, boxvl: boxvl, boxvr: boxvr, bprime: bprime, breve: breve, brvba: brvba, brvbar: brvbar, bscr: bscr, bsemi: bsemi, bsim: bsim, bsime: bsime, bsol: bsol, bsolb: bsolb, bsolhsub: bsolhsub, bull: bull, bullet: bullet, bump: bump, bumpE: bumpE, bumpe: bumpe, bumpeq: bumpeq, cacute: cacute, cap: cap, capand: capand, capbrcup: capbrcup, capcap: capcap, capcup: capcup, capdot: capdot, caps: caps, caret: caret, caron: caron, ccaps: ccaps, ccaron: ccaron, ccedi: ccedi, ccedil: ccedil, ccirc: ccirc, ccups: ccups, ccupssm: ccupssm, cdot: cdot, cedi: cedi, cedil: cedil, cemptyv: cemptyv, cen: cen, cent: cent, centerdot: centerdot, cfr: cfr, chcy: chcy, check: check$2, checkmark: checkmark, chi: chi, cir: cir, cirE: cirE, circ: circ, circeq: circeq, circlearrowleft: circlearrowleft, circlearrowright: circlearrowright, circledR: circledR, circledS: circledS, circledast: circledast, circledcirc: circledcirc, circleddash: circleddash, cire: cire, cirfnint: cirfnint, cirmid: cirmid, cirscir: cirscir, clubs: clubs, clubsuit: clubsuit, colon: colon, colone: colone, coloneq: coloneq, comma: comma, commat: commat, comp: comp, compfn: compfn, complement: complement, complexes: complexes, cong: cong, congdot: congdot, conint: conint, copf: copf, coprod: coprod, cop: cop, copy: copy$1, copysr: copysr, crarr: crarr, cross: cross, cscr: cscr, csub: csub, csube: csube, csup: csup, csupe: csupe, ctdot: ctdot, cudarrl: cudarrl, cudarrr: cudarrr, cuepr: cuepr, cuesc: cuesc, cularr: cularr, cularrp: cularrp, cup: cup, cupbrcap: cupbrcap, cupcap: cupcap, cupcup: cupcup, cupdot: cupdot, cupor: cupor, cups: cups, curarr: curarr, curarrm: curarrm, curlyeqprec: curlyeqprec, curlyeqsucc: curlyeqsucc, curlyvee: curlyvee, curlywedge: curlywedge, curre: curre, curren: curren, curvearrowleft: curvearrowleft, curvearrowright: curvearrowright, cuvee: cuvee, cuwed: cuwed, cwconint: cwconint, cwint: cwint, cylcty: cylcty, dArr: dArr, dHar: dHar, dagger: dagger, daleth: daleth, darr: darr, dash: dash, dashv: dashv, dbkarow: dbkarow, dblac: dblac, dcaron: dcaron, dcy: dcy, dd: dd, ddagger: ddagger, ddarr: ddarr, ddotseq: ddotseq, de: de, deg: deg, delta: delta, demptyv: demptyv, dfisht: dfisht, dfr: dfr, dharl: dharl, dharr: dharr, diam: diam, diamond: diamond, diamondsuit: diamondsuit, diams: diams, die: die, digamma: digamma, disin: disin, div: div, divid: divid, divide: divide, divideontimes: divideontimes, divonx: divonx, djcy: djcy, dlcorn: dlcorn, dlcrop: dlcrop, dollar: dollar, dopf: dopf, dot: dot, doteq: doteq, doteqdot: doteqdot, dotminus: dotminus, dotplus: dotplus, dotsquare: dotsquare, doublebarwedge: doublebarwedge, downarrow: downarrow, downdownarrows: downdownarrows, downharpoonleft: downharpoonleft, downharpoonright: downharpoonright, drbkarow: drbkarow, drcorn: drcorn, drcrop: drcrop, dscr: dscr, dscy: dscy, dsol: dsol, dstrok: dstrok, dtdot: dtdot, dtri: dtri, dtrif: dtrif, duarr: duarr, duhar: duhar, dwangle: dwangle, dzcy: dzcy, dzigrarr: dzigrarr, eDDot: eDDot, eDot: eDot, eacut: eacut, eacute: eacute, easter: easter, ecaron: ecaron, ecir: ecir, ecirc: ecirc, ecolon: ecolon, ecy: ecy, edot: edot, ee: ee, efDot: efDot, efr: efr, eg: eg, egrav: egrav, egrave: egrave, egs: egs, egsdot: egsdot, el: el, elinters: elinters, ell: ell, els: els, elsdot: elsdot, emacr: emacr, empty: empty, emptyset: emptyset, emptyv: emptyv, emsp13: emsp13, emsp14: emsp14, emsp: emsp, eng: eng, ensp: ensp, eogon: eogon, eopf: eopf, epar: epar, eparsl: eparsl, eplus: eplus, epsi: epsi, epsilon: epsilon, epsiv: epsiv, eqcirc: eqcirc, eqcolon: eqcolon, eqsim: eqsim, eqslantgtr: eqslantgtr, eqslantless: eqslantless, equals: equals, equest: equest, equiv: equiv, equivDD: equivDD, eqvparsl: eqvparsl, erDot: erDot, erarr: erarr, escr: escr, esdot: esdot, esim: esim, eta: eta, et: et, eth: eth, eum: eum, euml: euml, euro: euro, excl: excl, exist: exist, expectation: expectation, exponentiale: exponentiale, fallingdotseq: fallingdotseq, fcy: fcy, female: female, ffilig: ffilig, fflig: fflig, ffllig: ffllig, ffr: ffr, filig: filig, fjlig: fjlig, flat: flat, fllig: fllig, fltns: fltns, fnof: fnof, fopf: fopf, forall: forall, fork: fork, forkv: forkv, fpartint: fpartint, frac1: frac1, frac12: frac12, frac13: frac13, frac14: frac14, frac15: frac15, frac16: frac16, frac18: frac18, frac23: frac23, frac25: frac25, frac3: frac3, frac34: frac34, frac35: frac35, frac38: frac38, frac45: frac45, frac56: frac56, frac58: frac58, frac78: frac78, frasl: frasl, frown: frown, fscr: fscr, gE: gE, gEl: gEl, gacute: gacute, gamma: gamma, gammad: gammad, gap: gap, gbreve: gbreve, gcirc: gcirc, gcy: gcy, gdot: gdot, ge: ge, gel: gel, geq: geq, geqq: geqq, geqslant: geqslant, ges: ges, gescc: gescc, gesdot: gesdot, gesdoto: gesdoto, gesdotol: gesdotol, gesl: gesl, gesles: gesles, gfr: gfr, gg: gg, ggg: ggg, gimel: gimel, gjcy: gjcy, gl: gl, glE: glE, gla: gla, glj: glj, gnE: gnE, gnap: gnap, gnapprox: gnapprox, gne: gne, gneq: gneq, gneqq: gneqq, gnsim: gnsim, gopf: gopf, grave: grave, gscr: gscr, gsim: gsim, gsime: gsime, gsiml: gsiml, g: g, gt: gt, gtcc: gtcc, gtcir: gtcir, gtdot: gtdot, gtlPar: gtlPar, gtquest: gtquest, gtrapprox: gtrapprox, gtrarr: gtrarr, gtrdot: gtrdot, gtreqless: gtreqless, gtreqqless: gtreqqless, gtrless: gtrless, gtrsim: gtrsim, gvertneqq: gvertneqq, gvnE: gvnE, hArr: hArr, hairsp: hairsp, half: half, hamilt: hamilt, hardcy: hardcy, harr: harr, harrcir: harrcir, harrw: harrw, hbar: hbar, hcirc: hcirc, hearts: hearts, heartsuit: heartsuit, hellip: hellip, hercon: hercon, hfr: hfr, hksearow: hksearow, hkswarow: hkswarow, hoarr: hoarr, homtht: homtht, hookleftarrow: hookleftarrow, hookrightarrow: hookrightarrow, hopf: hopf, horbar: horbar, hscr: hscr, hslash: hslash, hstrok: hstrok, hybull: hybull, hyphen: hyphen, iacut: iacut, iacute: iacute, ic: ic, icir: icir, icirc: icirc, icy: icy, iecy: iecy, iexc: iexc, iexcl: iexcl, iff: iff, ifr: ifr, igrav: igrav, igrave: igrave, ii: ii, iiiint: iiiint, iiint: iiint, iinfin: iinfin, iiota: iiota, ijlig: ijlig, imacr: imacr, image: image, imagline: imagline, imagpart: imagpart, imath: imath, imof: imof, imped: imped, incare: incare, infin: infin, infintie: infintie, inodot: inodot, int: int, intcal: intcal, integers: integers, intercal: intercal, intlarhk: intlarhk, intprod: intprod, iocy: iocy, iogon: iogon, iopf: iopf, iota: iota, iprod: iprod, iques: iques, iquest: iquest, iscr: iscr, isin: isin, isinE: isinE, isindot: isindot, isins: isins, isinsv: isinsv, isinv: isinv, it: it, itilde: itilde, iukcy: iukcy, ium: ium, iuml: iuml, jcirc: jcirc, jcy: jcy, jfr: jfr, jmath: jmath, jopf: jopf, jscr: jscr, jsercy: jsercy, jukcy: jukcy, kappa: kappa, kappav: kappav, kcedil: kcedil, kcy: kcy, kfr: kfr, kgreen: kgreen, khcy: khcy, kjcy: kjcy, kopf: kopf, kscr: kscr, lAarr: lAarr, lArr: lArr, lAtail: lAtail, lBarr: lBarr, lE: lE, lEg: lEg, lHar: lHar, lacute: lacute, laemptyv: laemptyv, lagran: lagran, lambda: lambda, lang: lang, langd: langd, langle: langle, lap: lap, laqu: laqu, laquo: laquo, larr: larr, larrb: larrb, larrbfs: larrbfs, larrfs: larrfs, larrhk: larrhk, larrlp: larrlp, larrpl: larrpl, larrsim: larrsim, larrtl: larrtl, lat: lat, latail: latail, late: late, lates: lates, lbarr: lbarr, lbbrk: lbbrk, lbrace: lbrace, lbrack: lbrack, lbrke: lbrke, lbrksld: lbrksld, lbrkslu: lbrkslu, lcaron: lcaron, lcedil: lcedil, lceil: lceil, lcub: lcub, lcy: lcy, ldca: ldca, ldquo: ldquo, ldquor: ldquor, ldrdhar: ldrdhar, ldrushar: ldrushar, ldsh: ldsh, le: le, leftarrow: leftarrow, leftarrowtail: leftarrowtail, leftharpoondown: leftharpoondown, leftharpoonup: leftharpoonup, leftleftarrows: leftleftarrows, leftrightarrow: leftrightarrow, leftrightarrows: leftrightarrows, leftrightharpoons: leftrightharpoons, leftrightsquigarrow: leftrightsquigarrow, leftthreetimes: leftthreetimes, leg: leg, leq: leq, leqq: leqq, leqslant: leqslant, les: les, lescc: lescc, lesdot: lesdot, lesdoto: lesdoto, lesdotor: lesdotor, lesg: lesg, lesges: lesges, lessapprox: lessapprox, lessdot: lessdot, lesseqgtr: lesseqgtr, lesseqqgtr: lesseqqgtr, lessgtr: lessgtr, lesssim: lesssim, lfisht: lfisht, lfloor: lfloor, lfr: lfr, lg: lg, lgE: lgE, lhard: lhard, lharu: lharu, lharul: lharul, lhblk: lhblk, ljcy: ljcy, ll: ll, llarr: llarr, llcorner: llcorner, llhard: llhard, lltri: lltri, lmidot: lmidot, lmoust: lmoust, lmoustache: lmoustache, lnE: lnE, lnap: lnap, lnapprox: lnapprox, lne: lne, lneq: lneq, lneqq: lneqq, lnsim: lnsim, loang: loang, loarr: loarr, lobrk: lobrk, longleftarrow: longleftarrow, longleftrightarrow: longleftrightarrow, longmapsto: longmapsto, longrightarrow: longrightarrow, looparrowleft: looparrowleft, looparrowright: looparrowright, lopar: lopar, lopf: lopf, loplus: loplus, lotimes: lotimes, lowast: lowast, lowbar: lowbar, loz: loz, lozenge: lozenge, lozf: lozf, lpar: lpar, lparlt: lparlt, lrarr: lrarr, lrcorner: lrcorner, lrhar: lrhar, lrhard: lrhard, lrm: lrm, lrtri: lrtri, lsaquo: lsaquo, lscr: lscr, lsh: lsh, lsim: lsim, lsime: lsime, lsimg: lsimg, lsqb: lsqb, lsquo: lsquo, lsquor: lsquor, lstrok: lstrok, l: l, lt: lt, ltcc: ltcc, ltcir: ltcir, ltdot: ltdot, lthree: lthree, ltimes: ltimes, ltlarr: ltlarr, ltquest: ltquest, ltrPar: ltrPar, ltri: ltri, ltrie: ltrie, ltrif: ltrif, lurdshar: lurdshar, luruhar: luruhar, lvertneqq: lvertneqq, lvnE: lvnE, mDDot: mDDot, mac: mac, macr: macr, male: male, malt: malt, maltese: maltese, map: map$2, mapsto: mapsto, mapstodown: mapstodown, mapstoleft: mapstoleft, mapstoup: mapstoup, marker: marker, mcomma: mcomma, mcy: mcy, mdash: mdash, measuredangle: measuredangle, mfr: mfr, mho: mho, micr: micr, micro: micro, mid: mid, midast: midast, midcir: midcir, middo: middo, middot: middot, minus: minus, minusb: minusb, minusd: minusd, minusdu: minusdu, mlcp: mlcp, mldr: mldr, mnplus: mnplus, models: models$2, mopf: mopf, mp: mp, mscr: mscr, mstpos: mstpos, mu: mu, multimap: multimap, mumap: mumap, nGg: nGg, nGt: nGt, nGtv: nGtv, nLeftarrow: nLeftarrow, nLeftrightarrow: nLeftrightarrow, nLl: nLl, nLt: nLt, nLtv: nLtv, nRightarrow: nRightarrow, nVDash: nVDash, nVdash: nVdash, nabla: nabla, nacute: nacute, nang: nang, nap: nap, napE: napE, napid: napid, napos: napos, napprox: napprox, natur: natur, natural: natural, naturals: naturals, nbs: nbs, nbsp: nbsp, nbump: nbump, nbumpe: nbumpe, ncap: ncap, ncaron: ncaron, ncedil: ncedil, ncong: ncong, ncongdot: ncongdot, ncup: ncup, ncy: ncy, ndash: ndash, ne: ne, neArr: neArr, nearhk: nearhk, nearr: nearr, nearrow: nearrow, nedot: nedot, nequiv: nequiv, nesear: nesear, nesim: nesim, nexist: nexist, nexists: nexists, nfr: nfr, ngE: ngE, nge: nge, ngeq: ngeq, ngeqq: ngeqq, ngeqslant: ngeqslant, nges: nges, ngsim: ngsim, ngt: ngt, ngtr: ngtr, nhArr: nhArr, nharr: nharr, nhpar: nhpar, ni: ni, nis: nis, nisd: nisd, niv: niv, njcy: njcy, nlArr: nlArr, nlE: nlE, nlarr: nlarr, nldr: nldr, nle: nle, nleftarrow: nleftarrow, nleftrightarrow: nleftrightarrow, nleq: nleq, nleqq: nleqq, nleqslant: nleqslant, nles: nles, nless: nless, nlsim: nlsim, nlt: nlt, nltri: nltri, nltrie: nltrie, nmid: nmid, nopf: nopf, no: no, not: not, notin: notin, notinE: notinE, notindot: notindot, notinva: notinva, notinvb: notinvb, notinvc: notinvc, notni: notni, notniva: notniva, notnivb: notnivb, notnivc: notnivc, npar: npar, nparallel: nparallel, nparsl: nparsl, npart: npart, npolint: npolint, npr: npr, nprcue: nprcue, npre: npre, nprec: nprec, npreceq: npreceq, nrArr: nrArr, nrarr: nrarr, nrarrc: nrarrc, nrarrw: nrarrw, nrightarrow: nrightarrow, nrtri: nrtri, nrtrie: nrtrie, nsc: nsc, nsccue: nsccue, nsce: nsce, nscr: nscr, nshortmid: nshortmid, nshortparallel: nshortparallel, nsim: nsim, nsime: nsime, nsimeq: nsimeq, nsmid: nsmid, nspar: nspar, nsqsube: nsqsube, nsqsupe: nsqsupe, nsub: nsub, nsubE: nsubE, nsube: nsube, nsubset: nsubset, nsubseteq: nsubseteq, nsubseteqq: nsubseteqq, nsucc: nsucc, nsucceq: nsucceq, nsup: nsup, nsupE: nsupE, nsupe: nsupe, nsupset: nsupset, nsupseteq: nsupseteq, nsupseteqq: nsupseteqq, ntgl: ntgl, ntild: ntild, ntilde: ntilde, ntlg: ntlg, ntriangleleft: ntriangleleft, ntrianglelefteq: ntrianglelefteq, ntriangleright: ntriangleright, ntrianglerighteq: ntrianglerighteq, nu: nu, num: num, numero: numero, numsp: numsp, nvDash: nvDash, nvHarr: nvHarr, nvap: nvap, nvdash: nvdash, nvge: nvge, nvgt: nvgt, nvinfin: nvinfin, nvlArr: nvlArr, nvle: nvle, nvlt: nvlt, nvltrie: nvltrie, nvrArr: nvrArr, nvrtrie: nvrtrie, nvsim: nvsim, nwArr: nwArr, nwarhk: nwarhk, nwarr: nwarr, nwarrow: nwarrow, nwnear: nwnear, oS: oS, oacut: oacut, oacute: oacute, oast: oast, ocir: ocir, ocirc: ocirc, ocy: ocy, odash: odash, odblac: odblac, odiv: odiv, odot: odot, odsold: odsold, oelig: oelig, ofcir: ofcir, ofr: ofr, ogon: ogon, ograv: ograv, ograve: ograve, ogt: ogt, ohbar: ohbar, ohm: ohm, oint: oint, olarr: olarr, olcir: olcir, olcross: olcross, oline: oline, olt: olt, omacr: omacr, omega: omega, omicron: omicron, omid: omid, ominus: ominus, oopf: oopf, opar: opar, operp: operp, oplus: oplus, or: or, orarr: orarr, ord: ord, order: order$1, orderof: orderof, ordf: ordf, ordm: ordm, origof: origof, oror: oror, orslope: orslope, orv: orv, oscr: oscr, oslas: oslas, oslash: oslash, osol: osol, otild: otild, otilde: otilde, otimes: otimes, otimesas: otimesas, oum: oum, ouml: ouml, ovbar: ovbar, par: par, para: para, parallel: parallel, parsim: parsim, parsl: parsl, part: part, pcy: pcy, percnt: percnt, period: period, permil: permil, perp: perp, pertenk: pertenk, pfr: pfr, phi: phi, phiv: phiv, phmmat: phmmat, phone: phone, pi: pi, pitchfork: pitchfork, piv: piv, planck: planck, planckh: planckh, plankv: plankv, plus: plus, plusacir: plusacir, plusb: plusb, pluscir: pluscir, plusdo: plusdo, plusdu: plusdu, pluse: pluse, plusm: plusm, plusmn: plusmn, plussim: plussim, plustwo: plustwo, pm: pm, pointint: pointint, popf: popf, poun: poun, pound: pound, pr: pr, prE: prE, prap: prap, prcue: prcue, pre: pre, prec: prec, precapprox: precapprox, preccurlyeq: preccurlyeq, preceq: preceq, precnapprox: precnapprox, precneqq: precneqq, precnsim: precnsim, precsim: precsim, prime: prime, primes: primes, prnE: prnE, prnap: prnap, prnsim: prnsim, prod: prod, profalar: profalar, profline: profline, profsurf: profsurf, prop: prop, propto: propto, prsim: prsim, prurel: prurel, pscr: pscr, psi: psi, puncsp: puncsp, qfr: qfr, qint: qint, qopf: qopf, qprime: qprime, qscr: qscr, quaternions: quaternions, quatint: quatint, quest: quest, questeq: questeq, quo: quo, quot: quot, rAarr: rAarr, rArr: rArr, rAtail: rAtail, rBarr: rBarr, rHar: rHar, race: race, racute: racute, radic: radic, raemptyv: raemptyv, rang: rang, rangd: rangd, range: range$1, rangle: rangle, raqu: raqu, raquo: raquo, rarr: rarr, rarrap: rarrap, rarrb: rarrb, rarrbfs: rarrbfs, rarrc: rarrc, rarrfs: rarrfs, rarrhk: rarrhk, rarrlp: rarrlp, rarrpl: rarrpl, rarrsim: rarrsim, rarrtl: rarrtl, rarrw: rarrw, ratail: ratail, ratio: ratio, rationals: rationals, rbarr: rbarr, rbbrk: rbbrk, rbrace: rbrace, rbrack: rbrack, rbrke: rbrke, rbrksld: rbrksld, rbrkslu: rbrkslu, rcaron: rcaron, rcedil: rcedil, rceil: rceil, rcub: rcub, rcy: rcy, rdca: rdca, rdldhar: rdldhar, rdquo: rdquo, rdquor: rdquor, rdsh: rdsh, real: real, realine: realine, realpart: realpart, reals: reals, rect: rect, re: re, reg: reg, rfisht: rfisht, rfloor: rfloor, rfr: rfr, rhard: rhard, rharu: rharu, rharul: rharul, rho: rho, rhov: rhov, rightarrow: rightarrow, rightarrowtail: rightarrowtail, rightharpoondown: rightharpoondown, rightharpoonup: rightharpoonup, rightleftarrows: rightleftarrows, rightleftharpoons: rightleftharpoons, rightrightarrows: rightrightarrows, rightsquigarrow: rightsquigarrow, rightthreetimes: rightthreetimes, ring: ring, risingdotseq: risingdotseq, rlarr: rlarr, rlhar: rlhar, rlm: rlm, rmoust: rmoust, rmoustache: rmoustache, rnmid: rnmid, roang: roang, roarr: roarr, robrk: robrk, ropar: ropar, ropf: ropf, roplus: roplus, rotimes: rotimes, rpar: rpar, rpargt: rpargt, rppolint: rppolint, rrarr: rrarr, rsaquo: rsaquo, rscr: rscr, rsh: rsh, rsqb: rsqb, rsquo: rsquo, rsquor: rsquor, rthree: rthree, rtimes: rtimes, rtri: rtri, rtrie: rtrie, rtrif: rtrif, rtriltri: rtriltri, ruluhar: ruluhar, rx: rx, sacute: sacute, sbquo: sbquo, sc: sc, scE: scE, scap: scap, scaron: scaron, sccue: sccue, sce: sce, scedil: scedil, scirc: scirc, scnE: scnE, scnap: scnap, scnsim: scnsim, scpolint: scpolint, scsim: scsim, scy: scy, sdot: sdot, sdotb: sdotb, sdote: sdote, seArr: seArr, searhk: searhk, searr: searr, searrow: searrow, sec: sec, sect: sect, semi: semi, seswar: seswar, setminus: setminus, setmn: setmn, sext: sext, sfr: sfr, sfrown: sfrown, sharp: sharp, shchcy: shchcy, shcy: shcy, shortmid: shortmid, shortparallel: shortparallel, sh: sh, shy: shy, sigma: sigma, sigmaf: sigmaf, sigmav: sigmav, sim: sim, simdot: simdot, sime: sime, simeq: simeq, simg: simg, simgE: simgE, siml: siml, simlE: simlE, simne: simne, simplus: simplus, simrarr: simrarr, slarr: slarr, smallsetminus: smallsetminus, smashp: smashp, smeparsl: smeparsl, smid: smid, smile: smile, smt: smt, smte: smte, smtes: smtes, softcy: softcy, sol: sol, solb: solb, solbar: solbar, sopf: sopf, spades: spades, spadesuit: spadesuit, spar: spar, sqcap: sqcap, sqcaps: sqcaps, sqcup: sqcup, sqcups: sqcups, sqsub: sqsub, sqsube: sqsube, sqsubset: sqsubset, sqsubseteq: sqsubseteq, sqsup: sqsup, sqsupe: sqsupe, sqsupset: sqsupset, sqsupseteq: sqsupseteq, squ: squ, square: square, squarf: squarf, squf: squf, srarr: srarr, sscr: sscr, ssetmn: ssetmn, ssmile: ssmile, sstarf: sstarf, star: star$1, starf: starf, straightepsilon: straightepsilon, straightphi: straightphi, strns: strns, sub: sub, subE: subE, subdot: subdot, sube: sube, subedot: subedot, submult: submult, subnE: subnE, subne: subne, subplus: subplus, subrarr: subrarr, subset: subset, subseteq: subseteq, subseteqq: subseteqq, subsetneq: subsetneq, subsetneqq: subsetneqq, subsim: subsim, subsub: subsub, subsup: subsup, succ: succ, succapprox: succapprox, succcurlyeq: succcurlyeq, succeq: succeq, succnapprox: succnapprox, succneqq: succneqq, succnsim: succnsim, succsim: succsim, sum: sum, sung: sung, sup: sup, sup1: sup1, sup2: sup2, sup3: sup3, supE: supE, supdot: supdot, supdsub: supdsub, supe: supe, supedot: supedot, suphsol: suphsol, suphsub: suphsub, suplarr: suplarr, supmult: supmult, supnE: supnE, supne: supne, supplus: supplus, supset: supset, supseteq: supseteq, supseteqq: supseteqq, supsetneq: supsetneq, supsetneqq: supsetneqq, supsim: supsim, supsub: supsub, supsup: supsup, swArr: swArr, swarhk: swarhk, swarr: swarr, swarrow: swarrow, swnwar: swnwar, szli: szli, szlig: szlig, target: target, tau: tau, tbrk: tbrk, tcaron: tcaron, tcedil: tcedil, tcy: tcy, tdot: tdot, telrec: telrec, tfr: tfr, there4: there4, therefore: therefore, theta: theta, thetasym: thetasym, thetav: thetav, thickapprox: thickapprox, thicksim: thicksim, thinsp: thinsp, thkap: thkap, thksim: thksim, thor: thor, thorn: thorn, tilde: tilde, time: time, times: times, timesb: timesb, timesbar: timesbar, timesd: timesd, tint: tint, toea: toea, top: top, topbot: topbot, topcir: topcir, topf: topf, topfork: topfork, tosa: tosa, tprime: tprime, trade: trade, triangle: triangle, triangledown: triangledown, triangleleft: triangleleft, trianglelefteq: trianglelefteq, triangleq: triangleq, triangleright: triangleright, trianglerighteq: trianglerighteq, tridot: tridot, trie: trie, triminus: triminus, triplus: triplus, trisb: trisb, tritime: tritime, trpezium: trpezium, tscr: tscr, tscy: tscy, tshcy: tshcy, tstrok: tstrok, twixt: twixt, twoheadleftarrow: twoheadleftarrow, twoheadrightarrow: twoheadrightarrow, uArr: uArr, uHar: uHar, uacut: uacut, uacute: uacute, uarr: uarr, ubrcy: ubrcy, ubreve: ubreve, ucir: ucir, ucirc: ucirc, ucy: ucy, udarr: udarr, udblac: udblac, udhar: udhar, ufisht: ufisht, ufr: ufr, ugrav: ugrav, ugrave: ugrave, uharl: uharl, uharr: uharr, uhblk: uhblk, ulcorn: ulcorn, ulcorner: ulcorner, ulcrop: ulcrop, ultri: ultri, umacr: umacr, um: um, uml: uml, uogon: uogon, uopf: uopf, uparrow: uparrow, updownarrow: updownarrow, upharpoonleft: upharpoonleft, upharpoonright: upharpoonright, uplus: uplus, upsi: upsi, upsih: upsih, upsilon: upsilon, upuparrows: upuparrows, urcorn: urcorn, urcorner: urcorner, urcrop: urcrop, uring: uring, urtri: urtri, uscr: uscr, utdot: utdot, utilde: utilde, utri: utri, utrif: utrif, uuarr: uuarr, uum: uum, uuml: uuml, uwangle: uwangle, vArr: vArr, vBar: vBar, vBarv: vBarv, vDash: vDash, vangrt: vangrt, varepsilon: varepsilon, varkappa: varkappa, varnothing: varnothing, varphi: varphi, varpi: varpi, varpropto: varpropto, varr: varr, varrho: varrho, varsigma: varsigma, varsubsetneq: varsubsetneq, varsubsetneqq: varsubsetneqq, varsupsetneq: varsupsetneq, varsupsetneqq: varsupsetneqq, vartheta: vartheta, vartriangleleft: vartriangleleft, vartriangleright: vartriangleright, vcy: vcy, vdash: vdash, vee: vee, veebar: veebar, veeeq: veeeq, vellip: vellip, verbar: verbar, vert: vert, vfr: vfr, vltri: vltri, vnsub: vnsub, vnsup: vnsup, vopf: vopf, vprop: vprop, vrtri: vrtri, vscr: vscr, vsubnE: vsubnE, vsubne: vsubne, vsupnE: vsupnE, vsupne: vsupne, vzigzag: vzigzag, wcirc: wcirc, wedbar: wedbar, wedge: wedge, wedgeq: wedgeq, weierp: weierp, wfr: wfr, wopf: wopf, wp: wp, wr: wr, wreath: wreath, wscr: wscr, xcap: xcap, xcirc: xcirc, xcup: xcup, xdtri: xdtri, xfr: xfr, xhArr: xhArr, xharr: xharr, xi: xi, xlArr: xlArr, xlarr: xlarr, xmap: xmap, xnis: xnis, xodot: xodot, xopf: xopf, xoplus: xoplus, xotime: xotime, xrArr: xrArr, xrarr: xrarr, xscr: xscr, xsqcup: xsqcup, xuplus: xuplus, xutri: xutri, xvee: xvee, xwedge: xwedge, yacut: yacut, yacute: yacute, yacy: yacy, ycirc: ycirc, ycy: ycy, ye: ye, yen: yen, yfr: yfr, yicy: yicy, yopf: yopf, yscr: yscr, yucy: yucy, yum: yum, yuml: yuml, zacute: zacute, zcaron: zcaron, zcy: zcy, zdot: zdot, zeetrf: zeetrf, zeta: zeta, zfr: zfr, zhcy: zhcy, zigrarr: zigrarr, zopf: zopf, zscr: zscr, zwj: zwj, zwnj: zwnj, 'default': index$1 }); var characterEntities$1 = getCjsExportFromNamespace(characterEntities); var decodeEntity_1 = decodeEntity; var own$3 = {}.hasOwnProperty; function decodeEntity(characters) { return own$3.call(characterEntities$1, characters) ? characterEntities$1[characters] : false } var mdastUtilToString = toString$3; // Get the text content of a node. // Prefer the node’s plain-text fields, otherwise serialize its children, // and if the given value is an array, serialize the nodes in it. function toString$3(node) { return ( (node && (node.value || node.alt || node.title || ('children' in node && all(node.children)) || ('length' in node && all(node)))) || '' ) } function all(values) { var result = []; var length = values.length; var index = -1; while (++index < length) { result[index] = toString$3(values[index]); } return result.join('') } var hasOwnProperty_1 = {}.hasOwnProperty; var normalizeIdentifier_1 = normalizeIdentifier; function normalizeIdentifier(value) { return ( value // Collapse Markdown whitespace. .replace(/[\t\n\r ]+/g, ' ') // Trim. .replace(/^ | $/g, '') // Some characters are considered “uppercase”, but if their lowercase // counterpart is uppercased will result in a different uppercase // character. // Hence, to get that form, we perform both lower- and uppercase. // Upper case makes sure keys will not interact with default prototypal // methods: no object method is uppercase. .toLowerCase() .toUpperCase() ) } var fromCharCode = String.fromCharCode; var safeFromInt_1 = safeFromInt; function safeFromInt(value, base) { var code = parseInt(value, base); if ( // C0 except for HT, LF, FF, CR, space code < 9 || code === 11 || (code > 13 && code < 32) || // Control character (DEL) of the basic block and C1 controls. (code > 126 && code < 160) || // Lone high surrogates and low surrogates. (code > 55295 && code < 57344) || // Noncharacters. (code > 64975 && code < 65008) || (code & 65535) === 65535 || (code & 65535) === 65534 || // Out of range code > 1114111 ) { return '\uFFFD' } return fromCharCode(code) } var markdownLineEnding_1 = markdownLineEnding; function markdownLineEnding(code) { return code < -2 } var markdownSpace_1 = markdownSpace; function markdownSpace(code) { return code === -2 || code === -1 || code === 32 } var factorySpace = createSpace; function createSpace(effects, ok, type, max) { var limit = max ? max - 1 : Infinity; var size; return start function start(code) { if (markdownSpace_1(code)) { effects.enter(type); size = 0; return prefix(code) } return ok(code) } function prefix(code) { if (markdownSpace_1(code) && size++ < limit) { effects.consume(code); return prefix } effects.exit(type); return ok(code) } } var tokenize = initializeContent; function initializeContent(effects) { var contentStart = effects.attempt( this.parser.constructs.contentInitial, afterContentStartConstruct, paragraphInitial ); var previous; return contentStart function afterContentStartConstruct(code) { if (code === null) { effects.consume(code); return } effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); return factorySpace(effects, contentStart, 'linePrefix') } function paragraphInitial(code) { effects.enter('paragraph'); return lineStart(code) } function lineStart(code) { var token = effects.enter('chunkText', { contentType: 'text', previous: previous }); if (previous) { previous.next = token; } previous = token; return data(code) } function data(code) { if (code === null) { effects.exit('chunkText'); effects.exit('paragraph'); effects.consume(code); return } if (markdownLineEnding_1(code)) { effects.consume(code); effects.exit('chunkText'); return lineStart } // Data. effects.consume(code); return data } } var content = { tokenize: tokenize }; var tokenize$1 = tokenizeBlankLine; var partial = true; function tokenizeBlankLine(effects, ok, nok) { return factorySpace(effects, afterWhitespace, 'linePrefix') function afterWhitespace(code) { return code === null || markdownLineEnding_1(code) ? ok(code) : nok(code) } } var partialBlankLine = { tokenize: tokenize$1, partial: partial }; var tokenize$2 = initializeDocument; var container = {tokenize: tokenizeContainer}; var lazyFlow = {tokenize: tokenizeLazyFlow}; function initializeDocument(effects) { var self = this; var stack = []; var continued = 0; var inspectResult; var childFlow; var childToken; return start function start(code) { if (continued < stack.length) { self.containerState = stack[continued][1]; return effects.attempt( stack[continued][0].continuation, documentContinue, documentContinued )(code) } return documentContinued(code) } function documentContinue(code) { continued++; return start(code) } function documentContinued(code) { // If we’re in a concrete construct (such as when expecting another line of // HTML, or we resulted in lazy content), we can immediately start flow. if (inspectResult && inspectResult.flowContinue) { return flowStart(code) } self.interrupt = childFlow && childFlow.currentConstruct && childFlow.currentConstruct.interruptible; self.containerState = {}; return effects.attempt(container, containerContinue, flowStart)(code) } function containerContinue(code) { stack.push([self.currentConstruct, self.containerState]); self.containerState = undefined; return documentContinued(code) } function flowStart(code) { if (code === null) { exitContainers(0, true); effects.consume(code); return } childFlow = childFlow || self.parser.flow(self.now()); effects.enter('chunkFlow', { contentType: 'flow', previous: childToken, _tokenizer: childFlow }); return flowContinue(code) } function flowContinue(code) { if (code === null) { continueFlow(effects.exit('chunkFlow')); return flowStart(code) } if (markdownLineEnding_1(code)) { effects.consume(code); continueFlow(effects.exit('chunkFlow')); return effects.check( {tokenize: tokenizeInspect, partial: true}, documentAfterPeek ) } effects.consume(code); return flowContinue } function documentAfterPeek(code) { exitContainers( inspectResult.continued, inspectResult && inspectResult.flowEnd ); continued = 0; return start(code) } function continueFlow(token) { if (childToken) childToken.next = token; childToken = token; childFlow.lazy = inspectResult && inspectResult.lazy; childFlow.defineSkip(token.start); childFlow.write(self.sliceStream(token)); } function exitContainers(size, end) { var index = stack.length; // Close the flow. if (childFlow && end) { childFlow.write([null]); childToken = childFlow = undefined; } // Exit open containers. while (index-- > size) { self.containerState = stack[index][1]; stack[index][0].exit.call(self, effects); } stack.length = size; } function tokenizeInspect(effects, ok) { var subcontinued = 0; inspectResult = {}; return inspectStart function inspectStart(code) { if (subcontinued < stack.length) { self.containerState = stack[subcontinued][1]; return effects.attempt( stack[subcontinued][0].continuation, inspectContinue, inspectLess )(code) } // If we’re continued but in a concrete flow, we can’t have more // containers. if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) { inspectResult.flowContinue = true; return inspectDone(code) } self.interrupt = childFlow.currentConstruct && childFlow.currentConstruct.interruptible; self.containerState = {}; return effects.attempt(container, inspectFlowEnd, inspectDone)(code) } function inspectContinue(code) { subcontinued++; return self.containerState._closeFlow ? inspectFlowEnd(code) : inspectStart(code) } function inspectLess(code) { if (childFlow.currentConstruct && childFlow.currentConstruct.lazy) { // Maybe another container? self.containerState = {}; return effects.attempt( container, inspectFlowEnd, // Maybe flow, or a blank line? effects.attempt( lazyFlow, inspectFlowEnd, effects.check(partialBlankLine, inspectFlowEnd, inspectLazy) ) )(code) } // Otherwise we’re interrupting. return inspectFlowEnd(code) } function inspectLazy(code) { // Act as if all containers are continued. subcontinued = stack.length; inspectResult.lazy = true; inspectResult.flowContinue = true; return inspectDone(code) } // We’re done with flow if we have more containers, or an interruption. function inspectFlowEnd(code) { inspectResult.flowEnd = true; return inspectDone(code) } function inspectDone(code) { inspectResult.continued = subcontinued; self.interrupt = self.containerState = undefined; return ok(code) } } } function tokenizeContainer(effects, ok, nok) { return factorySpace( effects, effects.attempt(this.parser.constructs.document, ok, nok), 'linePrefix', 4 ) } function tokenizeLazyFlow(effects, ok, nok) { return factorySpace( effects, effects.lazy(this.parser.constructs.flow, ok, nok), 'linePrefix', 4 ) } var document$1 = { tokenize: tokenize$2 }; var assign = Object.assign; var chunkedSplice_1 = chunkedSplice; var v8MaxSafeChunkSize = 10000; // `Array#splice` takes all items to be inserted as individual argument which // causes a stack overflow in V8 when trying to insert 100k items for instance. function chunkedSplice(list, start, remove, items) { var end = list.length; var chunkStart = 0; var result; var parameters; // Make start between zero and `end` (included). if (start < 0) { start = -start > end ? 0 : end + start; } else { start = start > end ? end : start; } remove = remove > 0 ? remove : 0; // No need to chunk the items if there’s only a couple (10k) items. if (items.length < v8MaxSafeChunkSize) { parameters = Array.from(items); parameters.unshift(start, remove); return [].splice.apply(list, parameters) } // Delete `remove` items starting from `start` result = [].splice.apply(list, [start, remove]); // Insert the items in chunks to not cause stack overflows. while (chunkStart < items.length) { parameters = items.slice(chunkStart, chunkStart + v8MaxSafeChunkSize); parameters.unshift(start, 0) ;[].splice.apply(list, parameters); chunkStart += v8MaxSafeChunkSize; start += v8MaxSafeChunkSize; } return result } var shallow_1 = shallow; function shallow(object) { return assign({}, object) } var subtokenize_1 = subtokenize; function subtokenize(events) { var jumps = {}; var index = -1; var event; var lineIndex; var otherIndex; var otherEvent; var parameters; var subevents; var more; while (++index < events.length) { while (index in jumps) { index = jumps[index]; } event = events[index]; // Add a hook for the GFM tasklist extension, which needs to know if text // is in the first content of a list item. if ( index && event[1].type === 'chunkFlow' && events[index - 1][1].type === 'listItemPrefix' ) { subevents = event[1]._tokenizer.events; otherIndex = 0; if ( otherIndex < subevents.length && subevents[otherIndex][1].type === 'lineEndingBlank' ) { otherIndex += 2; } if ( otherIndex < subevents.length && subevents[otherIndex][1].type === 'content' ) { while (++otherIndex < subevents.length) { if (subevents[otherIndex][1].type === 'content') { break } if (subevents[otherIndex][1].type === 'chunkText') { subevents[otherIndex][1].isInFirstContentOfListItem = true; otherIndex++; } } } } // Enter. if (event[0] === 'enter') { if (event[1].contentType) { assign(jumps, subcontent(events, index)); index = jumps[index]; more = true; } } // Exit. else if (event[1]._container || event[1]._movePreviousLineEndings) { otherIndex = index; lineIndex = undefined; while (otherIndex--) { otherEvent = events[otherIndex]; if ( otherEvent[1].type === 'lineEnding' || otherEvent[1].type === 'lineEndingBlank' ) { if (otherEvent[0] === 'enter') { if (lineIndex) { events[lineIndex][1].type = 'lineEndingBlank'; } otherEvent[1].type = 'lineEnding'; lineIndex = otherIndex; } } else { break } } if (lineIndex) { // Fix position. event[1].end = shallow_1(events[lineIndex][1].start); // Switch container exit w/ line endings. parameters = events.slice(lineIndex, index); parameters.unshift(event); chunkedSplice_1(events, lineIndex, index - lineIndex + 1, parameters); } } } return !more } function subcontent(events, eventIndex) { var token = events[eventIndex][1]; var context = events[eventIndex][2]; var startPosition = eventIndex - 1; var startPositions = []; var tokenizer = token._tokenizer || context.parser[token.contentType](token.start); var childEvents = tokenizer.events; var jumps = []; var gaps = {}; var stream; var previous; var index; var entered; var end; var adjust; // Loop forward through the linked tokens to pass them in order to the // subtokenizer. while (token) { // Find the position of the event for this token. while (events[++startPosition][1] !== token) { // Empty. } startPositions.push(startPosition); if (!token._tokenizer) { stream = context.sliceStream(token); if (!token.next) { stream.push(null); } if (previous) { tokenizer.defineSkip(token.start); } if (token.isInFirstContentOfListItem) { tokenizer._gfmTasklistFirstContentOfListItem = true; } tokenizer.write(stream); if (token.isInFirstContentOfListItem) { tokenizer._gfmTasklistFirstContentOfListItem = undefined; } } // Unravel the next token. previous = token; token = token.next; } // Now, loop back through all events (and linked tokens), to figure out which // parts belong where. token = previous; index = childEvents.length; while (index--) { // Make sure we’ve at least seen something (final eol is part of the last // token). if (childEvents[index][0] === 'enter') { entered = true; } else if ( // Find a void token that includes a break. entered && childEvents[index][1].type === childEvents[index - 1][1].type && childEvents[index][1].start.line !== childEvents[index][1].end.line ) { add(childEvents.slice(index + 1, end)); // Help GC. token._tokenizer = token.next = undefined; token = token.previous; end = index + 1; } } // Help GC. tokenizer.events = token._tokenizer = token.next = undefined; // Do head: add(childEvents.slice(0, end)); index = -1; adjust = 0; while (++index < jumps.length) { gaps[adjust + jumps[index][0]] = adjust + jumps[index][1]; adjust += jumps[index][1] - jumps[index][0] - 1; } return gaps function add(slice) { var start = startPositions.pop(); jumps.unshift([start, start + slice.length - 1]); chunkedSplice_1(events, start, 2, slice); } } var sizeChunks_1 = sizeChunks; // Measure the number of character codes in chunks. // Counts tabs based on their expanded size, and CR+LF as one character. function sizeChunks(chunks) { var index = -1; var size = 0; while (++index < chunks.length) { size += typeof chunks[index] === 'string' ? chunks[index].length : 1; } return size } var prefixSize_1 = prefixSize; function prefixSize(events, type) { var tail = events[events.length - 1]; if (!tail || tail[1].type !== type) return 0 return sizeChunks_1(tail[2].sliceStream(tail[1])) } var tokenize$3 = tokenizeContent; var resolve$7 = resolveContent; var interruptible = true; var lazy = true; var lookaheadConstruct = {tokenize: tokenizeLookaheadConstruct, partial: true}; // Content is transparent: it’s parsed right now. That way, definitions are also // parsed right now: before text in paragraphs (specifically, media) are parsed. function resolveContent(events) { subtokenize_1(events); return events } function tokenizeContent(effects, ok) { var previous; return start function start(code) { effects.enter('content'); previous = effects.enter('chunkContent', { contentType: 'content' }); return data(code) } function data(code) { if (code === null) { return contentEnd(code) } if (markdownLineEnding_1(code)) { return effects.check( lookaheadConstruct, contentContinue, contentEnd )(code) } // Data. effects.consume(code); return data } function contentEnd(code) { effects.exit('chunkContent'); effects.exit('content'); return ok(code) } function contentContinue(code) { effects.consume(code); effects.exit('chunkContent'); previous = previous.next = effects.enter('chunkContent', { contentType: 'content', previous: previous }); return data } } function tokenizeLookaheadConstruct(effects, ok, nok) { var self = this; return startLookahead function startLookahead(code) { effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); return factorySpace(effects, prefixed, 'linePrefix') } function prefixed(code) { if (code === null || markdownLineEnding_1(code)) { return nok(code) } if (prefixSize_1(self.events, 'linePrefix') < 4) { return effects.interrupt(self.parser.constructs.flow, nok, ok)(code) } return ok(code) } } var content$1 = { tokenize: tokenize$3, resolve: resolve$7, interruptible: interruptible, lazy: lazy }; var tokenize$4 = initializeFlow; function initializeFlow(effects) { var self = this; var initial = effects.attempt( // Try to parse a blank line. partialBlankLine, atBlankEnding, // Try to parse initial flow (essentially, only code). effects.attempt( this.parser.constructs.flowInitial, afterConstruct, factorySpace( effects, effects.attempt( this.parser.constructs.flow, afterConstruct, effects.attempt(content$1, afterConstruct) ), 'linePrefix' ) ) ); return initial function atBlankEnding(code) { if (code === null) { effects.consume(code); return } effects.enter('lineEndingBlank'); effects.consume(code); effects.exit('lineEndingBlank'); self.currentConstruct = undefined; return initial } function afterConstruct(code) { if (code === null) { effects.consume(code); return } effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); self.currentConstruct = undefined; return initial } } var flow = { tokenize: tokenize$4 }; var text_1 = initializeFactory('text'); var string = initializeFactory('string'); var resolver_1 = {resolveAll: resolver()}; function initializeFactory(field) { return { tokenize: initializeText, resolveAll: resolver(field === 'text' ? resolveAllLineSuffixes : undefined) } function initializeText(effects) { var self = this; var constructs = this.parser.constructs[field]; var text = effects.attempt(constructs, start, notText); return start function start(code) { return atBreak(code) ? text(code) : notText(code) } function notText(code) { if (code === null) { effects.consume(code); return } effects.enter('data'); effects.consume(code); return data } function data(code) { if (atBreak(code)) { effects.exit('data'); return text(code) } // Data. effects.consume(code); return data } function atBreak(code) { var list = constructs[code]; var index = -1; if (code === null) { return true } if (list) { while (++index < list.length) { if ( !list[index].previous || list[index].previous.call(self, self.previous) ) { return true } } } } } } function resolver(extraResolver) { return resolveAllText function resolveAllText(events, context) { var index = -1; var enter; // A rather boring computation (to merge adjacent `data` events) which // improves mm performance by 29%. while (++index <= events.length) { if (enter === undefined) { if (events[index] && events[index][1].type === 'data') { enter = index; index++; } } else if (!events[index] || events[index][1].type !== 'data') { // Don’t do anything if there is one data token. if (index !== enter + 2) { events[enter][1].end = events[index - 1][1].end; events.splice(enter + 2, index - enter - 2); index = enter + 2; } enter = undefined; } } return extraResolver ? extraResolver(events, context) : events } } // A rather ugly set of instructions which again looks at chunks in the input // stream. // The reason to do this here is that it is *much* faster to parse in reverse. // And that we can’t hook into `null` to split the line suffix before an EOF. // To do: figure out if we can make this into a clean utility, or even in core. // As it will be useful for GFMs literal autolink extension (and maybe even // tables?) function resolveAllLineSuffixes(events, context) { var eventIndex = -1; var chunks; var data; var chunk; var index; var bufferIndex; var size; var tabs; var token; while (++eventIndex <= events.length) { if ( (eventIndex === events.length || events[eventIndex][1].type === 'lineEnding') && events[eventIndex - 1][1].type === 'data' ) { data = events[eventIndex - 1][1]; chunks = context.sliceStream(data); index = chunks.length; bufferIndex = -1; size = 0; tabs = undefined; while (index--) { chunk = chunks[index]; if (typeof chunk === 'string') { bufferIndex = chunk.length; while (chunk.charCodeAt(bufferIndex - 1) === 32) { size++; bufferIndex--; } if (bufferIndex) break bufferIndex = -1; } // Number else if (chunk === -2) { tabs = true; size++; } else if (chunk === -1) ; else { // Replacement character, exit. index++; break } } if (size) { token = { type: eventIndex === events.length || tabs || size < 2 ? 'lineSuffix' : 'hardBreakTrailing', start: { line: data.end.line, column: data.end.column - size, offset: data.end.offset - size, _index: data.start._index + index, _bufferIndex: index ? bufferIndex : data.start._bufferIndex + bufferIndex }, end: shallow_1(data.end) }; data.end = shallow_1(token.start); if (data.start.offset === data.end.offset) { assign(data, token); } else { events.splice( eventIndex, 0, ['enter', token, context], ['exit', token, context] ); eventIndex += 2; } } eventIndex++; } } return events } var text = { text: text_1, string: string, resolver: resolver_1 }; var markdownLineEndingOrSpace_1 = markdownLineEndingOrSpace; function markdownLineEndingOrSpace(code) { return code < 0 || code === 32 } // This module is generated by `script/`. // // CommonMark handles attention (emphasis, strong) markers based on what comes // before or after them. // One such difference is if those characters are Unicode punctuation. // This script is generated from the Unicode data. var unicodePunctuationRegex = /[!-\/:-@\[-`\{-~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]/; var regexCheck_1 = regexCheck; function regexCheck(regex) { return check function check(code) { return regex.test(fromCharCode(code)) } } // Size note: removing ASCII from the regex and using `ascii-punctuation` here // In fact adds to the bundle size. var unicodePunctuation_1 = regexCheck_1(unicodePunctuationRegex); var unicodeWhitespace = regexCheck_1(/\s/); var classifyCharacter_1 = classifyCharacter; // Classify whether a character is unicode whitespace, unicode punctuation, or // anything else. // Used for attention (emphasis, strong), whose sequences can open or close // based on the class of surrounding characters. function classifyCharacter(code) { if ( code === null || markdownLineEndingOrSpace_1(code) || unicodeWhitespace(code) ) { return 1 } if (unicodePunctuation_1(code)) { return 2 } } var movePoint_1 = movePoint; // Note! `move` only works inside lines! It’s not possible to move past other // chunks (replacement characters, tabs, or line endings). function movePoint(point, offset) { point.column += offset; point.offset += offset; point._bufferIndex += offset; return point } var resolveAll_1 = resolveAll; function resolveAll(constructs, events, context) { var called = []; var index = -1; var resolve; while (++index < constructs.length) { resolve = constructs[index].resolveAll; if (resolve && called.indexOf(resolve) < 0) { events = resolve(events, context); called.push(resolve); } } return events } var tokenize$5 = tokenizeAttention; var resolveAll_1$1 = resolveAllAttention; // Take all events and resolve attention to emphasis or strong. function resolveAllAttention(events, context) { var index = -1; var open; var group; var text; var openingSequence; var closingSequence; var use; var nextEvents; var offset; // Walk through all events. // // Note: performance of this is fine on an mb of normal markdown, but it’s // a bottleneck for malicious stuff. while (++index < events.length) { // Find a token that can close. if ( events[index][0] === 'enter' && events[index][1].type === 'attentionSequence' && events[index][1]._close ) { open = index; // Now walk back to find an opener. while (open--) { // Find a token that can open the closer. if ( events[open][0] === 'exit' && events[open][1].type === 'attentionSequence' && events[open][1]._open && // If the markers are the same: context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index][1]).charCodeAt(0) ) { // If the opening can close or the closing can open, // and the close size *is not* a multiple of three, // but the sum of the opening and closing size *is* multiple of three, // then don’t match. if ( (events[open][1]._close || events[index][1]._open) && (events[index][1].end.offset - events[index][1].start.offset) % 3 && !( (events[open][1].end.offset - events[open][1].start.offset + events[index][1].end.offset - events[index][1].start.offset) % 3 ) ) { continue } // Number of markers to use from the sequence. use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index][1].end.offset - events[index][1].start.offset > 1 ? 2 : 1; openingSequence = { type: use > 1 ? 'strongSequence' : 'emphasisSequence', start: movePoint_1(shallow_1(events[open][1].end), -use), end: shallow_1(events[open][1].end) }; closingSequence = { type: use > 1 ? 'strongSequence' : 'emphasisSequence', start: shallow_1(events[index][1].start), end: movePoint_1(shallow_1(events[index][1].start), use) }; text = { type: use > 1 ? 'strongText' : 'emphasisText', start: shallow_1(events[open][1].end), end: shallow_1(events[index][1].start) }; group = { type: use > 1 ? 'strong' : 'emphasis', start: shallow_1(openingSequence.start), end: shallow_1(closingSequence.end) }; events[open][1].end = shallow_1(openingSequence.start); events[index][1].start = shallow_1(closingSequence.end); nextEvents = []; // If there are more markers in the opening, add them before. if (events[open][1].end.offset - events[open][1].start.offset) { chunkedSplice_1(nextEvents, nextEvents.length, 0, [ ['enter', events[open][1], context], ['exit', events[open][1], context] ]); } // Opening. chunkedSplice_1(nextEvents, nextEvents.length, 0, [ ['enter', group, context], ['enter', openingSequence, context], ['exit', openingSequence, context], ['enter', text, context] ]); // Between. chunkedSplice_1( nextEvents, nextEvents.length, 0, resolveAll_1( context.parser.constructs.insideSpan.null, events.slice(open + 1, index), context ) ); // Closing. chunkedSplice_1(nextEvents, nextEvents.length, 0, [ ['exit', text, context], ['enter', closingSequence, context], ['exit', closingSequence, context], ['exit', group, context] ]); // If there are more markers in the closing, add them after. if (events[index][1].end.offset - events[index][1].start.offset) { offset = 2; chunkedSplice_1(nextEvents, nextEvents.length, 0, [ ['enter', events[index][1], context], ['exit', events[index][1], context] ]); } else { offset = 0; } chunkedSplice_1(events, open - 1, index - open + 3, nextEvents); index = open + nextEvents.length - offset - 2; break } } } } // Remove remaining sequences. index = -1; while (++index < events.length) { if (events[index][1].type === 'attentionSequence') { events[index][1].type = 'data'; } } return events } function tokenizeAttention(effects, ok) { var before = classifyCharacter_1(this.previous); var marker; return start function start(code) { effects.enter('attentionSequence'); marker = code; return sequence(code) } function sequence(code) { var token; var after; var open; var close; if (code === marker) { effects.consume(code); return sequence } token = effects.exit('attentionSequence'); after = classifyCharacter_1(code); open = !after || (after === 2 && before); close = !before || (before === 2 && after); token._open = marker === 42 ? open : open && (before || !close); token._close = marker === 42 ? close : close && (after || !open); return ok(code) } } var attention = { tokenize: tokenize$5, resolveAll: resolveAll_1$1 }; var tokenize$6 = tokenizeAtxHeading; var resolve$8 = resolveAtxHeading; function resolveAtxHeading(events, context) { var contentEnd = events.length - 2; var contentStart = 3; var content; var text; // Prefix whitespace, part of the opening. if (events[contentStart][1].type === 'whitespace') { contentStart += 2; } // Suffix whitespace, part of the closing. if ( contentEnd - 2 > contentStart && events[contentEnd][1].type === 'whitespace' ) { contentEnd -= 2; } if ( events[contentEnd][1].type === 'atxHeadingSequence' && (contentStart === contentEnd - 1 || (contentEnd - 4 > contentStart && events[contentEnd - 2][1].type === 'whitespace')) ) { contentEnd -= contentStart + 1 === contentEnd ? 2 : 4; } if (contentEnd > contentStart) { content = { type: 'atxHeadingText', start: events[contentStart][1].start, end: events[contentEnd][1].end }; text = { type: 'chunkText', start: events[contentStart][1].start, end: events[contentEnd][1].end, contentType: 'text' }; chunkedSplice_1(events, contentStart, contentEnd - contentStart + 1, [ ['enter', content, context], ['enter', text, context], ['exit', text, context], ['exit', content, context] ]); } return events } function tokenizeAtxHeading(effects, ok, nok) { var self = this; var size = 0; return start function start(code) { effects.enter('atxHeading'); effects.enter('atxHeadingSequence'); return fenceOpenInside(code) } function fenceOpenInside(code) { if (code === 35 && size++ < 6) { effects.consume(code); return fenceOpenInside } if (code === null || markdownLineEndingOrSpace_1(code)) { effects.exit('atxHeadingSequence'); return self.interrupt ? ok(code) : headingBreak(code) } return nok(code) } function headingBreak(code) { if (code === 35) { effects.enter('atxHeadingSequence'); return sequence(code) } if (code === null || markdownLineEnding_1(code)) { effects.exit('atxHeading'); return ok(code) } if (markdownSpace_1(code)) { return factorySpace(effects, headingBreak, 'whitespace')(code) } effects.enter('atxHeadingText'); return data(code) } function sequence(code) { if (code === 35) { effects.consume(code); return sequence } effects.exit('atxHeadingSequence'); return headingBreak(code) } function data(code) { if (code === null || code === 35 || markdownLineEndingOrSpace_1(code)) { effects.exit('atxHeadingText'); return headingBreak(code) } effects.consume(code); return data } } var headingAtx = { tokenize: tokenize$6, resolve: resolve$8 }; var asciiAlpha = regexCheck_1(/[A-Za-z]/); var asciiAlphanumeric = regexCheck_1(/[\dA-Za-z]/); var asciiAtext = regexCheck_1(/[#-'*+\--9=?A-Z^-~]/); var asciiControl_1 = asciiControl; // Note: EOF is seen as ASCII control here, because `null < 32 == true`. function asciiControl(code) { return ( // Special whitespace codes (which have negative values), C0 and Control // character DEL code < 32 || code === 127 ) } var tokenize$7 = tokenizeAutolink; function tokenizeAutolink(effects, ok, nok) { var size; return start function start(code) { effects.enter('autolink'); effects.enter('autolinkMarker'); effects.consume(code); effects.exit('autolinkMarker'); effects.enter('autolinkProtocol'); return open } function open(code) { if (asciiAlpha(code)) { effects.consume(code); size = 1; return schemeOrEmailAtext } return asciiAtext(code) ? emailAtext(code) : nok(code) } function schemeOrEmailAtext(code) { return code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code) ? schemeInsideOrEmailAtext(code) : emailAtext(code) } function schemeInsideOrEmailAtext(code) { if (code === 58) { effects.consume(code); return urlInside } if ( (code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) && size++ < 32 ) { effects.consume(code); return schemeInsideOrEmailAtext } return emailAtext(code) } function urlInside(code) { if (code === 62) { effects.exit('autolinkProtocol'); return end(code) } if (code === 32 || code === 60 || asciiControl_1(code)) { return nok(code) } effects.consume(code); return urlInside } function emailAtext(code) { if (code === 64) { effects.consume(code); size = 0; return emailAtSignOrDot } if (asciiAtext(code)) { effects.consume(code); return emailAtext } return nok(code) } function emailAtSignOrDot(code) { return asciiAlphanumeric(code) ? emailLabel(code) : nok(code) } function emailLabel(code) { if (code === 46) { effects.consume(code); size = 0; return emailAtSignOrDot } if (code === 62) { // Exit, then change the type. effects.exit('autolinkProtocol').type = 'autolinkEmail'; return end(code) } return emailValue(code) } function emailValue(code) { if ((code === 45 || asciiAlphanumeric(code)) && size++ < 63) { effects.consume(code); return code === 45 ? emailValue : emailLabel } return nok(code) } function end(code) { effects.enter('autolinkMarker'); effects.consume(code); effects.exit('autolinkMarker'); effects.exit('autolink'); return ok } } var autolink = { tokenize: tokenize$7 }; var asciiDigit = regexCheck_1(/\d/); var tokenize$8 = tokenizeThematicBreak; function tokenizeThematicBreak(effects, ok, nok) { var size = 0; var marker; return start function start(code) { effects.enter('thematicBreak'); marker = code; return atBreak(code) } function atBreak(code) { if (code === marker) { effects.enter('thematicBreakSequence'); return sequence(code) } if (markdownSpace_1(code)) { return factorySpace(effects, atBreak, 'whitespace')(code) } if (size < 3 || (code !== null && !markdownLineEnding_1(code))) { return nok(code) } effects.exit('thematicBreak'); return ok(code) } function sequence(code) { if (code === marker) { effects.consume(code); size++; return sequence } effects.exit('thematicBreakSequence'); return atBreak(code) } } var thematicBreak = { tokenize: tokenize$8 }; var list = createCommonjsModule(function (module, exports) { exports.tokenize = tokenizeListStart; exports.continuation = {tokenize: tokenizeListContinuation}; exports.exit = tokenizeListEnd; function tokenizeListStart(effects, ok, nok) { var self = this; var initialSize = prefixSize_1(self.events, 'linePrefix'); var valueSize; return start function start(code) { if ( (code === 42 || code === 43 || code === 45) && (!self.containerState.marker || code === self.containerState.marker) ) { return code === 42 || code === 45 ? effects.check(thematicBreak, nok, unordered)(code) : unordered(code) } if ( asciiDigit(code) && (!self.containerState.type || self.containerState.type === 'listOrdered') ) { return ordered(code) } return nok(code) } function unordered(code) { if (!self.containerState.type) { self.containerState.type = 'listUnordered'; effects.enter(self.containerState.type, {_container: true}); } effects.enter('listItemPrefix'); return atMarker(code) } function ordered(code) { if (self.containerState.type || !self.interrupt || code === 49) { if (!self.containerState.type) { self.containerState.type = 'listOrdered'; effects.enter(self.containerState.type, {_container: true}); } effects.enter('listItemPrefix'); effects.enter('listItemValue'); effects.consume(code); valueSize = 1; return self.interrupt ? afterValue : inside } return nok(code) } function inside(code) { if (asciiDigit(code) && ++valueSize < 10) { effects.consume(code); return inside } return afterValue(code) } function afterValue(code) { effects.exit('listItemValue'); return code === 41 || code === 46 ? atMarker(code) : nok(code) } function atMarker(code) { self.containerState.marker = self.containerState.marker || code; if (code === self.containerState.marker) { effects.enter('listItemMarker'); effects.consume(code); effects.exit('listItemMarker'); return effects.check( partialBlankLine, // Can’t be empty when interrupting. self.interrupt ? nok : onBlank, effects.attempt( {tokenize: tokenizeListItemPrefixWhitespace, partial: true}, endOfPrefix, otherPrefix ) ) } return nok(code) } function onBlank(code) { self.containerState.initialBlankLine = true; initialSize++; return endOfPrefix(code) } function otherPrefix(code) { if (markdownSpace_1(code)) { effects.enter('listItemPrefixWhitespace'); effects.consume(code); effects.exit('listItemPrefixWhitespace'); return endOfPrefix } return nok(code) } function endOfPrefix(code) { self.containerState.size = initialSize + sizeChunks_1(self.sliceStream(effects.exit('listItemPrefix'))); return ok(code) } } function tokenizeListContinuation(effects, ok, nok) { var self = this; self.containerState._closeFlow = undefined; return effects.check(partialBlankLine, onBlank, notBlank) function onBlank(code) { self.containerState.furtherBlankLines = self.containerState.furtherBlankLines || self.containerState.initialBlankLine; return ok(code) } function notBlank(code) { if (self.containerState.furtherBlankLines || !markdownSpace_1(code)) { self.containerState.furtherBlankLines = self.containerState.initialBlankLine = undefined; return notInCurrentItem(code) } self.containerState.furtherBlankLines = self.containerState.initialBlankLine = undefined; return effects.attempt( {tokenize: tokenizeIndent, partial: true}, ok, notInCurrentItem )(code) } function notInCurrentItem(code) { // While we do continue, we signal that the flow should be closed. self.containerState._closeFlow = true; // As we’re closing flow, we’re no longer interrupting self.interrupt = undefined; return factorySpace( effects, effects.attempt(exports, ok, nok), 'linePrefix', 4 )(code) } } function tokenizeIndent(effects, ok, nok) { var self = this; return factorySpace( effects, afterPrefix, 'listItemIndent', self.containerState.size + 1 ) function afterPrefix(code) { return prefixSize_1(self.events, 'listItemIndent') === self.containerState.size ? ok(code) : nok(code) } } function tokenizeListEnd(effects) { effects.exit(this.containerState.type); } function tokenizeListItemPrefixWhitespace(effects, ok, nok) { var self = this; return factorySpace( effects, afterPrefix, 'listItemPrefixWhitespace', 4 + 1 ) function afterPrefix(code) { return markdownSpace_1(code) || !prefixSize_1(self.events, 'listItemPrefixWhitespace') ? nok(code) : ok(code) } } }); var list_1 = list.tokenize; var list_2 = list.continuation; var list_3 = list.exit; var blockQuote = createCommonjsModule(function (module, exports) { exports.tokenize = tokenizeBlockQuoteStart; exports.continuation = {tokenize: tokenizeBlockQuoteContinuation}; exports.exit = exit; function tokenizeBlockQuoteStart(effects, ok, nok) { var self = this; return start function start(code) { if (code === 62) { if (!self.containerState.open) { effects.enter('blockQuote', {_container: true}); self.containerState.open = true; } effects.enter('blockQuotePrefix'); effects.enter('blockQuoteMarker'); effects.consume(code); effects.exit('blockQuoteMarker'); return after } return nok(code) } function after(code) { if (markdownSpace_1(code)) { effects.enter('blockQuotePrefixWhitespace'); effects.consume(code); effects.exit('blockQuotePrefixWhitespace'); effects.exit('blockQuotePrefix'); return ok } effects.exit('blockQuotePrefix'); return ok(code) } } function tokenizeBlockQuoteContinuation(effects, ok, nok) { return factorySpace( effects, effects.attempt(exports, ok, nok), 'linePrefix', 4 ) } function exit(effects) { effects.exit('blockQuote'); } }); var blockQuote_1 = blockQuote.tokenize; var blockQuote_2 = blockQuote.continuation; var blockQuote_3 = blockQuote.exit; var asciiPunctuation = regexCheck_1(/[!-/:-@[-`{-~]/); var tokenize$9 = tokenizeCharacterEscape; function tokenizeCharacterEscape(effects, ok, nok) { return start function start(code) { effects.enter('characterEscape'); effects.enter('escapeMarker'); effects.consume(code); effects.exit('escapeMarker'); return open } function open(code) { if (asciiPunctuation(code)) { effects.enter('characterEscapeValue'); effects.consume(code); effects.exit('characterEscapeValue'); effects.exit('characterEscape'); return ok } return nok(code) } } var characterEscape = { tokenize: tokenize$9 }; var asciiHexDigit = regexCheck_1(/[\dA-Fa-f]/); var tokenize$a = tokenizeCharacterReference; function tokenizeCharacterReference(effects, ok, nok) { var self = this; var size = 0; var max; var test; return start function start(code) { effects.enter('characterReference'); effects.enter('characterReferenceMarker'); effects.consume(code); effects.exit('characterReferenceMarker'); return open } function open(code) { if (code === 35) { effects.enter('characterReferenceMarkerNumeric'); effects.consume(code); effects.exit('characterReferenceMarkerNumeric'); return numeric } effects.enter('characterReferenceValue'); max = 31; test = asciiAlphanumeric; return value(code) } function numeric(code) { if (code === 88 || code === 120) { effects.enter('characterReferenceMarkerHexadecimal'); effects.consume(code); effects.exit('characterReferenceMarkerHexadecimal'); effects.enter('characterReferenceValue'); max = 6; test = asciiHexDigit; return value } effects.enter('characterReferenceValue'); max = 7; test = asciiDigit; return value(code) } function value(code) { var token; if (code === 59 && size) { token = effects.exit('characterReferenceValue'); if (test === asciiAlphanumeric && !decodeEntity_1(self.sliceSerialize(token))) { return nok(code) } effects.enter('characterReferenceMarker'); effects.consume(code); effects.exit('characterReferenceMarker'); effects.exit('characterReference'); return ok } if (test(code) && size++ < max) { effects.consume(code); return value } return nok(code) } } var characterReference = { tokenize: tokenize$a }; var tokenize$b = tokenizeCodeFenced; var concrete = true; function tokenizeCodeFenced(effects, ok, nok) { var self = this; var initialPrefix = prefixSize_1(this.events, 'linePrefix'); var sizeOpen = 0; var marker; return start function start(code) { effects.enter('codeFenced'); effects.enter('codeFencedFence'); effects.enter('codeFencedFenceSequence'); marker = code; return sequenceOpen(code) } function sequenceOpen(code) { if (code === marker) { effects.consume(code); sizeOpen++; return sequenceOpen } effects.exit('codeFencedFenceSequence'); return sizeOpen < 3 ? nok(code) : factorySpace(effects, infoOpen, 'whitespace')(code) } function infoOpen(code) { if (code === null || markdownLineEnding_1(code)) { return openAfter(code) } effects.enter('codeFencedFenceInfo'); effects.enter('chunkString', {contentType: 'string'}); return info(code) } function info(code) { if (code === null || markdownLineEndingOrSpace_1(code)) { effects.exit('chunkString'); effects.exit('codeFencedFenceInfo'); return factorySpace(effects, infoAfter, 'whitespace')(code) } if (code === 96 && code === marker) return nok(code) effects.consume(code); return info } function infoAfter(code) { if (code === null || markdownLineEnding_1(code)) { return openAfter(code) } effects.enter('codeFencedFenceMeta'); effects.enter('chunkString', {contentType: 'string'}); return meta(code) } function meta(code) { if (code === null || markdownLineEnding_1(code)) { effects.exit('chunkString'); effects.exit('codeFencedFenceMeta'); return openAfter(code) } if (code === 96 && code === marker) return nok(code) effects.consume(code); return meta } function openAfter(code) { effects.exit('codeFencedFence'); return self.interrupt ? ok(code) : content(code) } function content(code) { if (code === null) { return after(code) } if (markdownLineEnding_1(code)) { effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); return effects.attempt( {tokenize: tokenizeClosingFence, partial: true}, after, initialPrefix ? factorySpace(effects, content, 'linePrefix', initialPrefix + 1) : content ) } effects.enter('codeFlowValue'); return contentContinue(code) } function contentContinue(code) { if (code === null || markdownLineEnding_1(code)) { effects.exit('codeFlowValue'); return content(code) } effects.consume(code); return contentContinue } function after(code) { effects.exit('codeFenced'); return ok(code) } function tokenizeClosingFence(effects, ok, nok) { var size = 0; return factorySpace(effects, closingPrefixAfter, 'linePrefix', 4) function closingPrefixAfter(code) { effects.enter('codeFencedFence'); effects.enter('codeFencedFenceSequence'); return closingSequence(code) } function closingSequence(code) { if (code === marker) { effects.consume(code); size++; return closingSequence } if (size < sizeOpen) return nok(code) effects.exit('codeFencedFenceSequence'); return factorySpace(effects, closingSequenceEnd, 'whitespace')(code) } function closingSequenceEnd(code) { if (code === null || markdownLineEnding_1(code)) { effects.exit('codeFencedFence'); return ok(code) } return nok(code) } } } var codeFenced = { tokenize: tokenize$b, concrete: concrete }; var tokenize$c = tokenizeCodeIndented; var resolve$9 = resolveCodeIndented; var continuedIndent = {tokenize: tokenizeContinuedIndent, partial: true}; function resolveCodeIndented(events, context) { var code = { type: 'codeIndented', start: events[0][1].start, end: events[events.length - 1][1].end }; chunkedSplice_1(events, 0, 0, [['enter', code, context]]); chunkedSplice_1(events, events.length, 0, [['exit', code, context]]); return events } function tokenizeCodeIndented(effects, ok, nok) { var self = this; return factorySpace( effects, afterInitial, 'linePrefix', 4 + 1 ) function afterInitial(code) { // Flow checks blank lines first, so we don’t have EOL/EOF. if (prefixSize_1(self.events, 'linePrefix') < 4) { return nok(code) } effects.enter('codeFlowValue'); return content(code) } function afterPrefix(code) { if (code === null) { return ok(code) } if (markdownLineEnding_1(code)) { return effects.attempt(continuedIndent, afterPrefix, ok)(code) } effects.enter('codeFlowValue'); return content(code) } function content(code) { if (code === null || markdownLineEnding_1(code)) { effects.exit('codeFlowValue'); return afterPrefix(code) } effects.consume(code); return content } } function tokenizeContinuedIndent(effects, ok, nok) { var self = this; return factorySpace( effects, afterPrefix, 'linePrefix', 4 + 1 ) function afterPrefix(code) { if (markdownLineEnding_1(code)) { effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); return factorySpace( effects, afterPrefix, 'linePrefix', 4 + 1 ) } return prefixSize_1(self.events, 'linePrefix') < 4 ? nok(code) : ok(code) } } var codeIndented = { tokenize: tokenize$c, resolve: resolve$9 }; var tokenize$d = tokenizeCodeText; var resolve$a = resolveCodeText; var previous_1 = previous; function resolveCodeText(events) { var tailExitIndex = events.length - 4; var headEnterIndex = 3; var index; var enter; // If we start and end with an EOL or a space. if ( (events[headEnterIndex][1].type === 'lineEnding' || events[headEnterIndex][1].type === 'space') && (events[tailExitIndex][1].type === 'lineEnding' || events[tailExitIndex][1].type === 'space') ) { index = headEnterIndex; // And we have data. while (++index < tailExitIndex) { if (events[index][1].type === 'codeTextData') { // Then we have padding. events[tailExitIndex][1].type = events[headEnterIndex][1].type = 'codeTextPadding'; headEnterIndex += 2; tailExitIndex -= 2; break } } } // Merge adjacent spaces and data. index = headEnterIndex - 1; tailExitIndex++; while (++index <= tailExitIndex) { if (enter === undefined) { if (index !== tailExitIndex && events[index][1].type !== 'lineEnding') { enter = index; } } else if ( index === tailExitIndex || events[index][1].type === 'lineEnding' ) { events[enter][1].type = 'codeTextData'; if (index !== enter + 2) { events[enter][1].end = events[index - 1][1].end; events.splice(enter + 2, index - enter - 2); tailExitIndex -= index - enter - 2; index = enter + 2; } enter = undefined; } } return events } function previous(code) { // If there is a previous code, there will always be a tail. return ( code !== 96 || this.events[this.events.length - 1][1].type === 'characterEscape' ) } function tokenizeCodeText(effects, ok, nok) { var sizeOpen = 0; var size; var token; return start function start(code) { effects.enter('codeText'); effects.enter('codeTextSequence'); return openingSequence(code) } function openingSequence(code) { if (code === 96) { effects.consume(code); sizeOpen++; return openingSequence } effects.exit('codeTextSequence'); return gap(code) } function gap(code) { // EOF. if (code === null) { return nok(code) } // Closing fence? // Could also be data. if (code === 96) { token = effects.enter('codeTextSequence'); size = 0; return closingSequence(code) } // Tabs don’t work, and virtual spaces don’t make sense. if (code === 32) { effects.enter('space'); effects.consume(code); effects.exit('space'); return gap } if (markdownLineEnding_1(code)) { effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); return gap } // Data. effects.enter('codeTextData'); return data(code) } // In code. function data(code) { if ( code === null || code === 32 || code === 96 || markdownLineEnding_1(code) ) { effects.exit('codeTextData'); return gap(code) } effects.consume(code); return data } // Closing fence. function closingSequence(code) { // More. if (code === 96) { effects.consume(code); size++; return closingSequence } // Done! if (size === sizeOpen) { effects.exit('codeTextSequence'); effects.exit('codeText'); return ok(code) } // More or less accents: mark as data. token.type = 'codeTextData'; return data(code) } } var codeText = { tokenize: tokenize$d, resolve: resolve$a, previous: previous_1 }; var factoryDestination = createDestination; // eslint-disable-next-line max-params function createDestination( effects, ok, nok, type, literalType, literalMarkerType, rawType, stringType, max ) { var limit = max || Infinity; var balance = 0; return start function start(code) { if (code === 60) { effects.enter(type); effects.enter(literalType); effects.enter(literalMarkerType); effects.consume(code); effects.exit(literalMarkerType); return destinationEnclosedBefore } if (asciiControl_1(code)) { return nok(code) } effects.enter(type); effects.enter(rawType); effects.enter(stringType); effects.enter('chunkString', {contentType: 'string'}); return destinationRaw(code) } function destinationEnclosedBefore(code) { if (code === 62) { effects.enter(literalMarkerType); effects.consume(code); effects.exit(literalMarkerType); effects.exit(literalType); effects.exit(type); return ok } effects.enter(stringType); effects.enter('chunkString', {contentType: 'string'}); return destinationEnclosed(code) } function destinationEnclosed(code) { if (code === 62) { effects.exit('chunkString'); effects.exit(stringType); return destinationEnclosedBefore(code) } if (code === null || code === 60 || markdownLineEnding_1(code)) { return nok(code) } effects.consume(code); return code === 92 ? destinationEnclosedEscape : destinationEnclosed } function destinationEnclosedEscape(code) { if (code === 60 || code === 62 || code === 92) { effects.consume(code); return destinationEnclosed } return destinationEnclosed(code) } function destinationRaw(code) { if (code === 40) { if (++balance > limit) return nok(code) effects.consume(code); return destinationRaw } if (code === 41) { if (!balance--) { effects.exit('chunkString'); effects.exit(stringType); effects.exit(rawType); effects.exit(type); return ok(code) } effects.consume(code); return destinationRaw } if (code === null || markdownLineEndingOrSpace_1(code)) { if (balance) return nok(code) effects.exit('chunkString'); effects.exit(stringType); effects.exit(rawType); effects.exit(type); return ok(code) } if (asciiControl_1(code)) return nok(code) effects.consume(code); return code === 92 ? destinationRawEscape : destinationRaw } function destinationRawEscape(code) { if (code === 40 || code === 41 || code === 92) { effects.consume(code); return destinationRaw } return destinationRaw(code) } } var factoryLabel = createLabel; // eslint-disable-next-line max-params function createLabel(effects, ok, nok, type, markerType, stringType) { var self = this; var size = 0; var data; return start function start(code) { effects.enter(type); effects.enter(markerType); effects.consume(code); effects.exit(markerType); effects.enter(stringType); return atBreak } function atBreak(code) { if ( code === null || code === 91 || (code === 93 && !data) || /* istanbul ignore next - footnotes. */ (code === 94 && !size && '_hiddenFootnoteSupport' in self.parser.constructs) || size > 999 ) { return nok(code) } if (code === 93) { effects.exit(stringType); effects.enter(markerType); effects.consume(code); effects.exit(markerType); effects.exit(type); return ok } if (markdownLineEnding_1(code)) { effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); return atBreak } effects.enter('chunkString', {contentType: 'string'}); return label(code) } function label(code) { if ( code === null || code === 91 || code === 93 || markdownLineEnding_1(code) || size++ > 999 ) { effects.exit('chunkString'); return atBreak(code) } effects.consume(code); data = data || !markdownSpace_1(code); return code === 92 ? labelEscape : label } function labelEscape(code) { if (code === 91 || code === 92 || code === 93) { effects.consume(code); size++; return label } return label(code) } } var factoryWhitespace = createWhitespace; function createWhitespace(effects, ok) { var seen; return start function start(code) { if (markdownLineEnding_1(code)) { effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); seen = true; return start } if (markdownSpace_1(code)) { return factorySpace( effects, start, seen ? 'linePrefix' : 'lineSuffix' )(code) } return ok(code) } } var factoryTitle = createTitle; // eslint-disable-next-line max-params function createTitle(effects, ok, nok, type, markerType, stringType) { var marker; return start function start(code) { effects.enter(type); effects.enter(markerType); effects.consume(code); effects.exit(markerType); marker = code === 40 ? 41 : code; return atFirstTitleBreak } function atFirstTitleBreak(code) { if (code === marker) { effects.enter(markerType); effects.consume(code); effects.exit(markerType); effects.exit(type); return ok } effects.enter(stringType); return atTitleBreak(code) } function atTitleBreak(code) { if (code === marker) { effects.exit(stringType); return atFirstTitleBreak(marker) } if (code === null) { return nok(code) } // Note: blank lines can’t exist in content. if (markdownLineEnding_1(code)) { effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); return factorySpace(effects, atTitleBreak, 'linePrefix') } effects.enter('chunkString', {contentType: 'string'}); return title(code) } function title(code) { if (code === marker || code === null || markdownLineEnding_1(code)) { effects.exit('chunkString'); return atTitleBreak(code) } effects.consume(code); return code === 92 ? titleEscape : title } function titleEscape(code) { if (code === marker || code === 92) { effects.consume(code); return title } return title(code) } } var tokenize$e = tokenizeDefinition; function tokenizeDefinition(effects, ok, nok) { var self = this; var destinationAfter = effects.attempt( {tokenize: tokenizeTitle, partial: true}, factorySpace(effects, after, 'whitespace'), factorySpace(effects, after, 'whitespace') ); var identifier; return start function start(code) { effects.enter('definition'); return factoryLabel.call( self, effects, labelAfter, nok, 'definitionLabel', 'definitionLabelMarker', 'definitionLabelString' )(code) } function labelAfter(code) { identifier = normalizeIdentifier_1( self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1) ); if (code === 58) { effects.enter('definitionMarker'); effects.consume(code); effects.exit('definitionMarker'); // Note: blank lines can’t exist in content. return factoryWhitespace( effects, factoryDestination( effects, destinationAfter, nok, 'definitionDestination', 'definitionDestinationLiteral', 'definitionDestinationLiteralMarker', 'definitionDestinationRaw', 'definitionDestinationString' ) ) } return nok(code) } function after(code) { if (code === null || markdownLineEnding_1(code)) { effects.exit('definition'); if (self.parser.defined.indexOf(identifier) < 0) { self.parser.defined.push(identifier); } return ok(code) } return nok(code) } } function tokenizeTitle(effects, ok, nok) { return start function start(code) { return markdownLineEndingOrSpace_1(code) ? factoryWhitespace(effects, before)(code) : nok(code) } function before(code) { if (code === 34 || code === 39 || code === 40) { return factoryTitle( effects, factorySpace(effects, after, 'whitespace'), nok, 'definitionTitle', 'definitionTitleMarker', 'definitionTitleString' )(code) } return nok(code) } function after(code) { return code === null || markdownLineEnding_1(code) ? ok(code) : nok(code) } } var definition = { tokenize: tokenize$e }; var tokenize$f = tokenizeHardBreakEscape; function tokenizeHardBreakEscape(effects, ok, nok) { return start function start(code) { effects.enter('hardBreakEscape'); effects.enter('escapeMarker'); effects.consume(code); return open } function open(code) { if (markdownLineEnding_1(code)) { effects.exit('escapeMarker'); effects.exit('hardBreakEscape'); return ok(code) } return nok(code) } } var hardBreakEscape = { tokenize: tokenize$f }; // This module is copied from . var htmlBlockNames = [ 'address', 'article', 'aside', 'base', 'basefont', 'blockquote', 'body', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'iframe', 'legend', 'li', 'link', 'main', 'menu', 'menuitem', 'nav', 'noframes', 'ol', 'optgroup', 'option', 'p', 'param', 'section', 'source', 'summary', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul' ]; // This module is copied from . var htmlRawNames = ['pre', 'script', 'style']; var tokenize$g = tokenizeHtml; var resolveTo = resolveToHtml; var concrete$1 = true; var nextBlank = {tokenize: tokenizeNextBlank, partial: true}; function resolveToHtml(events) { var index = events.length; while (index--) { if (events[index][0] === 'enter' && events[index][1].type === 'htmlFlow') { break } } if (index > 1 && events[index - 2][1].type === 'linePrefix') { // Add the prefix start to the HTML token. events[index][1].start = events[index - 2][1].start; // Add the prefix start to the HTML line token. events[index + 1][1].start = events[index - 2][1].start; // Remove the line prefix. events.splice(index - 2, 2); } return events } function tokenizeHtml(effects, ok, nok) { var self = this; var kind; var startTag; var buffer; var index; var marker; return start function start(code) { effects.enter('htmlFlow'); effects.enter('htmlFlowData'); effects.consume(code); return open } function open(code) { if (code === 33) { effects.consume(code); return declarationStart } if (code === 47) { effects.consume(code); return tagCloseStart } if (code === 63) { effects.consume(code); kind = 3; // While we’re in an instruction instead of a declaration, we’re on a `?` // right now, so we do need to search for `>`, similar to declarations. return self.interrupt ? ok : continuationDeclarationInside } if (asciiAlpha(code)) { effects.consume(code); buffer = fromCharCode(code); startTag = true; return tagName } return nok(code) } function declarationStart(code) { if (code === 45) { effects.consume(code); kind = 2; return commentOpenInside } if (code === 91) { effects.consume(code); kind = 5; buffer = 'CDATA['; index = 0; return cdataOpenInside } if (asciiAlpha(code)) { effects.consume(code); kind = 4; return self.interrupt ? ok : continuationDeclarationInside } return nok(code) } function commentOpenInside(code) { if (code === 45) { effects.consume(code); return self.interrupt ? ok : continuationDeclarationInside } return nok(code) } function cdataOpenInside(code) { if (code === buffer.charCodeAt(index++)) { effects.consume(code); return index === buffer.length ? self.interrupt ? ok : continuation : cdataOpenInside } return nok(code) } function tagCloseStart(code) { if (asciiAlpha(code)) { effects.consume(code); buffer = fromCharCode(code); return tagName } return nok(code) } function tagName(code) { if ( code === null || code === 47 || code === 62 || markdownLineEndingOrSpace_1(code) ) { if (code !== 47 && startTag && htmlRawNames.indexOf(buffer.toLowerCase()) > -1) { kind = 1; return self.interrupt ? ok(code) : continuation(code) } if (htmlBlockNames.indexOf(buffer.toLowerCase()) > -1) { kind = 6; if (code === 47) { effects.consume(code); return basicSelfClosing } return self.interrupt ? ok(code) : continuation(code) } kind = 7; // Do not support complete HTML when interrupting. return self.interrupt ? nok(code) : startTag ? completeAttributeNameBefore(code) : completeClosingTagAfter(code) } if (code === 45 || asciiAlphanumeric(code)) { effects.consume(code); buffer += fromCharCode(code); return tagName } return nok(code) } function basicSelfClosing(code) { if (code === 62) { effects.consume(code); return self.interrupt ? ok : continuation } return nok(code) } function completeClosingTagAfter(code) { if (markdownSpace_1(code)) { effects.consume(code); return completeClosingTagAfter } return completeEnd(code) } function completeAttributeNameBefore(code) { if (code === 47) { effects.consume(code); return completeEnd } if (code === 58 || code === 95 || asciiAlpha(code)) { effects.consume(code); return completeAttributeName } if (markdownSpace_1(code)) { effects.consume(code); return completeAttributeNameBefore } return completeEnd(code) } function completeAttributeName(code) { if ( code === 45 || code === 46 || code === 58 || code === 95 || asciiAlphanumeric(code) ) { effects.consume(code); return completeAttributeName } return completeAttributeNameAfter(code) } function completeAttributeNameAfter(code) { if (code === 61) { effects.consume(code); return completeAttributeValueBefore } if (markdownSpace_1(code)) { effects.consume(code); return completeAttributeNameAfter } return completeAttributeNameBefore(code) } function completeAttributeValueBefore(code) { if ( code === null || code === 60 || code === 61 || code === 62 || code === 96 ) { return nok(code) } if (code === 34 || code === 39) { effects.consume(code); marker = code; return completeAttributeValueQuoted } if (markdownSpace_1(code)) { effects.consume(code); return completeAttributeValueBefore } marker = undefined; return completeAttributeValueUnquoted(code) } function completeAttributeValueQuoted(code) { if (code === marker) { effects.consume(code); return completeAttributeValueQuotedAfter } if (code === null || markdownLineEnding_1(code)) { return nok(code) } effects.consume(code); return completeAttributeValueQuoted } function completeAttributeValueUnquoted(code) { if ( code === null || code === 34 || code === 39 || code === 60 || code === 61 || code === 62 || code === 96 || markdownLineEndingOrSpace_1(code) ) { return completeAttributeNameAfter(code) } effects.consume(code); return completeAttributeValueUnquoted } function completeAttributeValueQuotedAfter(code) { if (code === 47 || code === 62 || markdownSpace_1(code)) { return completeAttributeNameBefore(code) } return nok(code) } function completeEnd(code) { if (code === 62) { effects.consume(code); return completeAfter } return nok(code) } function completeAfter(code) { if (markdownSpace_1(code)) { effects.consume(code); return completeAfter } return code === null || markdownLineEnding_1(code) ? continuation(code) : nok(code) } function continuation(code) { if (code === 45 && kind === 2) { effects.consume(code); return continuationCommentInside } if (code === 60 && kind === 1) { effects.consume(code); return continuationRawTagOpen } if (code === 62 && kind === 4) { effects.consume(code); return continuationClose } if (code === 63 && kind === 3) { effects.consume(code); return continuationDeclarationInside } if (code === 93 && kind === 5) { effects.consume(code); return continuationCharacterDataInside } if (markdownLineEnding_1(code) && (kind === 6 || kind === 7)) { return effects.check( nextBlank, continuationClose, continuationAtLineEnding )(code) } if (code === null || markdownLineEnding_1(code)) { return continuationAtLineEnding(code) } effects.consume(code); return continuation } function continuationAtLineEnding(code) { effects.exit('htmlFlowData'); return htmlContinueStart(code) } function htmlContinueStart(code) { if (code === null) { return done(code) } if (markdownLineEnding_1(code)) { effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); return htmlContinueStart } effects.enter('htmlFlowData'); return continuation(code) } function continuationCommentInside(code) { if (code === 45) { effects.consume(code); return continuationDeclarationInside } return continuation(code) } function continuationRawTagOpen(code) { if (code === 47) { effects.consume(code); buffer = ''; return continuationRawEndTag } return continuation(code) } function continuationRawEndTag(code) { if (code === 62 && htmlRawNames.indexOf(buffer.toLowerCase()) > -1) { effects.consume(code); return continuationClose } if (asciiAlpha(code) && buffer.length < 6) { effects.consume(code); buffer += fromCharCode(code); return continuationRawEndTag } return continuation(code) } function continuationCharacterDataInside(code) { if (code === 93) { effects.consume(code); return continuationDeclarationInside } return continuation(code) } function continuationDeclarationInside(code) { if (code === 62) { effects.consume(code); return continuationClose } return continuation(code) } function continuationClose(code) { if (code === null || markdownLineEnding_1(code)) { effects.exit('htmlFlowData'); return done(code) } effects.consume(code); return continuationClose } function done(code) { effects.exit('htmlFlow'); return ok(code) } } function tokenizeNextBlank(effects, ok, nok) { return start function start(code) { effects.exit('htmlFlowData'); effects.enter('lineEndingBlank'); effects.consume(code); effects.exit('lineEndingBlank'); return effects.attempt(partialBlankLine, ok, nok) } } var htmlFlow = { tokenize: tokenize$g, resolveTo: resolveTo, concrete: concrete$1 }; var tokenize$h = tokenizeHtml$1; function tokenizeHtml$1(effects, ok, nok) { var marker; var buffer; var index; var returnState; return start function start(code) { effects.enter('htmlText'); effects.enter('htmlTextData'); effects.consume(code); return open } function open(code) { if (code === 33) { effects.consume(code); return declarationOpen } if (code === 47) { effects.consume(code); return tagCloseStart } if (code === 63) { effects.consume(code); return instruction } if (asciiAlpha(code)) { effects.consume(code); return tagOpen } return nok(code) } function declarationOpen(code) { if (code === 45) { effects.consume(code); return commentOpen } if (code === 91) { effects.consume(code); buffer = 'CDATA['; index = 0; return cdataOpen } if (asciiAlpha(code)) { effects.consume(code); return declaration } return nok(code) } function commentOpen(code) { if (code === 45) { effects.consume(code); return commentStart } return nok(code) } function commentStart(code) { if (code === null || code === 62) { return nok(code) } if (code === 45) { effects.consume(code); return commentStartDash } return comment(code) } function commentStartDash(code) { if (code === null || code === 62) { return nok(code) } return comment(code) } function comment(code) { if (code === null) { return nok(code) } if (code === 45) { effects.consume(code); return commentClose } if (markdownLineEnding_1(code)) { returnState = comment; return atLineEnding(code) } effects.consume(code); return comment } function commentClose(code) { if (code === 45) { effects.consume(code); return end } return comment(code) } function cdataOpen(code) { if (code === buffer.charCodeAt(index++)) { effects.consume(code); return index === buffer.length ? cdata : cdataOpen } return nok(code) } function cdata(code) { if (code === null) { return nok(code) } if (code === 93) { effects.consume(code); return cdataClose } effects.consume(code); return cdata } function cdataClose(code) { if (code === 93) { effects.consume(code); return cdataEnd } return cdata(code) } function cdataEnd(code) { if (code === 62) { return end(code) } if (code === 93) { effects.consume(code); return cdataEnd } return cdata(code) } function declaration(code) { if (code === null || code === 62) { return end(code) } if (markdownLineEnding_1(code)) { returnState = declaration; return atLineEnding(code) } effects.consume(code); return declaration } function instruction(code) { if (code === null) { return nok(code) } if (code === 63) { effects.consume(code); return instructionClose } if (markdownLineEnding_1(code)) { returnState = instruction; return atLineEnding(code) } effects.consume(code); return instruction } function instructionClose(code) { return code === 62 ? end(code) : instruction(code) } function tagCloseStart(code) { if (asciiAlpha(code)) { effects.consume(code); return tagClose } return nok(code) } function tagClose(code) { if (code === 45 || asciiAlphanumeric(code)) { effects.consume(code); return tagClose } return tagCloseBetween(code) } function tagCloseBetween(code) { if (markdownLineEnding_1(code)) { returnState = tagCloseBetween; return atLineEnding(code) } if (markdownSpace_1(code)) { effects.consume(code); return tagCloseBetween } return end(code) } function tagOpen(code) { if (code === 45 || asciiAlphanumeric(code)) { effects.consume(code); return tagOpen } if (code === 47 || code === 62 || markdownLineEndingOrSpace_1(code)) { return tagOpenBetween(code) } return nok(code) } function tagOpenBetween(code) { if (code === 47) { effects.consume(code); return end } if (code === 58 || code === 95 || asciiAlpha(code)) { effects.consume(code); return tagOpenAttributeName } if (markdownLineEnding_1(code)) { returnState = tagOpenBetween; return atLineEnding(code) } if (markdownSpace_1(code)) { effects.consume(code); return tagOpenBetween } return end(code) } function tagOpenAttributeName(code) { if ( code === 45 || code === 46 || code === 58 || code === 95 || asciiAlphanumeric(code) ) { effects.consume(code); return tagOpenAttributeName } return tagOpenAttributeNameAfter(code) } function tagOpenAttributeNameAfter(code) { if (code === 61) { effects.consume(code); return tagOpenAttributeValueBefore } if (markdownLineEnding_1(code)) { returnState = tagOpenAttributeNameAfter; return atLineEnding(code) } if (markdownSpace_1(code)) { effects.consume(code); return tagOpenAttributeNameAfter } return tagOpenBetween(code) } function tagOpenAttributeValueBefore(code) { if ( code === null || code === 60 || code === 61 || code === 62 || code === 96 ) { return nok(code) } if (code === 34 || code === 39) { effects.consume(code); marker = code; return tagOpenAttributeValueQuoted } if (markdownLineEnding_1(code)) { returnState = tagOpenAttributeValueBefore; return atLineEnding(code) } if (markdownSpace_1(code)) { effects.consume(code); return tagOpenAttributeValueBefore } effects.consume(code); marker = undefined; return tagOpenAttributeValueUnquoted } function tagOpenAttributeValueQuoted(code) { if (code === marker) { effects.consume(code); return tagOpenAttributeValueQuotedAfter } if (code === null) { return nok(code) } if (markdownLineEnding_1(code)) { returnState = tagOpenAttributeValueQuoted; return atLineEnding(code) } effects.consume(code); return tagOpenAttributeValueQuoted } function tagOpenAttributeValueQuotedAfter(code) { if (code === 62 || code === 47 || markdownLineEndingOrSpace_1(code)) { return tagOpenBetween(code) } return nok(code) } function tagOpenAttributeValueUnquoted(code) { if ( code === null || code === 34 || code === 39 || code === 60 || code === 61 || code === 96 ) { return nok(code) } if (code === 62 || markdownLineEndingOrSpace_1(code)) { return tagOpenBetween(code) } effects.consume(code); return tagOpenAttributeValueUnquoted } // We can’t have blank lines in content, so no need to worry about empty // tokens. function atLineEnding(code) { effects.exit('htmlTextData'); effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); return factorySpace(effects, afterPrefix, 'linePrefix', 4) } function afterPrefix(code) { effects.enter('htmlTextData'); return returnState(code) } function end(code) { if (code === 62) { effects.consume(code); effects.exit('htmlTextData'); effects.exit('htmlText'); return ok } return nok(code) } } var htmlText = { tokenize: tokenize$h }; var tokenize$i = tokenizeLabelEnd; var resolveTo$1 = resolveToLabelEnd; var resolveAll_1$2 = resolveAllLabelEnd; var resource = {tokenize: tokenizeResource}; var fullReference = {tokenize: tokenizeFullReference}; var collapsedReference = {tokenize: tokenizeCollapsedReference}; function resolveAllLabelEnd(events) { var index = -1; var token; while (++index < events.length) { token = events[index][1]; if ( !token._used && (token.type === 'labelImage' || token.type === 'labelLink' || token.type === 'labelEnd') ) { // Remove the marker. events.splice(index + 1, token.type === 'labelImage' ? 4 : 2); token.type = 'data'; index++; } } return events } function resolveToLabelEnd(events, context) { var index = events.length; var offset = 0; var group; var label; var text; var token; var open; var close; var media; // Find an opening. while (index--) { token = events[index][1]; if (open) { // If we see another link, or inactive link label, we’ve been here before. if ( token.type === 'link' || (token.type === 'labelLink' && token._inactive) ) { break } // Mark other link openings as inactive, as we can’t have links in // links. if (events[index][0] === 'enter' && token.type === 'labelLink') { token._inactive = true; } } else if (close) { if ( events[index][0] === 'enter' && (token.type === 'labelImage' || token.type === 'labelLink') && !token._balanced ) { open = index; if (token.type !== 'labelLink') { offset = 2; break } } } else if (token.type === 'labelEnd') { close = index; } } group = { type: events[open][1].type === 'labelLink' ? 'link' : 'image', start: shallow_1(events[open][1].start), end: shallow_1(events[events.length - 1][1].end) }; label = { type: 'label', start: shallow_1(events[open][1].start), end: shallow_1(events[close][1].end) }; text = { type: 'labelText', start: shallow_1(events[open + offset + 2][1].end), end: shallow_1(events[close - 2][1].start) }; media = [ ['enter', group, context], ['enter', label, context] ]; // Opening marker. chunkedSplice_1( media, media.length, 0, events.slice(open + 1, open + offset + 3) ); // Text open. chunkedSplice_1(media, media.length, 0, [['enter', text, context]]); // Between. chunkedSplice_1( media, media.length, 0, resolveAll_1( context.parser.constructs.insideSpan.null, events.slice(open + offset + 4, close - 3), context ) ); // Text close, marker close, label close. chunkedSplice_1(media, media.length, 0, [ ['exit', text, context], events[close - 2], events[close - 1], ['exit', label, context] ]); // Reference, resource, or so. chunkedSplice_1(media, media.length, 0, events.slice(close + 1)); // Media close. chunkedSplice_1(media, media.length, 0, [['exit', group, context]]); chunkedSplice_1(events, open, events.length, media); return events } function tokenizeLabelEnd(effects, ok, nok) { var self = this; var index = self.events.length; var labelStart; var defined; // Find an opening. while (index--) { if ( (self.events[index][1].type === 'labelImage' || self.events[index][1].type === 'labelLink') && !self.events[index][1]._balanced ) { labelStart = self.events[index][1]; break } } return start function start(code) { if (!labelStart) { return nok(code) } // It’s a balanced bracket, but contains a link. if (labelStart._inactive) return balanced(code) defined = self.parser.defined.indexOf( normalizeIdentifier_1( self.sliceSerialize({start: labelStart.end, end: self.now()}) ) ) > -1; effects.enter('labelEnd'); effects.enter('labelMarker'); effects.consume(code); effects.exit('labelMarker'); effects.exit('labelEnd'); return afterLabelEnd } function afterLabelEnd(code) { // Resource: `[asd](fgh)`. if (code === 40) { return effects.attempt(resource, ok, defined ? ok : balanced)(code) } // Collapsed (`[asd][]`) or full (`[asd][fgh]`) reference? if (code === 91) { return effects.attempt( fullReference, ok, defined ? effects.attempt(collapsedReference, ok, balanced) : balanced )(code) } // Shortcut reference: `[asd]`? return defined ? ok(code) : balanced(code) } function balanced(code) { labelStart._balanced = true; return nok(code) } } function tokenizeResource(effects, ok, nok) { return start function start(code) { effects.enter('resource'); effects.enter('resourceMarker'); effects.consume(code); effects.exit('resourceMarker'); return factoryWhitespace(effects, open) } function open(code) { if (code === 41) { return end(code) } return factoryDestination( effects, destinationAfter, nok, 'resourceDestination', 'resourceDestinationLiteral', 'resourceDestinationLiteralMarker', 'resourceDestinationRaw', 'resourceDestinationString', 3 )(code) } function destinationAfter(code) { return markdownLineEndingOrSpace_1(code) ? factoryWhitespace(effects, between)(code) : end(code) } function between(code) { if (code === 34 || code === 39 || code === 40) { return factoryTitle( effects, factoryWhitespace(effects, end), nok, 'resourceTitle', 'resourceTitleMarker', 'resourceTitleString' )(code) } return end(code) } function end(code) { if (code === 41) { effects.enter('resourceMarker'); effects.consume(code); effects.exit('resourceMarker'); effects.exit('resource'); return ok } return nok(code) } } function tokenizeFullReference(effects, ok, nok) { var self = this; return start function start(code) { return factoryLabel.call( self, effects, afterLabel, nok, 'reference', 'referenceMarker', 'referenceString' )(code) } function afterLabel(code) { return self.parser.defined.indexOf( normalizeIdentifier_1( self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1) ) ) < 0 ? nok(code) : ok(code) } } function tokenizeCollapsedReference(effects, ok, nok) { return start function start(code) { effects.enter('reference'); effects.enter('referenceMarker'); effects.consume(code); effects.exit('referenceMarker'); return open } function open(code) { if (code === 93) { effects.enter('referenceMarker'); effects.consume(code); effects.exit('referenceMarker'); effects.exit('reference'); return ok } return nok(code) } } var labelEnd = { tokenize: tokenize$i, resolveTo: resolveTo$1, resolveAll: resolveAll_1$2 }; var tokenize$j = tokenizelabelImage; var resolveAll$1 = labelEnd.resolveAll; function tokenizelabelImage(effects, ok, nok) { var self = this; return start function start(code) { effects.enter('labelImage'); effects.enter('labelImageMarker'); effects.consume(code); effects.exit('labelImageMarker'); return open } function open(code) { if (code === 91) { effects.enter('labelMarker'); effects.consume(code); effects.exit('labelMarker'); effects.exit('labelImage'); return after } return nok(code) } function after(code) { /* istanbul ignore next - footnotes. */ return code === 94 && '_hiddenFootnoteSupport' in self.parser.constructs ? nok(code) : ok(code) } } var labelStartImage = { tokenize: tokenize$j, resolveAll: resolveAll$1 }; var tokenize$k = tokenizelabelLink; var resolveAll$2 = labelEnd.resolveAll; function tokenizelabelLink(effects, ok, nok) { var self = this; return start function start(code) { effects.enter('labelLink'); effects.enter('labelMarker'); effects.consume(code); effects.exit('labelMarker'); effects.exit('labelLink'); return after } function after(code) { /* istanbul ignore next - footnotes. */ return code === 94 && '_hiddenFootnoteSupport' in self.parser.constructs ? nok(code) : ok(code) } } var labelStartLink = { tokenize: tokenize$k, resolveAll: resolveAll$2 }; var tokenize$l = tokenizeSetextUnderline; var resolveTo$2 = resolveToSetextUnderline; function resolveToSetextUnderline(events, context) { var index = events.length; var content; var text; var definition; var heading; // Find the opening of the content. // It’ll always exist: we don’t tokenize if it isn’t there. while (index--) { if (events[index][0] === 'enter') { if (events[index][1].type === 'content') { content = index; break } if (events[index][1].type === 'paragraph') { text = index; } } // Exit else { if (events[index][1].type === 'content') { // Remove the content end (if needed we’ll add it later) events.splice(index, 1); } if (!definition && events[index][1].type === 'definition') { definition = index; } } } heading = { type: 'setextHeading', start: shallow_1(events[text][1].start), end: shallow_1(events[events.length - 1][1].end) }; // Change the paragraph to setext heading text. events[text][1].type = 'setextHeadingText'; // If we have definitions in the content, we’ll keep on having content, // but we need move it. if (definition) { events.splice(text, 0, ['enter', heading, context]); events.splice(definition + 1, 0, ['exit', events[content][1], context]); events[content][1].end = shallow_1(events[definition][1].end); } else { events[content][1] = heading; } // Add the heading exit at the end. events.push(['exit', heading, context]); return events } function tokenizeSetextUnderline(effects, ok, nok) { var self = this; var index = self.events.length; var marker; var paragraph; // Find an opening. while (index--) { // Skip enter/exit of line ending, line prefix, and content. // We can now either have a definition or a paragraph. if ( self.events[index][1].type !== 'lineEnding' && self.events[index][1].type !== 'linePrefix' && self.events[index][1].type !== 'content' ) { paragraph = self.events[index][1].type === 'paragraph'; break } } return start function start(code) { if (!self.lazy && (self.interrupt || paragraph)) { effects.enter('setextHeadingLine'); effects.enter('setextHeadingLineSequence'); marker = code; return closingSequence(code) } return nok(code) } function closingSequence(code) { if (code === marker) { effects.consume(code); return closingSequence } effects.exit('setextHeadingLineSequence'); return factorySpace(effects, closingSequenceEnd, 'lineSuffix')(code) } function closingSequenceEnd(code) { if (code === null || markdownLineEnding_1(code)) { effects.exit('setextHeadingLine'); return ok(code) } return nok(code) } } var setextUnderline = { tokenize: tokenize$l, resolveTo: resolveTo$2 }; var tokenize$m = tokenizeWhitespace; function tokenizeWhitespace(effects, ok) { return start function start(code) { effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); return factorySpace(effects, ok, 'linePrefix') } } var lineEnding = { tokenize: tokenize$m }; var resolveText = text.resolver; var document$2 = { 42: list, // Asterisk 43: list, // Plus sign 45: list, // Dash 48: list, // 0 49: list, // 1 50: list, // 2 51: list, // 3 52: list, // 4 53: list, // 5 54: list, // 6 55: list, // 7 56: list, // 8 57: list, // 9 62: blockQuote // Greater than }; var contentInitial = { 91: definition // Left square bracket }; var flowInitial = { '-2': codeIndented, // Horizontal tab '-1': codeIndented, // Virtual space 32: codeIndented // Space }; var flow$1 = { 35: headingAtx, // Number sign 42: thematicBreak, // Asterisk 45: [setextUnderline, thematicBreak], // Dash 60: htmlFlow, // Less than 61: setextUnderline, // Equals to 95: thematicBreak, // Underscore 96: codeFenced, // Grave accent 126: codeFenced // Tilde }; var string$1 = { 38: characterReference, // Ampersand 92: characterEscape // Backslash }; var text$1 = { '-5': lineEnding, // Carriage return '-4': lineEnding, // Line feed '-3': lineEnding, // Carriage return + line feed 33: labelStartImage, // Exclamation mark 38: characterReference, // Ampersand 42: attention, // Asterisk 60: [autolink, htmlText], // Less than 91: labelStartLink, // Left square bracket 92: [hardBreakEscape, characterEscape], // Backslash 93: labelEnd, // Right square bracket 95: attention, // Underscore 96: codeText // Grave accent }; var insideSpan = { null: [attention, resolveText] }; var constructs = { document: document$2, contentInitial: contentInitial, flowInitial: flowInitial, flow: flow$1, string: string$1, text: text$1, insideSpan: insideSpan }; var serializeChunks_1 = serializeChunks; function serializeChunks(chunks) { var index = -1; var result = []; var chunk; var value; var atTab; while (++index < chunks.length) { chunk = chunks[index]; if (typeof chunk === 'string') { value = chunk; } else if (chunk === -5) { value = '\r'; } else if (chunk === -4) { value = '\n'; } else if (chunk === -3) { value = '\r' + '\n'; } else if (chunk === -2) { value = '\t'; } else if (chunk === -1) { if (atTab) continue value = ' '; } else { // Currently only replacement character. value = fromCharCode(chunk); } atTab = chunk === -2; result.push(value); } return result.join('') } var sliceChunks_1 = sliceChunks; function sliceChunks(chunks, token) { var startIndex = token.start._index; var startBufferIndex = token.start._bufferIndex; var endIndex = token.end._index; var endBufferIndex = token.end._bufferIndex; var view; if (startIndex === endIndex) { view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)]; } else { view = chunks.slice(startIndex, endIndex); if (startBufferIndex > -1) { view[0] = view[0].slice(startBufferIndex); } if (endBufferIndex > 0) { view.push(chunks[endIndex].slice(0, endBufferIndex)); } } return view } var miniflat_1 = miniflat; function miniflat(value) { return value === null || value === undefined ? [] : 'length' in value ? value : [value] } var createTokenizer_1 = createTokenizer; // Create a tokenizer. // Tokenizers deal with one type of data (e.g., containers, flow, text). // The parser is the object dealing with it all. // `initialize` works like other constructs, except that only its `tokenize` // function is used, in which case it doesn’t receive an `ok` or `nok`. // `from` can be given to set the point before the first character, although // when further lines are indented, they must be set with `defineSkip`. function createTokenizer(parser, initialize, from) { var point = from ? shallow_1(from) : {line: 1, column: 1, offset: 0}; var columnStart = {}; var resolveAllConstructs = []; var chunks = []; var stack = []; // Tools used for tokenizing. var effects = { consume: consume, enter: enter, exit: exit, attempt: constructFactory(onsuccessfulconstruct), check: constructFactory(onsuccessfulcheck), interrupt: constructFactory(onsuccessfulcheck, {interrupt: true}), lazy: constructFactory(onsuccessfulcheck, {lazy: true}) }; // State and tools for resolving and serializing. var context = { previous: null, events: [], parser: parser, sliceStream: sliceStream, sliceSerialize: sliceSerialize, now: now, defineSkip: skip, write: write }; // The state function. var state = initialize.tokenize.call(context, effects); if (initialize.resolveAll) { resolveAllConstructs.push(initialize); } // Store where we are in the input stream. point._index = 0; point._bufferIndex = -1; return context function write(slice) { chunkedSplice_1(chunks, chunks.length, 0, slice); main(); // Exit if we’re not done, resolve might change stuff. if (chunks[chunks.length - 1] !== null) { return [] } addResult(initialize, 0); // Otherwise, resolve, and exit. context.events = resolveAll_1(resolveAllConstructs, context.events, context); return context.events } // // Tools. // function sliceSerialize(token) { return serializeChunks_1(sliceStream(token)) } function sliceStream(token) { return sliceChunks_1(chunks, token) } function now() { return shallow_1(point) } function skip(value) { columnStart[value.line] = value.column; accountForPotentialSkip(); } // // State management. // // Main loop (note that `_index` and `_bufferIndex` in `point` are modified by // `consume`). // Here is where we walk through the chunks, which either include strings of // several characters, or numerical character codes. // The reason to do this in a loop instead of a call is so the stack can // drain. function main() { var chunkIndex; var chunk; while (point._index < chunks.length) { chunk = chunks[point._index]; // If we’re in a buffer chunk, loop through it. if (typeof chunk === 'string') { chunkIndex = point._index; if (point._bufferIndex < 0) { point._bufferIndex = 0; } while ( point._index === chunkIndex && point._bufferIndex < chunk.length ) { go(chunk.charCodeAt(point._bufferIndex)); } } else { go(chunk); } } } // Deal with one code. function go(code) { state = state(code); } // Move a character forward. function consume(code) { if (markdownLineEnding_1(code)) { point.line++; point.column = 1; point.offset += code === -3 ? 2 : 1; accountForPotentialSkip(); } else if (code !== -1) { point.column++; point.offset++; } // Not in a string chunk. if (point._bufferIndex < 0) { point._index++; } else { point._bufferIndex++; // At end of string chunk. if (point._bufferIndex === chunks[point._index].length) { point._bufferIndex = -1; point._index++; } } // Expose the previous character. context.previous = code; } // Start a token. function enter(type, fields) { var token = fields || {}; token.type = type; token.start = now(); context.events.push(['enter', token, context]); stack.push(token); return token } // Stop a token. function exit(type) { var token = stack.pop(); token.end = now(); context.events.push(['exit', token, context]); return token } // Use results. function onsuccessfulconstruct(construct, info) { addResult(construct, info.from); } // Discard results. function onsuccessfulcheck(construct, info) { info.restore(); } // Factory to attempt/check/interrupt. function constructFactory(onreturn, fields) { return hook // Handle either an object mapping codes to constructs, a list of // constructs, or a single construct. function hook(constructs, returnState, bogusState) { var listOfConstructs; var constructIndex; var currentConstruct; var info; return constructs.tokenize || 'length' in constructs ? handleListOfConstructs(miniflat_1(constructs)) : handleMapOfConstructs function handleMapOfConstructs(code) { if (code in constructs || null in constructs) { return handleListOfConstructs( /* istanbul ignore next - `null` is used by some extensions */ constructs.null ? miniflat_1(constructs[code]).concat(miniflat_1(constructs.null)) : constructs[code] )(code) } return bogusState(code) } function handleListOfConstructs(list) { listOfConstructs = list; constructIndex = 0; return handleConstruct(list[constructIndex]) } function handleConstruct(construct) { return start function start(code) { // To do: not nede to store if there is no bogus state, probably? // Currently doesn’t work because `inspect` in document does a check // w/o a bogus, which doesn’t make sense. But it does seem to help perf // by not storing. info = store(); currentConstruct = construct; if (!construct.partial) { context.currentConstruct = construct; } return construct.tokenize.call( fields ? assign({}, context, fields) : context, effects, ok, nok )(code) } } function ok(code) { onreturn(currentConstruct, info); return returnState } function nok(code) { info.restore(); if (++constructIndex < listOfConstructs.length) { return handleConstruct(listOfConstructs[constructIndex]) } return bogusState } } } function addResult(construct, from) { if (construct.resolveAll && resolveAllConstructs.indexOf(construct) < 0) { resolveAllConstructs.push(construct); } if (construct.resolve) { chunkedSplice_1( context.events, from, context.events.length - from, construct.resolve(context.events.slice(from), context) ); } if (construct.resolveTo) { context.events = construct.resolveTo(context.events, context); } } function store() { var startPoint = now(); var startPrevious = context.previous; var startCurrentConstruct = context.currentConstruct; var startEventsIndex = context.events.length; var startStack = Array.from(stack); return {restore: restore, from: startEventsIndex} function restore() { point = startPoint; context.previous = startPrevious; context.currentConstruct = startCurrentConstruct; context.events.length = startEventsIndex; stack = startStack; accountForPotentialSkip(); } } function accountForPotentialSkip() { if (point.line in columnStart && point.column < 2) { point.column = columnStart[point.line]; point.offset += columnStart[point.line] - 1; } } } var combineExtensions_1 = combineExtensions; // Combine several syntax extensions into one. function combineExtensions(extensions) { var all = {}; var index = -1; while (++index < extensions.length) { extension$1(all, extensions[index]); } return all } function extension$1(all, extension) { var hook; var left; var right; var code; for (hook in extension) { left = hasOwnProperty_1.call(all, hook) ? all[hook] : (all[hook] = {}); right = extension[hook]; for (code in right) { left[code] = constructs$1( miniflat_1(right[code]), hasOwnProperty_1.call(left, code) ? left[code] : [] ); } } } function constructs$1(list, existing) { var index = -1; var before = []; while (++index < list.length) { (list[index].add === 'after' ? existing : before).push(list[index]); } chunkedSplice_1(existing, 0, 0, before); return existing } var parse$8 = createParser; function createParser(options) { var settings = options || {}; var parser = { defined: [], constructs: combineExtensions_1( [constructs].concat(miniflat_1(settings.extensions)) ), content: create(content), document: create(document$1), flow: create(flow), string: create(text.string), text: create(text.text) }; return parser function create(initializer) { return creator function creator(from) { return createTokenizer_1(parser, initializer, from) } } } var preprocess = preprocessor; var search$1 = /[\0\t\n\r]/g; function preprocessor() { var start = true; var column = 1; var buffer = ''; var atCarriageReturn; return preprocess function preprocess(value, encoding, end) { var chunks = []; var match; var next; var startPosition; var endPosition; var code; value = buffer + value.toString(encoding); startPosition = 0; buffer = ''; if (start) { if (value.charCodeAt(0) === 65279) { startPosition++; } start = undefined; } while (startPosition < value.length) { search$1.lastIndex = startPosition; match = search$1.exec(value); endPosition = match ? match.index : value.length; code = value.charCodeAt(endPosition); if (!match) { buffer = value.slice(startPosition); break } if (code === 10 && startPosition === endPosition && atCarriageReturn) { chunks.push(-3); atCarriageReturn = undefined; } else { if (atCarriageReturn) { chunks.push(-5); atCarriageReturn = undefined; } if (startPosition < endPosition) { chunks.push(value.slice(startPosition, endPosition)); column += endPosition - startPosition; } if (code === 0) { chunks.push(65533); column++; } else if (code === 9) { next = Math.ceil(column / 4) * 4; chunks.push(-2); while (column++ < next) chunks.push(-1); } else if (code === 10) { chunks.push(-4); column = 1; } // Must be carriage return. else { atCarriageReturn = true; column = 1; } } startPosition = endPosition + 1; } if (end) { if (atCarriageReturn) chunks.push(-5); if (buffer) chunks.push(buffer); chunks.push(null); } return chunks } } var postprocess_1 = postprocess; function postprocess(events) { while (!subtokenize_1(events)) { // Empty } return events } var dist$2 = fromMarkdown; // These three are compiled away in the `dist/` function fromMarkdown(value, encoding, options) { if (typeof encoding !== 'string') { options = encoding; encoding = undefined; } return compiler(options)( postprocess_1( parse$8(options).document().write(preprocess()(value, encoding, true)) ) ) } // Note this compiler only understand complete buffering, not streaming. function compiler(options) { var settings = options || {}; var config = configure$2( { canContainEols: [ 'emphasis', 'fragment', 'heading', 'paragraph', 'strong' ], enter: { autolink: opener(link), autolinkProtocol: onenterdata, autolinkEmail: onenterdata, atxHeading: opener(heading), blockQuote: opener(blockQuote), characterEscape: onenterdata, characterReference: onenterdata, codeFenced: opener(codeFlow), codeFencedFenceInfo: buffer, codeFencedFenceMeta: buffer, codeIndented: opener(codeFlow, buffer), codeText: opener(codeText, buffer), codeTextData: onenterdata, data: onenterdata, codeFlowValue: onenterdata, definition: opener(definition), definitionDestinationString: buffer, definitionLabelString: buffer, definitionTitleString: buffer, emphasis: opener(emphasis), hardBreakEscape: opener(hardBreak), hardBreakTrailing: opener(hardBreak), htmlFlow: opener(html, buffer), htmlFlowData: onenterdata, htmlText: opener(html, buffer), htmlTextData: onenterdata, image: opener(image), label: buffer, link: opener(link), listItem: opener(listItem), listItemValue: onenterlistitemvalue, listOrdered: opener(list, onenterlistordered), listUnordered: opener(list), paragraph: opener(paragraph), reference: onenterreference, referenceString: buffer, resourceDestinationString: buffer, resourceTitleString: buffer, setextHeading: opener(heading), strong: opener(strong), thematicBreak: opener(thematicBreak) }, exit: { atxHeading: closer(), atxHeadingSequence: onexitatxheadingsequence, autolink: closer(), autolinkEmail: onexitautolinkemail, autolinkProtocol: onexitautolinkprotocol, blockQuote: closer(), characterEscapeValue: onexitdata, characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker, characterReferenceMarkerNumeric: onexitcharacterreferencemarker, characterReferenceValue: closer(onexitcharacterreferencevalue), codeFenced: closer(onexitcodefenced), codeFencedFence: onexitcodefencedfence, codeFencedFenceInfo: onexitcodefencedfenceinfo, codeFencedFenceMeta: onexitcodefencedfencemeta, codeFlowValue: onexitdata, codeIndented: closer(onexitcodeindented), codeText: closer(onexitcodetext), codeTextData: onexitdata, data: onexitdata, definition: closer(), definitionDestinationString: onexitdefinitiondestinationstring, definitionLabelString: onexitdefinitionlabelstring, definitionTitleString: onexitdefinitiontitlestring, emphasis: closer(), hardBreakEscape: closer(onexithardbreak), hardBreakTrailing: closer(onexithardbreak), htmlFlow: closer(onexithtmlflow), htmlFlowData: onexitdata, htmlText: closer(onexithtmltext), htmlTextData: onexitdata, image: closer(onexitimage), label: onexitlabel, labelText: onexitlabeltext, lineEnding: onexitlineending, link: closer(onexitlink), listItem: closer(), listOrdered: closer(), listUnordered: closer(), paragraph: closer(), referenceString: onexitreferencestring, resourceDestinationString: onexitresourcedestinationstring, resourceTitleString: onexitresourcetitlestring, resource: onexitresource, setextHeading: closer(onexitsetextheading), setextHeadingLineSequence: onexitsetextheadinglinesequence, setextHeadingText: onexitsetextheadingtext, strong: closer(), thematicBreak: closer() } }, settings.mdastExtensions || [] ); var data = {}; return compile function compile(events) { var stack = [{type: 'root', children: []}]; var index = -1; var listStack = []; var length; var handler; var listStart; var event; while (++index < events.length) { event = events[index]; // We preprocess lists to add `listItem` tokens, and to infer whether // items the list itself are spread out. if ( event[1].type === 'listOrdered' || event[1].type === 'listUnordered' ) { if (event[0] === 'enter') { listStack.push(index); } else { listStart = listStack.pop(index); index = prepareList(events, listStart, index); } } } index = -1; length = events.length; while (++index < length) { handler = config[events[index][0]]; if (hasOwnProperty_1.call(handler, events[index][1].type)) { handler[events[index][1].type].call( { stack: stack, config: config, enter: enter, exit: exit, buffer: buffer, resume: resume, sliceSerialize: events[index][2].sliceSerialize, setData: setData, getData: getData }, events[index][1] ); } } // Figure out `root` position. stack[0].position = { start: point( length ? events[0][1].start : {line: 1, column: 1, offset: 0} ), end: point( length ? events[events.length - 2][1].end : {line: 1, column: 1, offset: 0} ) }; return stack[0] } function prepareList(events, start, length) { var index = start - 1; var containerBalance = -1; var listSpread = false; var listItem; var tailIndex; var lineIndex; var tailEvent; var event; var firstBlankLineIndex; var atMarker; while (++index <= length) { event = events[index]; if ( event[1].type === 'listUnordered' || event[1].type === 'listOrdered' || event[1].type === 'blockQuote' ) { if (event[0] === 'enter') { containerBalance++; } else { containerBalance--; } atMarker = undefined; } else if (event[1].type === 'lineEndingBlank') { if (event[0] === 'enter') { if ( listItem && !atMarker && !containerBalance && !firstBlankLineIndex ) { firstBlankLineIndex = index; } atMarker = undefined; } } else if ( event[1].type === 'linePrefix' || event[1].type === 'listItemValue' || event[1].type === 'listItemMarker' || event[1].type === 'listItemPrefix' || event[1].type === 'listItemPrefixWhitespace' ) ; else { atMarker = undefined; } if ( (!containerBalance && event[0] === 'enter' && event[1].type === 'listItemPrefix') || (containerBalance === -1 && event[0] === 'exit' && (event[1].type === 'listUnordered' || event[1].type === 'listOrdered')) ) { if (listItem) { tailIndex = index; lineIndex = undefined; while (tailIndex--) { tailEvent = events[tailIndex]; if ( tailEvent[1].type === 'lineEnding' || tailEvent[1].type === 'lineEndingBlank' ) { if (tailEvent[0] === 'exit') continue if (lineIndex) { events[lineIndex][1].type = 'lineEndingBlank'; listSpread = true; } tailEvent[1].type = 'lineEnding'; lineIndex = tailIndex; } else if ( tailEvent[1].type === 'linePrefix' || tailEvent[1].type === 'blockQuotePrefix' || tailEvent[1].type === 'blockQuotePrefixWhitespace' || tailEvent[1].type === 'blockQuoteMarker' || tailEvent[1].type === 'listItemIndent' ) ; else { break } } if ( firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex) ) { listItem._spread = true; } // Fix position. listItem.end = point( lineIndex ? events[lineIndex][1].start : event[1].end ); events.splice(lineIndex || index, 0, ['exit', listItem, event[2]]); index++; length++; } // Create a new list item. if (event[1].type === 'listItemPrefix') { listItem = { type: 'listItem', _spread: false, start: point(event[1].start) }; events.splice(index, 0, ['enter', listItem, event[2]]); index++; length++; firstBlankLineIndex = undefined; atMarker = true; } } } events[start][1]._spread = listSpread; return length } function setData(key, value) { data[key] = value; } function getData(key) { return data[key] } function point(d) { return {line: d.line, column: d.column, offset: d.offset} } function opener(create, and) { return open function open(token) { enter.call(this, create(token), token); if (and) and.call(this, token); } } function buffer() { this.stack.push({type: 'fragment', children: []}); } function enter(node, token) { this.stack[this.stack.length - 1].children.push(node); this.stack.push(node); node.position = {start: point(token.start)}; return node } function closer(and) { return close function close(token) { if (and) and.call(this, token); exit.call(this, token); } } function exit(token) { var node = this.stack.pop(); node.position.end = point(token.end); return node } function resume() { var value = mdastUtilToString(this.stack.pop()); return value } // // Handlers. // function onenterlistordered() { setData('expectingFirstListItemValue', true); } function onenterlistitemvalue(token) { if (getData('expectingFirstListItemValue')) { this.stack[this.stack.length - 2].start = parseInt( this.sliceSerialize(token), 10 ); setData('expectingFirstListItemValue'); } } function onexitcodefencedfenceinfo() { var data = this.resume(); this.stack[this.stack.length - 1].lang = data; } function onexitcodefencedfencemeta() { var data = this.resume(); this.stack[this.stack.length - 1].meta = data; } function onexitcodefencedfence() { // Exit if this is the closing fence. if (getData('flowCodeInside')) return this.buffer(); setData('flowCodeInside', true); } function onexitcodefenced() { var data = this.resume(); this.stack[this.stack.length - 1].value = data.replace( /^(\r?\n|\r)|(\r?\n|\r)$/g, '' ); setData('flowCodeInside'); } function onexitcodeindented() { var data = this.resume(); this.stack[this.stack.length - 1].value = data; } function onexitdefinitionlabelstring(token) { // Discard label, use the source content instead. var label = this.resume(); this.stack[this.stack.length - 1].label = label; this.stack[this.stack.length - 1].identifier = normalizeIdentifier_1( this.sliceSerialize(token) ).toLowerCase(); } function onexitdefinitiontitlestring() { var data = this.resume(); this.stack[this.stack.length - 1].title = data; } function onexitdefinitiondestinationstring() { var data = this.resume(); this.stack[this.stack.length - 1].url = data; } function onexitatxheadingsequence(token) { if (!this.stack[this.stack.length - 1].depth) { this.stack[this.stack.length - 1].depth = this.sliceSerialize( token ).length; } } function onexitsetextheadingtext() { setData('setextHeadingSlurpLineEnding', true); } function onexitsetextheadinglinesequence(token) { this.stack[this.stack.length - 1].depth = this.sliceSerialize(token).charCodeAt(0) === 61 ? 1 : 2; } function onexitsetextheading() { setData('setextHeadingSlurpLineEnding'); } function onenterdata(token) { var siblings = this.stack[this.stack.length - 1].children; var tail = siblings[siblings.length - 1]; if (!tail || tail.type !== 'text') { // Add a new text node. tail = text(); tail.position = {start: point(token.start)}; this.stack[this.stack.length - 1].children.push(tail); } this.stack.push(tail); } function onexitdata(token) { var tail = this.stack.pop(); tail.value += this.sliceSerialize(token); tail.position.end = point(token.end); } function onexitlineending(token) { var context = this.stack[this.stack.length - 1]; // If we’re at a hard break, include the line ending in there. if (getData('atHardBreak')) { context.children[context.children.length - 1].position.end = point( token.end ); setData('atHardBreak'); return } if (getData('setextHeadingSlurpLineEnding')) { return } if (config.canContainEols.indexOf(context.type) !== -1) { onenterdata.call(this, token); onexitdata.call(this, token); } } function onexithardbreak() { setData('atHardBreak', true); } function onexithtmlflow() { var data = this.resume(); this.stack[this.stack.length - 1].value = data; } function onexithtmltext() { var data = this.resume(); this.stack[this.stack.length - 1].value = data; } function onexitcodetext() { var data = this.resume(); this.stack[this.stack.length - 1].value = data; } function onexitlink() { var context = this.stack[this.stack.length - 1]; // To do: clean. if (getData('inReference')) { context.type += 'Reference'; context.referenceType = getData('referenceType') || 'shortcut'; delete context.url; delete context.title; } else { delete context.identifier; delete context.label; delete context.referenceType; } setData('referenceType'); } function onexitimage() { var context = this.stack[this.stack.length - 1]; // To do: clean. if (getData('inReference')) { context.type += 'Reference'; context.referenceType = getData('referenceType') || 'shortcut'; delete context.url; delete context.title; } else { delete context.identifier; delete context.label; delete context.referenceType; } setData('referenceType'); } function onexitlabeltext(token) { this.stack[this.stack.length - 2].identifier = normalizeIdentifier_1( this.sliceSerialize(token) ).toLowerCase(); } function onexitlabel() { var fragment = this.stack[this.stack.length - 1]; var value = this.resume(); this.stack[this.stack.length - 1].label = value; // Assume a reference. setData('inReference', true); if (this.stack[this.stack.length - 1].type === 'link') { this.stack[this.stack.length - 1].children = fragment.children; } else { this.stack[this.stack.length - 1].alt = value; } } function onexitresourcedestinationstring() { var data = this.resume(); this.stack[this.stack.length - 1].url = data; } function onexitresourcetitlestring() { var data = this.resume(); this.stack[this.stack.length - 1].title = data; } function onexitresource() { setData('inReference'); } function onenterreference() { setData('referenceType', 'collapsed'); } function onexitreferencestring(token) { var label = this.resume(); this.stack[this.stack.length - 1].label = label; this.stack[this.stack.length - 1].identifier = normalizeIdentifier_1( this.sliceSerialize(token) ).toLowerCase(); setData('referenceType', 'full'); } function onexitcharacterreferencemarker(token) { setData('characterReferenceType', token.type); } function onexitcharacterreferencevalue(token) { var data = this.sliceSerialize(token); var type = getData('characterReferenceType'); var value; if (type) { value = safeFromInt_1( data, type === 'characterReferenceMarkerNumeric' ? 10 : 16 ); setData('characterReferenceType'); } else { value = decodeEntity_1(data); } this.stack[this.stack.length - 1].value += value; } function onexitautolinkprotocol(token) { onexitdata.call(this, token); this.stack[this.stack.length - 1].url = this.sliceSerialize(token); } function onexitautolinkemail(token) { onexitdata.call(this, token); this.stack[this.stack.length - 1].url = 'mailto:' + this.sliceSerialize(token); } // // Creaters. // function blockQuote() { return {type: 'blockquote', children: []} } function codeFlow() { return {type: 'code', lang: null, meta: null, value: ''} } function codeText() { return {type: 'inlineCode', value: ''} } function definition() { return { type: 'definition', identifier: '', label: null, title: null, url: '' } } function emphasis() { return {type: 'emphasis', children: []} } function heading() { return {type: 'heading', depth: undefined, children: []} } function hardBreak() { return {type: 'break'} } function html() { return {type: 'html', value: ''} } function image() { return {type: 'image', title: null, url: '', alt: null} } function link() { return {type: 'link', title: null, url: '', children: []} } function list(token) { return { type: 'list', ordered: token.type === 'listOrdered', start: null, spread: token._spread, children: [] } } function listItem(token) { return { type: 'listItem', spread: token._spread, checked: null, children: [] } } function paragraph() { return {type: 'paragraph', children: []} } function strong() { return {type: 'strong', children: []} } function text() { return {type: 'text', value: ''} } function thematicBreak() { return {type: 'thematicBreak'} } } function configure$2(config, extensions) { var length = extensions.length; var index = -1; while (++index < length) { extension$2(config, extensions[index]); } return config } function extension$2(config, extension) { var key; var left; var right; for (key in extension) { left = hasOwnProperty_1.call(config, key) ? config[key] : (config[key] = {}); right = extension[key]; if (key === 'canContainEols') { config[key] = [].concat(left, right); } else { Object.assign(left, right); } } } var mdastUtilFromMarkdown = dist$2; var remarkParse = parse$9; function parse$9(options) { var self = this; this.Parser = parse; function parse(doc) { return mdastUtilFromMarkdown( doc, Object.assign({}, self.data('settings'), options, { // Note: these options are not in the readme. // The goal is for them to be set by plugins on `data` instead of being // passed by users. extensions: self.data('micromarkExtensions') || [], mdastExtensions: self.data('fromMarkdownExtensions') || [] }) ) } } var zwitch = factory$1; var noop$2 = Function.prototype; var own$4 = {}.hasOwnProperty; // Handle values based on a property. function factory$1(key, options) { var settings = options || {}; function one(value) { var fn = one.invalid; var handlers = one.handlers; if (value && own$4.call(value, key)) { fn = own$4.call(handlers, value[key]) ? handlers[value[key]] : one.unknown; } return (fn || noop$2).apply(this, arguments) } one.handlers = settings.handlers || {}; one.invalid = settings.invalid; one.unknown = settings.unknown; return one } var containerFlow = flow$2; function flow$2(parent, context) { var children = parent.children || []; var results = []; var index = -1; var child; while (++index < children.length) { child = children[index]; results.push( context.handle(child, parent, context, {before: '\n', after: '\n'}) ); if (index + 1 < children.length) { results.push(between(child, children[index + 1])); } } return results.join('') function between(left, right) { var index = -1; var result; while (++index < context.join.length) { result = context.join[index](left, right, parent, context); if (result === true || result === 1) { break } if (typeof result === 'number') { return repeatString('\n', 1 + Number(result)) } if (result === false) { return '\n\n\n\n' } } return '\n\n' } } var indentLines_1 = indentLines; var eol = /\r?\n|\r/g; function indentLines(value, map) { var result = []; var start = 0; var line = 0; var match; while ((match = eol.exec(value))) { one(value.slice(start, match.index)); result.push(match[0]); start = match.index + match[0].length; line++; } one(value.slice(start)); return result.join('') function one(value) { result.push(map(value, line, !value)); } } var blockquote_1 = blockquote; function blockquote(node, _, context) { var exit = context.enter('blockquote'); var value = indentLines_1(containerFlow(node, context), map$3); exit(); return value } function map$3(line, index, blank) { return '>' + (blank ? '' : ' ') + line } var _break = hardBreak; function hardBreak() { return '\\\n' } var longestStreak_1 = longestStreak; // Get the count of the longest repeating streak of `character` in `value`. function longestStreak(value, character) { var count = 0; var maximum = 0; var expected; var index; if (typeof character !== 'string' || character.length !== 1) { throw new Error('Expected character') } value = String(value); index = value.indexOf(character); expected = index; while (index !== -1) { count++; if (index === expected) { if (count > maximum) { maximum = count; } } else { count = 1; } expected = index + 1; index = value.indexOf(character, expected); } return maximum } var formatCodeAsIndented_1 = formatCodeAsIndented; function formatCodeAsIndented(node, context) { return ( node.value && !context.options.fences && // If there’s no info… !node.lang && // And there’s a non-whitespace character… /[^ \r\n]/.test(node.value) && // And the value doesn’t start or end in a blank… !/^[\t ]*[\r\n]|[\r\n][\t ]*$/.test(node.value) ) } var checkFence_1 = checkFence; function checkFence(context) { var marker = context.options.fence || '`'; if (marker !== '`' && marker !== '~') { throw new Error( 'Cannot serialize code with `' + marker + '` for `options.fence`, expected `` ` `` or `~`' ) } return marker } var safe_1 = safe; function safe(context, input, config) { var value = (config.before || '') + (input || '') + (config.after || ''); var positions = []; var result = []; var infos = {}; var index = -1; var before; var after; var position; var pattern; var expression; var match; var start; var end; while (++index < context.unsafePatterns.length) { pattern = context.unsafePatterns[index]; if ( !inScope(context.stack, pattern.inConstruct, true) || inScope(context.stack, pattern.notInConstruct) ) { continue } expression = pattern._compiled || (pattern._compiled = toExpression(pattern)); while ((match = expression.exec(value))) { before = 'before' in pattern || pattern.atBreak; after = 'after' in pattern; position = match.index + (before ? match[1].length : 0); if (positions.indexOf(position) === -1) { positions.push(position); infos[position] = {before: before, after: after}; } else { if (infos[position].before && !before) { infos[position].before = false; } if (infos[position].after && !after) { infos[position].after = false; } } } } positions.sort(numerical); start = config.before ? config.before.length : 0; end = value.length - (config.after ? config.after.length : 0); index = -1; while (++index < positions.length) { position = positions[index]; if ( // Character before or after matched: position < start || position >= end ) { continue } // If this character is supposed to be escaped because it has a condition on // the next character, and the next character is definitly being escaped, // then skip this escape. if ( position + 1 < end && positions[index + 1] === position + 1 && infos[position].after && !infos[position + 1].before && !infos[position + 1].after ) { continue } if (start !== position) { result.push(value.slice(start, position)); } start = position; if ( /[!-/:-@[-`{-~]/.test(value.charAt(position)) && (!config.encode || config.encode.indexOf(value.charAt(position)) === -1) ) { // Character escape. result.push('\\'); } else { // Character reference. result.push( '&#x' + value.charCodeAt(position).toString(16).toUpperCase() + ';' ); start++; } } result.push(value.slice(start, end)); return result.join('') } function inScope(stack, list, none) { var index; if (!list) { return none } if (typeof list === 'string') { list = [list]; } index = -1; while (++index < list.length) { if (stack.indexOf(list[index]) !== -1) { return true } } return false } function toExpression(pattern) { var before = pattern.before ? '(?:' + pattern.before + ')' : ''; var after = pattern.after ? '(?:' + pattern.after + ')' : ''; if (pattern.atBreak) { before = '[\\r\\n][\\t ]*' + before; } return new RegExp( (before ? '(' + before + ')' : '') + (/[|\\{}()[\]^$+*?.-]/.test(pattern.character) ? '\\' : '') + pattern.character + (after || ''), 'g' ) } function numerical(a, b) { return a - b } var code_1 = code; function code(node, _, context) { var marker = checkFence_1(context); var raw = node.value || ''; var suffix = marker === '`' ? 'GraveAccent' : 'Tilde'; var value; var sequence; var exit; var subexit; if (formatCodeAsIndented_1(node, context)) { exit = context.enter('codeIndented'); value = indentLines_1(raw, map$4); } else { sequence = repeatString(marker, Math.max(longestStreak_1(raw, marker) + 1, 3)); exit = context.enter('codeFenced'); value = sequence; if (node.lang) { subexit = context.enter('codeFencedLang' + suffix); value += safe_1(context, node.lang, { before: '`', after: ' ', encode: ['`'] }); subexit(); } if (node.lang && node.meta) { subexit = context.enter('codeFencedMeta' + suffix); value += ' ' + safe_1(context, node.meta, { before: ' ', after: '\n', encode: ['`'] }); subexit(); } value += '\n'; if (raw) { value += raw + '\n'; } value += sequence; } exit(); return value } function map$4(line, _, blank) { return (blank ? '' : ' ') + line } var association_1 = association; var characterEscape$1 = /\\([!-/:-@[-`{-~])/g; var characterReference$1 = /&(#(\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi; // The `label` of an association is the string value: character escapes and // references work, and casing is intact. // The `identifier` is used to match one association to another: controversially, // character escapes and references don’t work in this matching: `©` does // not match `©`, and `\+` does not match `+`. // But casing is ignored (and whitespace) is trimmed and collapsed: ` A\nb` // matches `a b`. // So, we do prefer the label when figuring out how we’re going to serialize: // it has whitespace, casing, and we can ignore most useless character escapes // and all character references. function association(node) { if (node.label || !node.identifier) { return node.label || '' } return node.identifier .replace(characterEscape$1, '$1') .replace(characterReference$1, decodeIfPossible) } function decodeIfPossible($0, $1) { return decodeEntity_1($1) || $0 } var checkQuote_1 = checkQuote; function checkQuote(context) { var marker = context.options.quote || '"'; if (marker !== '"' && marker !== "'") { throw new Error( 'Cannot serialize title with `' + marker + '` for `options.quote`, expected `"`, or `\'`' ) } return marker } var definition_1 = definition$1; function definition$1(node, _, context) { var marker = checkQuote_1(context); var suffix = marker === '"' ? 'Quote' : 'Apostrophe'; var exit = context.enter('definition'); var subexit = context.enter('label'); var value = '[' + safe_1(context, association_1(node), {before: '[', after: ']'}) + ']: '; subexit(); if ( // If there’s no url, or… !node.url || // If there’s whitespace, enclosed is prettier. /[ \t\r\n]/.test(node.url) ) { subexit = context.enter('destinationLiteral'); value += '<' + safe_1(context, node.url, {before: '<', after: '>'}) + '>'; } else { // No whitespace, raw is prettier. subexit = context.enter('destinationRaw'); value += safe_1(context, node.url, {before: ' ', after: ' '}); } subexit(); if (node.title) { subexit = context.enter('title' + suffix); value += ' ' + marker + safe_1(context, node.title, {before: marker, after: marker}) + marker; subexit(); } exit(); return value } var checkEmphasis_1 = checkEmphasis; function checkEmphasis(context) { var marker = context.options.emphasis || '*'; if (marker !== '*' && marker !== '_') { throw new Error( 'Cannot serialize emphasis with `' + marker + '` for `options.emphasis`, expected `*`, or `_`' ) } return marker } var containerPhrasing = phrasing; function phrasing(parent, context, safeOptions) { var children = parent.children || []; var results = []; var index = -1; var before = safeOptions.before; var after; var handle; var child; while (++index < children.length) { child = children[index]; if (index + 1 < children.length) { handle = context.handle.handlers[children[index + 1].type]; if (handle && handle.peek) handle = handle.peek; after = handle ? handle(children[index + 1], parent, context, { before: '', after: '' }).charAt(0) : ''; } else { after = safeOptions.after; } results.push( context.handle(child, parent, context, { before: before, after: after }) ); before = results[results.length - 1].slice(-1); } return results.join('') } var emphasis_1 = emphasis; emphasis.peek = emphasisPeek; // To do: there are cases where emphasis cannot “form” depending on the // previous or next character of sequences. // There’s no way around that though, except for injecting zero-width stuff. // Do we need to safeguard against that? function emphasis(node, _, context) { var marker = checkEmphasis_1(context); var exit = context.enter('emphasis'); var value = containerPhrasing(node, context, {before: marker, after: marker}); exit(); return marker + value + marker } function emphasisPeek(node, _, context) { return context.options.emphasis || '*' } var formatHeadingAsSetext_1 = formatHeadingAsSetext; function formatHeadingAsSetext(node, context) { return ( context.options.setext && (!node.depth || node.depth < 3) && mdastUtilToString(node) ) } var heading_1 = heading; function heading(node, _, context) { var rank = Math.max(Math.min(6, node.depth || 1), 1); var exit; var subexit; var value; var sequence; if (formatHeadingAsSetext_1(node, context)) { exit = context.enter('headingSetext'); subexit = context.enter('phrasing'); value = containerPhrasing(node, context, {before: '\n', after: '\n'}); subexit(); exit(); return ( value + '\n' + repeatString( rank === 1 ? '=' : '-', // The whole size… value.length - // Minus the position of the character after the last EOL (or // 0 if there is none)… (Math.max(value.lastIndexOf('\r'), value.lastIndexOf('\n')) + 1) ) ) } sequence = repeatString('#', rank); exit = context.enter('headingAtx'); subexit = context.enter('phrasing'); value = containerPhrasing(node, context, {before: '# ', after: '\n'}); value = value ? sequence + ' ' + value : sequence; if (context.options.closeAtx) { value += ' ' + sequence; } subexit(); exit(); return value } var html_1 = html; function html(node) { return node.value || '' } var image_1 = image$1; image$1.peek = imagePeek; function image$1(node, _, context) { var quote = checkQuote_1(context); var suffix = quote === '"' ? 'Quote' : 'Apostrophe'; var exit = context.enter('image'); var subexit = context.enter('label'); var value = '![' + safe_1(context, node.alt, {before: '[', after: ']'}) + ']('; subexit(); if ( // If there’s no url but there is a title… (!node.url && node.title) || // Or if there’s markdown whitespace or an eol, enclose. /[ \t\r\n]/.test(node.url) ) { subexit = context.enter('destinationLiteral'); value += '<' + safe_1(context, node.url, {before: '<', after: '>'}) + '>'; } else { // No whitespace, raw is prettier. subexit = context.enter('destinationRaw'); value += safe_1(context, node.url, { before: '(', after: node.title ? ' ' : ')' }); } subexit(); if (node.title) { subexit = context.enter('title' + suffix); value += ' ' + quote + safe_1(context, node.title, {before: quote, after: quote}) + quote; subexit(); } value += ')'; exit(); return value } function imagePeek() { return '!' } var imageReference_1 = imageReference; imageReference.peek = imageReferencePeek; function imageReference(node, _, context) { var type = node.referenceType; var exit = context.enter('imageReference'); var subexit = context.enter('label'); var alt = safe_1(context, node.alt, {before: '[', after: ']'}); var value = '![' + alt + ']'; var reference; var stack; subexit(); // Hide the fact that we’re in phrasing, because escapes don’t work. stack = context.stack; context.stack = []; subexit = context.enter('reference'); reference = safe_1(context, association_1(node), {before: '[', after: ']'}); subexit(); context.stack = stack; exit(); if (type === 'full' || !alt || alt !== reference) { value += '[' + reference + ']'; } else if (type !== 'shortcut') { value += '[]'; } return value } function imageReferencePeek() { return '!' } var inlineCode_1 = inlineCode; inlineCode.peek = inlineCodePeek; function inlineCode(node) { var value = node.value || ''; var sequence = '`'; var pad = ''; // If there is a single grave accent on its own in the code, use a fence of // two. // If there are two in a row, use one. while (new RegExp('(^|[^`])' + sequence + '([^`]|$)').test(value)) { sequence += '`'; } // If this is not just spaces or eols (tabs don’t count), and either the // first or last character are a space, eol, or tick, then pad with spaces. if ( /[^ \r\n]/.test(value) && (/[ \r\n`]/.test(value.charAt(0)) || /[ \r\n`]/.test(value.charAt(value.length - 1))) ) { pad = ' '; } return sequence + pad + value + pad + sequence } function inlineCodePeek() { return '`' } var formatLinkAsAutolink_1 = formatLinkAsAutolink; function formatLinkAsAutolink(node) { var raw = mdastUtilToString(node); return ( // If there’s a url… node.url && // And there’s a no title… !node.title && // And if the url is the same as the content… (raw === node.url || 'mailto:' + raw === node.url) && // And that starts w/ a protocol… /^[a-z][a-z+.-]+:/i.test(node.url) && // And that doesn’t contain ASCII control codes (character escapes and // references don’t work) or angle brackets… !/[\0- <>\u007F]/.test(node.url) ) } var link_1 = link$2; link$2.peek = linkPeek; function link$2(node, _, context) { var quote = checkQuote_1(context); var suffix = quote === '"' ? 'Quote' : 'Apostrophe'; var exit; var subexit; var value; var stack; if (formatLinkAsAutolink_1(node)) { // Hide the fact that we’re in phrasing, because escapes don’t work. stack = context.stack; context.stack = []; exit = context.enter('autolink'); value = '<' + containerPhrasing(node, context, {before: '<', after: '>'}) + '>'; exit(); context.stack = stack; return value } exit = context.enter('link'); subexit = context.enter('label'); value = '[' + containerPhrasing(node, context, {before: '[', after: ']'}) + ']('; subexit(); if ( // If there’s no url but there is a title… (!node.url && node.title) || // Or if there’s markdown whitespace or an eol, enclose. /[ \t\r\n]/.test(node.url) ) { subexit = context.enter('destinationLiteral'); value += '<' + safe_1(context, node.url, {before: '<', after: '>'}) + '>'; } else { // No whitespace, raw is prettier. subexit = context.enter('destinationRaw'); value += safe_1(context, node.url, { before: '(', after: node.title ? ' ' : ')' }); } subexit(); if (node.title) { subexit = context.enter('title' + suffix); value += ' ' + quote + safe_1(context, node.title, {before: quote, after: quote}) + quote; subexit(); } value += ')'; exit(); return value } function linkPeek(node) { return formatLinkAsAutolink_1(node) ? '<' : '[' } var linkReference_1 = linkReference; linkReference.peek = linkReferencePeek; function linkReference(node, _, context) { var type = node.referenceType; var exit = context.enter('linkReference'); var subexit = context.enter('label'); var text = containerPhrasing(node, context, {before: '[', after: ']'}); var value = '[' + text + ']'; var reference; var stack; subexit(); // Hide the fact that we’re in phrasing, because escapes don’t work. stack = context.stack; context.stack = []; subexit = context.enter('reference'); reference = safe_1(context, association_1(node), {before: '[', after: ']'}); subexit(); context.stack = stack; exit(); if (type === 'full' || !text || text !== reference) { value += '[' + reference + ']'; } else if (type !== 'shortcut') { value += '[]'; } return value } function linkReferencePeek() { return '[' } var list_1$1 = list$1; function list$1(node, _, context) { var exit = context.enter('list'); var value = containerFlow(node, context); exit(); return value } var checkBullet_1 = checkBullet; function checkBullet(context) { var marker = context.options.bullet || '*'; if (marker !== '*' && marker !== '+' && marker !== '-') { throw new Error( 'Cannot serialize items with `' + marker + '` for `options.bullet`, expected `*`, `+`, or `-`' ) } return marker } var checkListItemIndent_1 = checkListItemIndent; function checkListItemIndent(context) { var style = context.options.listItemIndent || 'tab'; if (style === 1 || style === '1') { return 'one' } if (style !== 'tab' && style !== 'one' && style !== 'mixed') { throw new Error( 'Cannot serialize items with `' + style + '` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`' ) } return style } var listItem_1 = listItem; function listItem(node, parent, context) { var bullet = checkBullet_1(context); var listItemIndent = checkListItemIndent_1(context); var size; var value; var exit; if (parent && parent.ordered) { bullet = (parent.start > -1 ? parent.start : 1) + (context.options.incrementListMarker === false ? 0 : parent.children.indexOf(node)) + '.'; } size = bullet.length + 1; if ( listItemIndent === 'tab' || (listItemIndent === 'mixed' && ((parent && parent.spread) || node.spread)) ) { size = Math.ceil(size / 4) * 4; } exit = context.enter('listItem'); value = indentLines_1(containerFlow(node, context), map); exit(); return value function map(line, index, blank) { if (index) { return (blank ? '' : repeatString(' ', size)) + line } return (blank ? bullet : bullet + repeatString(' ', size - bullet.length)) + line } } var paragraph_1 = paragraph; function paragraph(node, _, context) { var exit = context.enter('paragraph'); var subexit = context.enter('phrasing'); var value = containerPhrasing(node, context, {before: '\n', after: '\n'}); subexit(); exit(); return value } var root_1 = root$1; function root$1(node, _, context) { return containerFlow(node, context) } var checkStrong_1 = checkStrong; function checkStrong(context) { var marker = context.options.strong || '*'; if (marker !== '*' && marker !== '_') { throw new Error( 'Cannot serialize strong with `' + marker + '` for `options.strong`, expected `*`, or `_`' ) } return marker } var strong_1 = strong; strong.peek = strongPeek; // To do: there are cases where emphasis cannot “form” depending on the // previous or next character of sequences. // There’s no way around that though, except for injecting zero-width stuff. // Do we need to safeguard against that? function strong(node, _, context) { var marker = checkStrong_1(context); var exit = context.enter('strong'); var value = containerPhrasing(node, context, {before: marker, after: marker}); exit(); return marker + marker + value + marker + marker } function strongPeek(node, _, context) { return context.options.strong || '*' } var text_1$1 = text$2; function text$2(node, parent, context, safeOptions) { return safe_1(context, node.value, safeOptions) } var checkRuleRepeat = checkRule; function checkRule(context) { var repetition = context.options.ruleRepetition || 3; if (repetition < 3) { throw new Error( 'Cannot serialize rules with repetition `' + repetition + '` for `options.ruleRepetition`, expected `3` or more' ) } return repetition } var checkRule_1 = checkRule$1; function checkRule$1(context) { var marker = context.options.rule || '*'; if (marker !== '*' && marker !== '-' && marker !== '_') { throw new Error( 'Cannot serialize rules with `' + marker + '` for `options.rule`, expected `*`, `-`, or `_`' ) } return marker } var thematicBreak_1 = thematicBreak$1; function thematicBreak$1(node, parent, context) { var value = repeatString( checkRule_1(context) + (context.options.ruleSpaces ? ' ' : ''), checkRuleRepeat(context) ); return context.options.ruleSpaces ? value.slice(0, -1) : value } var blockquote$1 = blockquote_1; var _break$1 = _break; var code$1 = code_1; var definition$2 = definition_1; var emphasis$1 = emphasis_1; var hardBreak$1 = _break; var heading$1 = heading_1; var html$1 = html_1; var image$2 = image_1; var imageReference$1 = imageReference_1; var inlineCode$1 = inlineCode_1; var link$3 = link_1; var linkReference$1 = linkReference_1; var list$2 = list_1$1; var listItem$1 = listItem_1; var paragraph$1 = paragraph_1; var root$2 = root_1; var strong$1 = strong_1; var text$3 = text_1$1; var thematicBreak$2 = thematicBreak_1; var handle = { blockquote: blockquote$1, break: _break$1, code: code$1, definition: definition$2, emphasis: emphasis$1, hardBreak: hardBreak$1, heading: heading$1, html: html$1, image: image$2, imageReference: imageReference$1, inlineCode: inlineCode$1, link: link$3, linkReference: linkReference$1, list: list$2, listItem: listItem$1, paragraph: paragraph$1, root: root$2, strong: strong$1, text: text$3, thematicBreak: thematicBreak$2 }; var unsafe = [ { character: '\t', inConstruct: ['codeFencedLangGraveAccent', 'codeFencedLangTilde'] }, { character: '\r', inConstruct: [ 'codeFencedLangGraveAccent', 'codeFencedLangTilde', 'codeFencedMetaGraveAccent', 'codeFencedMetaTilde', 'destinationLiteral', 'headingAtx' ] }, { character: '\n', inConstruct: [ 'codeFencedLangGraveAccent', 'codeFencedLangTilde', 'codeFencedMetaGraveAccent', 'codeFencedMetaTilde', 'destinationLiteral', 'headingAtx' ] }, { character: ' ', inConstruct: ['codeFencedLangGraveAccent', 'codeFencedLangTilde'] }, // An exclamation mark can start an image, if it is followed by a link or // a link reference. {character: '!', after: '\\[', inConstruct: 'phrasing'}, // A quote can break out of a title. {character: '"', inConstruct: 'titleQuote'}, // A number sign could start an ATX heading if it starts a line. {atBreak: true, character: '#'}, // Dollar sign and percentage are not used in markdown. // An ampersand could start a character reference. {character: '&', after: '[#A-Za-z]', inConstruct: 'phrasing'}, // An apostrophe can break out of a title. {character: "'", inConstruct: 'titleApostrophe'}, // A left paren could break out of a destination raw. {character: '(', inConstruct: 'destinationRaw'}, {before: '\\]', character: '(', inConstruct: 'phrasing'}, // A right paren could start a list item or break out of a destination // raw. {atBreak: true, before: '\\d+', character: ')'}, {character: ')', inConstruct: 'destinationRaw'}, // An asterisk can start thematic breaks, list items, emphasis, strong. {atBreak: true, character: '*'}, {character: '*', inConstruct: 'phrasing'}, // A plus sign could start a list item. {atBreak: true, character: '+'}, // A dash can start thematic breaks, list items, and setext heading // underlines. {atBreak: true, character: '-'}, // A dot could start a list item. {atBreak: true, before: '\\d+', character: '.', after: '(?:[ \t\r\n]|$)'}, // Slash, colon, and semicolon are not used in markdown for constructs. // A less than can start html (flow or text) or an autolink. // HTML could start with an exclamation mark (declaration, cdata, comment), // slash (closing tag), question mark (instruction), or a letter (tag). // An autolink also starts with a letter. // Finally, it could break out of a destination literal. {atBreak: true, character: '<', after: '[!/?A-Za-z]'}, {character: '<', after: '[!/?A-Za-z]', inConstruct: 'phrasing'}, {character: '<', inConstruct: 'destinationLiteral'}, // An equals to can start setext heading underlines. {atBreak: true, character: '='}, // A greater than can start block quotes and it can break out of a // destination literal. {atBreak: true, character: '>'}, {character: '>', inConstruct: 'destinationLiteral'}, // Question mark and at sign are not used in markdown for constructs. // A left bracket can start definitions, references, labels, {atBreak: true, character: '['}, { character: '[', inConstruct: ['phrasing', 'label', 'reference'] }, // A backslash can start an escape (when followed by punctuation) or a // hard break (when followed by an eol). {character: '\\', after: '[!-/:-@[-`{-~]'}, {character: '\\', after: '[\\r\\n]', inConstruct: 'phrasing'}, // A right bracket can exit labels. { character: ']', inConstruct: ['label', 'reference'] }, // Caret is not used in markdown for constructs. // An underscore can start emphasis, strong, or a thematic break. {atBreak: true, character: '_'}, {before: '[^A-Za-z]', character: '_', inConstruct: 'phrasing'}, {character: '_', after: '[^A-Za-z]', inConstruct: 'phrasing'}, // A grave accent can start code (fenced or text), or it can break out of // a grave accent code fence. {atBreak: true, character: '`'}, { character: '`', inConstruct: [ 'codeFencedLangGraveAccent', 'codeFencedMetaGraveAccent', 'phrasing' ] }, // Left brace, vertical bar, right brace are not used in markdown for // constructs. // A tilde can start code (fenced). {atBreak: true, character: '~'} ]; var join$2 = [joinDefaults]; function joinDefaults(left, right, parent, context) { if ( // Two lists with the same marker. (right.type === 'list' && right.type === left.type && Boolean(left.ordered) === Boolean(right.ordered)) || // Indented code after list or another indented code. (right.type === 'code' && formatCodeAsIndented_1(right, context) && (left.type === 'list' || (left.type === right.type && formatCodeAsIndented_1(left, context)))) ) { return false } // Join children of a list or an item. // In which case, `parent` has a `spread` field. if (typeof parent.spread === 'boolean') { if ( left.type === 'paragraph' && // Two paragraphs. (left.type === right.type || right.type === 'definition' || // Paragraph followed by a setext heading. (right.type === 'heading' && formatHeadingAsSetext_1(right, context))) ) { return } return parent.spread ? 1 : 0 } } var lib$7 = toMarkdown; function toMarkdown(tree, options) { var settings = options || {}; var extensions = configure$3(settings); var stack = []; var handle = zwitch('type', { invalid: invalid, unknown: unknown, handlers: extensions.handlers }); var context = { handle: handle, stack: stack, enter: enter, options: settings, unsafePatterns: extensions.unsafe, join: extensions.join }; var result = handle(tree, null, context, {before: '\n', after: '\n'}); if ( result && result.charCodeAt(result.length - 1) !== 10 && result.charCodeAt(result.length - 1) !== 13 ) { result += '\n'; } return result function enter(name) { stack.push(name); return exit function exit() { stack.pop(); } } } function invalid(value) { throw new Error('Cannot handle value `' + value + '`, expected node') } function unknown(node) { throw new Error('Cannot handle unknown node `' + node.type + '`') } function configure$3(settings) { var extensions = [ {unsafe: settings.unsafe, handlers: settings.handlers, join: settings.join} ].concat(settings.extensions || []); var unsafe$1 = unsafe; var join = join$2; var handlers = Object.assign({}, handle); var index = -1; if (settings.tightDefinitions) { join = [joinDefinition].concat(join); } while (++index < extensions.length) { unsafe$1 = unsafe$1.concat(extensions[index].unsafe || []); join = join.concat(extensions[index].join || []); Object.assign(handlers, extensions[index].handlers || {}); } return {unsafe: unsafe$1, join: join, handlers: handlers} } function joinDefinition(left, right) { // No blank line between adjacent definitions. if (left.type === 'definition' && left.type === right.type) { return 0 } } var mdastUtilToMarkdown = lib$7; var remarkStringify = stringify$6; function stringify$6(options) { var self = this; this.Compiler = compile; function compile(tree) { return mdastUtilToMarkdown( tree, Object.assign({}, self.data('settings'), options, { // Note: this option is not in the readme. // The goal is for it to be set by plugins on `data` instead of being // passed by users. extensions: self.data('toMarkdownExtensions') || [] }) ) } } var remark = unified_1().use(remarkParse).use(remarkStringify).freeze(); const name = "remark"; const version$1 = "13.0.0"; const description = "Markdown processor powered by plugins part of the unified collective"; const license = "MIT"; const keywords = [ "unified", "remark", "markdown", "mdast", "abstract", "syntax", "tree", "ast", "parse", "stringify", "serialize", "compile", "process" ]; const homepage = "https://remark.js.org"; const repository = "https://github.com/remarkjs/remark/tree/main/packages/remark"; const bugs = "https://github.com/remarkjs/remark/issues"; const funding = { type: "opencollective", url: "https://opencollective.com/unified" }; const author = "Titus Wormer (https://wooorm.com)"; const contributors = [ "Titus Wormer (https://wooorm.com)" ]; const files = [ "index.js", "types/index.d.ts" ]; const types = "types/index.d.ts"; const dependencies = { "remark-parse": "^9.0.0", "remark-stringify": "^9.0.0", unified: "^9.1.0" }; const scripts = { test: "tape test.js" }; const xo = false; var _package = { name: name, version: version$1, description: description, license: license, keywords: keywords, homepage: homepage, repository: repository, bugs: bugs, funding: funding, author: author, contributors: contributors, files: files, types: types, dependencies: dependencies, scripts: scripts, xo: xo }; var _package$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name, version: version$1, description: description, license: license, keywords: keywords, homepage: homepage, repository: repository, bugs: bugs, funding: funding, author: author, contributors: contributors, files: files, types: types, dependencies: dependencies, scripts: scripts, xo: xo, 'default': _package }); const name$1 = "node-lint-md-cli-rollup"; const description$1 = "remark packaged for Node.js Markdown linting"; const version$2 = "2.0.2"; const devDependencies = { "@rollup/plugin-commonjs": "^11.0.1", "@rollup/plugin-json": "^4.0.1", "@rollup/plugin-node-resolve": "^7.0.0", rollup: "^2.32.1", shx: "^0.3.3" }; const dependencies$1 = { "markdown-extensions": "^1.1.1", remark: "^13.0.0", "remark-gfm": "^1.0.0", "remark-lint": "^7.0.0", "remark-preset-lint-node": "^2.0.0", "unified-args": "^8.0.0" }; const main = "dist/index.js"; const scripts$1 = { build: "npx rollup -c", "build-node": "npm run build && npx shx cp dist/index.js ../lint-md.js" }; var _package$2 = { name: name$1, description: description$1, version: version$2, devDependencies: devDependencies, dependencies: dependencies$1, main: main, scripts: scripts$1 }; var _package$3 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$1, description: description$1, version: version$2, devDependencies: devDependencies, dependencies: dependencies$1, main: main, scripts: scripts$1, 'default': _package$2 }); var vfileLocation = factory$2; function factory$2(file) { var contents = indices(String(file)); var toPoint = offsetToPointFactory(contents); return { toPoint: toPoint, toPosition: toPoint, toOffset: pointToOffsetFactory(contents) } } // Factory to get the line and column-based `point` for `offset` in the bound // indices. function offsetToPointFactory(indices) { return offsetToPoint // Get the line and column-based `point` for `offset` in the bound indices. function offsetToPoint(offset) { var index = -1; var length = indices.length; if (offset < 0) { return {} } while (++index < length) { if (indices[index] > offset) { return { line: index + 1, column: offset - (indices[index - 1] || 0) + 1, offset: offset } } } return {} } } // Factory to get the `offset` for a line and column-based `point` in the // bound indices. function pointToOffsetFactory(indices) { return pointToOffset // Get the `offset` for a line and column-based `point` in the bound // indices. function pointToOffset(point) { var line = point && point.line; var column = point && point.column; if (!isNaN(line) && !isNaN(column) && line - 1 in indices) { return (indices[line - 2] || 0) + column - 1 || 0 } return -1 } } // Get indices of line-breaks in `value`. function indices(value) { var result = []; var index = value.indexOf('\n'); while (index !== -1) { result.push(index + 1); index = value.indexOf('\n', index + 1); } result.push(value.length + 1); return result } var convert_1 = convert$3; function convert$3(test) { if (typeof test === 'string') { return typeFactory(test) } if (test === null || test === undefined) { return ok$1 } if (typeof test === 'object') { return ('length' in test ? anyFactory : matchesFactory)(test) } if (typeof test === 'function') { return test } throw new Error('Expected function, string, or object as test') } function convertAll(tests) { var results = []; var length = tests.length; var index = -1; while (++index < length) { results[index] = convert$3(tests[index]); } return results } // Utility assert each property in `test` is represented in `node`, and each // values are strictly equal. function matchesFactory(test) { return matches function matches(node) { var key; for (key in test) { if (node[key] !== test[key]) { return false } } return true } } function anyFactory(tests) { var checks = convertAll(tests); var length = checks.length; return matches function matches() { var index = -1; while (++index < length) { if (checks[index].apply(this, arguments)) { return true } } return false } } // Utility to convert a string into a function which checks a given node’s type // for said string. function typeFactory(test) { return type function type(node) { return Boolean(node && node.type === test) } } // Utility to return true. function ok$1() { return true } var color_1 = color$1; function color$1(d) { return '\u001B[33m' + d + '\u001B[39m' } var unistUtilVisitParents = visitParents; var CONTINUE = true; var SKIP = 'skip'; var EXIT = false; visitParents.CONTINUE = CONTINUE; visitParents.SKIP = SKIP; visitParents.EXIT = EXIT; function visitParents(tree, test, visitor, reverse) { var is; if (func(test) && !func(visitor)) { reverse = visitor; visitor = test; test = null; } is = convert_1(test); one(tree, null, [])(); function one(child, index, parents) { var value = object(child) ? child : {}; var name; if (string$2(value.type)) { name = string$2(value.tagName) ? value.tagName : string$2(value.name) ? value.name : undefined; node.displayName = 'node (' + color_1(value.type + (name ? '<' + name + '>' : '')) + ')'; } return node function node() { var result = []; var subresult; if (!test || is(child, index, parents[parents.length - 1] || null)) { result = toResult(visitor(child, parents)); if (result[0] === EXIT) { return result } } if (!child.children || result[0] === SKIP) { return result } subresult = toResult(children(child.children, parents.concat(child))); return subresult[0] === EXIT ? subresult : result } } // Visit children in `parent`. function children(children, parents) { var min = -1; var step = reverse ? -1 : 1; var index = (reverse ? children.length : min) + step; var child; var result; while (index > min && index < children.length) { child = children[index]; result = one(child, index, parents)(); if (result[0] === EXIT) { return result } index = typeof result[1] === 'number' ? result[1] : index + step; } } } function toResult(value) { if (object(value) && 'length' in value) { return value } if (typeof value === 'number') { return [CONTINUE, value] } return [value] } function func(d) { return typeof d === 'function' } function string$2(d) { return typeof d === 'string' } function object(d) { return typeof d === 'object' && d !== null } var unistUtilVisit = visit; var CONTINUE$1 = unistUtilVisitParents.CONTINUE; var SKIP$1 = unistUtilVisitParents.SKIP; var EXIT$1 = unistUtilVisitParents.EXIT; visit.CONTINUE = CONTINUE$1; visit.SKIP = SKIP$1; visit.EXIT = EXIT$1; function visit(tree, test, visitor, reverse) { if (typeof test === 'function' && typeof visitor !== 'function') { reverse = visitor; visitor = test; test = null; } unistUtilVisitParents(tree, test, overload, reverse); function overload(node, parents) { var parent = parents[parents.length - 1]; var index = parent ? parent.children.indexOf(node) : null; return visitor(node, index, parent) } } var unifiedMessageControl = messageControl; function messageControl(options) { var settings = options || {}; var name = settings.name; var marker = settings.marker; var test = settings.test; var sources = settings.source; var known = settings.known; var reset = settings.reset; var enable = settings.enable || []; var disable = settings.disable || []; if (!name) { throw new Error('Expected `name` in `options`, got `' + name + '`') } if (!marker) { throw new Error('Expected `marker` in `options`, got `' + marker + '`') } if (!sources) { sources = [name]; } else if (typeof sources === 'string') { sources = [sources]; } return transformer function transformer(tree, file) { var toOffset = vfileLocation(file).toOffset; var initial = !reset; var gaps = detectGaps(tree, file); var scope = {}; var globals = []; unistUtilVisit(tree, test, visitor); file.messages = file.messages.filter(filter); function visitor(node, position, parent) { var mark = marker(node); var ruleIds; var ruleId; var verb; var index; var length; var next; var pos; var tail; if (!mark || mark.name !== name) { return } ruleIds = mark.attributes.split(/\s/g); verb = ruleIds.shift(); next = parent.children[position + 1]; pos = mark.node.position && mark.node.position.start; tail = next && next.position && next.position.end; if (verb !== 'enable' && verb !== 'disable' && verb !== 'ignore') { file.fail( 'Unknown keyword `' + verb + '`: expected ' + "`'enable'`, `'disable'`, or `'ignore'`", mark.node ); } length = ruleIds.length; index = -1; // Apply to all rules. if (length === 0) { if (verb === 'ignore') { toggle(pos, false); toggle(tail, true); } else { toggle(pos, verb === 'enable'); reset = verb !== 'enable'; } } else { while (++index < length) { ruleId = ruleIds[index]; if (isKnown(ruleId, verb, mark.node)) { toggle(pos, verb === 'enable', ruleId); if (verb === 'ignore') { toggle(tail, true, ruleId); } } } } } function filter(message) { var gapIndex = gaps.length; var ruleId = message.ruleId; var ranges = scope[ruleId]; var pos; // Keep messages from a different source. if (!message.source || sources.indexOf(message.source) === -1) { return true } // We only ignore messages if they‘re disabled, *not* when they’re not in // the document. if (!message.line) { message.line = 1; } if (!message.column) { message.column = 1; } // Check whether the warning is inside a gap. pos = toOffset(message); while (gapIndex--) { if (gaps[gapIndex].start <= pos && gaps[gapIndex].end > pos) { return false } } // Check whether allowed by specific and global states. return check(message, ranges, ruleId) && check(message, globals) } // Helper to check (and possibly warn) if a `ruleId` is unknown. function isKnown(ruleId, verb, pos) { var result = known ? known.indexOf(ruleId) !== -1 : true; if (!result) { file.message( 'Unknown rule: cannot ' + verb + " `'" + ruleId + "'`", pos ); } return result } // Get the latest state of a rule. // When without `ruleId`, gets global state. function getState(ruleId) { var ranges = ruleId ? scope[ruleId] : globals; if (ranges && ranges.length !== 0) { return ranges[ranges.length - 1].state } if (!ruleId) { return !reset } if (reset) { return enable.indexOf(ruleId) !== -1 } return disable.indexOf(ruleId) === -1 } // Handle a rule. function toggle(pos, state, ruleId) { var markers = ruleId ? scope[ruleId] : globals; var previousState; if (!markers) { markers = []; scope[ruleId] = markers; } previousState = getState(ruleId); if (state !== previousState) { markers.push({state: state, position: pos}); } // Toggle all known rules. if (!ruleId) { for (ruleId in scope) { toggle(pos, state, ruleId); } } } // Check all `ranges` for `message`. function check(message, ranges, id) { // Check the state at the message’s position. var index = ranges && ranges.length; var length = -1; var range; while (--index > length) { range = ranges[index]; /* istanbul ignore if - Generated marker. */ if (!range.position || !range.position.line || !range.position.column) { continue } if ( range.position.line < message.line || (range.position.line === message.line && range.position.column <= message.column) ) { return range.state === true } } // The first marker ocurred after the first message, so we check the // initial state. if (!id) { return initial || reset } return reset ? enable.indexOf(id) !== -1 : disable.indexOf(id) === -1 } } } // Detect gaps in `tree`. function detectGaps(tree, file) { var lastNode = tree.children[tree.children.length - 1]; var offset = 0; var isGap = false; var gaps = []; // Find all gaps. unistUtilVisit(tree, one); // Get the end of the document. // This detects if the last node was the last node. // If not, there’s an extra gap between the last node and the end of the // document. if ( lastNode && lastNode.position && lastNode.position.end && offset === lastNode.position.end.offset && trim(file.toString().slice(offset)) !== '' ) { update(); update( tree && tree.position && tree.position.end && tree.position.end.offset - 1 ); } return gaps function one(node) { var pos = node.position; update(pos && pos.start && pos.start.offset); if (!node.children) { update(pos && pos.end && pos.end.offset); } } // Detect a new position. function update(latest) { if (latest === null || latest === undefined) { isGap = true; return } if (offset >= latest) { return } if (isGap) { gaps.push({start: offset, end: latest}); isGap = false; } offset = latest; } } function trim(value) { return value.replace(/^\s*|\s*$/g, '') } var mdastCommentMarker = marker$1; var whiteSpaceExpression = /\s+/g; var parametersExpression = /\s+([-a-z0-9_]+)(?:=(?:"((?:\\[\s\S]|[^"])+)"|'((?:\\[\s\S]|[^'])+)'|((?:\\[\s\S]|[^"'\s])+)))?/gi; var commentExpression = /\s*([a-zA-Z0-9-]+)(\s+([\s\S]*))?\s*/; var markerExpression = new RegExp( '(\\s*\\s*)' ); // Parse a comment marker. function marker$1(node) { var type; var value; var match; var params; if (!node) { return null } type = node.type; if (type !== 'html' && type !== 'comment') { return null } value = node.value; match = value.match(type === 'comment' ? commentExpression : markerExpression); if (!match || match[0].length !== value.length) { return null } match = match.slice(node.type === 'comment' ? 1 : 2); params = parameters(match[1] || ''); if (!params) { return null } return { name: match[0], attributes: match[2] || '', parameters: params, node: node } } // Parse `value` into an object. function parameters(value) { var attributes = {}; var rest = value.replace(parametersExpression, replacer); return rest.replace(whiteSpaceExpression, '') ? null : attributes // eslint-disable-next-line max-params function replacer($0, $1, $2, $3, $4) { var result = $2 || $3 || $4 || ''; if (result === 'true' || result === '') { result = true; } else if (result === 'false') { result = false; } else if (!isNaN(result)) { result = Number(result); } attributes[$1] = result; return '' } } var remarkMessageControl = messageControl$1; var test = [ 'html', // Comments are `html` nodes in mdast. 'comment' // In MDX, comments have their own node. ]; function messageControl$1(options) { return unifiedMessageControl(Object.assign({marker: mdastCommentMarker, test: test}, options)) } var remarkLint = lint; // `remark-lint`. // This adds support for ignoring stuff from messages (``). // All rules are in their own packages and presets. function lint() { this.use(lintMessageControl); } function lintMessageControl() { return remarkMessageControl({name: 'lint', source: 'remark-lint'}) } var remarkLint$1 = lint$1; // `remark-lint`. // This adds support for ignoring stuff from messages (``). // All rules are in their own packages and presets. function lint$1() { this.use(lintMessageControl$1); } function lintMessageControl$1() { return remarkMessageControl({name: 'lint', source: 'remark-lint'}) } /** * An Array.prototype.slice.call(arguments) alternative * * @param {Object} args something with a length * @param {Number} slice * @param {Number} sliceEnd * @api public */ var sliced = function (args, slice, sliceEnd) { var ret = []; var len = args.length; if (0 === len) return ret; var start = slice < 0 ? Math.max(0, slice + len) : slice || 0; if (sliceEnd !== undefined) { len = sliceEnd < 0 ? sliceEnd + len : sliceEnd; } while (len-- > start) { ret[len - start] = args[len]; } return ret; }; /** * slice() reference. */ var slice$4 = Array.prototype.slice; /** * Expose `co`. */ var co_1 = co; /** * Wrap the given generator `fn` and * return a thunk. * * @param {Function} fn * @return {Function} * @api public */ function co(fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this; // in toThunk() below we invoke co() // with a generator, so optimize for // this case var gen = fn; // we only need to parse the arguments // if gen is a generator function. if (isGenFun) { var args = slice$4.call(arguments), len = args.length; var hasCallback = len && 'function' == typeof args[len - 1]; done = hasCallback ? args.pop() : error; gen = fn.apply(this, args); } else { done = done || error; } next(); // #92 // wrap the callback in a setImmediate // so that any of its errors aren't caught by `co` function exit(err, res) { setImmediate(function(){ done.call(ctx, err, res); }); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) res = slice$4.call(arguments, 1); // error if (err) { try { ret = gen.throw(err); } catch (e) { return exit(e); } } // ok if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } // done if (ret.done) return exit(null, ret.value); // normalize ret.value = toThunk(ret.value, ctx); // run if ('function' == typeof ret.value) { var called = false; try { ret.value.call(ctx, function(){ if (called) return; called = true; next.apply(ctx, arguments); }); } catch (e) { setImmediate(function(){ if (called) return; called = true; next(e); }); } return; } // invalid next(new TypeError('You may only yield a function, promise, generator, array, or object, ' + 'but the following was passed: "' + String(ret.value) + '"')); } } } /** * Convert `obj` into a normalized thunk. * * @param {Mixed} obj * @param {Mixed} ctx * @return {Function} * @api private */ function toThunk(obj, ctx) { if (isGeneratorFunction(obj)) { return co(obj.call(ctx)); } if (isGenerator(obj)) { return co(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if ('function' == typeof obj) { return obj; } if (isObject$3(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } /** * Convert an object of yieldables to a thunk. * * @param {Object} obj * @return {Function} * @api private */ function objectToThunk(obj){ var ctx = this; var isArray = Array.isArray(obj); return function(done){ var keys = Object.keys(obj); var pending = keys.length; var results = isArray ? new Array(pending) // predefine the array length : new obj.constructor(); var finished; if (!pending) { setImmediate(function(){ done(null, results); }); return; } // prepopulate object keys to preserve key ordering if (!isArray) { for (var i = 0; i < pending; i++) { results[keys[i]] = undefined; } } for (var i = 0; i < keys.length; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) return; try { fn = toThunk(fn, ctx); if ('function' != typeof fn) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res){ if (finished) return; if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (err) { finished = true; done(err); } } } } /** * Convert `promise` to a thunk. * * @param {Object} promise * @return {Function} * @api private */ function promiseToThunk(promise) { return function(fn){ promise.then(function(res) { fn(null, res); }, fn); } } /** * Check if `obj` is a promise. * * @param {Object} obj * @return {Boolean} * @api private */ function isPromise(obj) { return obj && 'function' == typeof obj.then; } /** * Check if `obj` is a generator. * * @param {Mixed} obj * @return {Boolean} * @api private */ function isGenerator(obj) { return obj && 'function' == typeof obj.next && 'function' == typeof obj.throw; } /** * Check if `obj` is a generator function. * * @param {Mixed} obj * @return {Boolean} * @api private */ function isGeneratorFunction(obj) { return obj && obj.constructor && 'GeneratorFunction' == obj.constructor.name; } /** * Check for plain object. * * @param {Mixed} val * @return {Boolean} * @api private */ function isObject$3(val) { return val && Object == val.constructor; } /** * Throw `err` in a new stack. * * This is used when co() is invoked * without supplying a callback, which * should only be for demonstrational * purposes. * * @param {Error} err * @api private */ function error(err) { if (!err) return; setImmediate(function(){ throw err; }); } /** * Module Dependencies */ var noop$3 = function(){}; /** * Export `wrapped` */ var wrapped_1 = wrapped; /** * Wrap a function to support * sync, async, and gen functions. * * @param {Function} fn * @return {Function} * @api public */ function wrapped(fn) { function wrap() { var args = sliced(arguments); var last = args[args.length - 1]; var ctx = this; // done var done = typeof last == 'function' ? args.pop() : noop$3; // nothing if (!fn) { return done.apply(ctx, [null].concat(args)); } // generator if (generator(fn)) { return co_1(fn).apply(ctx, args.concat(done)); } // async if (fn.length > args.length) { // NOTE: this only handles uncaught synchronous errors try { return fn.apply(ctx, args.concat(done)); } catch (e) { return done(e); } } // sync return sync$5(fn, done).apply(ctx, args); } return wrap; } /** * Wrap a synchronous function execution. * * @param {Function} fn * @param {Function} done * @return {Function} * @api private */ function sync$5(fn, done) { return function () { var ret; try { ret = fn.apply(this, arguments); } catch (err) { return done(err); } if (promise(ret)) { ret.then(function (value) { done(null, value); }, done); } else { ret instanceof Error ? done(ret) : done(null, ret); } } } /** * Is `value` a generator? * * @param {Mixed} value * @return {Boolean} * @api private */ function generator(value) { return value && value.constructor && 'GeneratorFunction' == value.constructor.name; } /** * Is `value` a promise? * * @param {Mixed} value * @return {Boolean} * @api private */ function promise(value) { return value && 'function' == typeof value.then; } var unifiedLintRule = factory$3; function factory$3(id, rule) { var parts = id.split(':'); var source = parts[0]; var ruleId = parts[1]; var fn = wrapped_1(rule); /* istanbul ignore if - possibly useful if externalised later. */ if (!ruleId) { ruleId = source; source = null; } attacher.displayName = id; return attacher function attacher(raw) { var config = coerce(ruleId, raw); var severity = config[0]; var options = config[1]; var fatal = severity === 2; return severity ? transformer : undefined function transformer(tree, file, next) { var index = file.messages.length; fn(tree, file, options, done); function done(err) { var messages = file.messages; var message; // Add the error, if not already properly added. /* istanbul ignore if - only happens for incorrect plugins */ if (err && messages.indexOf(err) === -1) { try { file.fail(err); } catch (_) {} } while (index < messages.length) { message = messages[index]; message.ruleId = ruleId; message.source = source; message.fatal = fatal; index++; } next(); } } } } // Coerce a value to a severity--options tuple. function coerce(name, value) { var def = 1; var result; var level; /* istanbul ignore if - Handled by unified in v6.0.0 */ if (typeof value === 'boolean') { result = [value]; } else if (value == null) { result = [def]; } else if ( typeof value === 'object' && (typeof value[0] === 'number' || typeof value[0] === 'boolean' || typeof value[0] === 'string') ) { result = value.concat(); } else { result = [1, value]; } level = result[0]; if (typeof level === 'boolean') { level = level ? 1 : 0; } else if (typeof level === 'string') { if (level === 'off') { level = 0; } else if (level === 'on' || level === 'warn') { level = 1; } else if (level === 'error') { level = 2; } else { level = 1; result = [level, result]; } } if (level < 0 || level > 2) { throw new Error( 'Incorrect severity `' + level + '` for `' + name + '`, ' + 'expected 0, 1, or 2' ) } result[0] = level; return result } var remarkLintFinalNewline = unifiedLintRule('remark-lint:final-newline', finalNewline); function finalNewline(tree, file) { var contents = String(file); var last = contents.length - 1; if (last > -1 && contents.charAt(last) !== '\n') { file.message('Missing newline character at end of file'); } } var pluralize = createCommonjsModule(function (module, exports) { /* global define */ (function (root, pluralize) { /* istanbul ignore else */ if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') { // Node. module.exports = pluralize(); } else { // Browser global. root.pluralize = pluralize(); } })(commonjsGlobal, function () { // Rule storage - pluralize and singularize need to be run sequentially, // while other rules can be optimized using an object for instant lookups. var pluralRules = []; var singularRules = []; var uncountables = {}; var irregularPlurals = {}; var irregularSingles = {}; /** * Sanitize a pluralization rule to a usable regular expression. * * @param {(RegExp|string)} rule * @return {RegExp} */ function sanitizeRule (rule) { if (typeof rule === 'string') { return new RegExp('^' + rule + '$', 'i'); } return rule; } /** * Pass in a word token to produce a function that can replicate the case on * another word. * * @param {string} word * @param {string} token * @return {Function} */ function restoreCase (word, token) { // Tokens are an exact match. if (word === token) return token; // Lower cased words. E.g. "hello". if (word === word.toLowerCase()) return token.toLowerCase(); // Upper cased words. E.g. "WHISKY". if (word === word.toUpperCase()) return token.toUpperCase(); // Title cased words. E.g. "Title". if (word[0] === word[0].toUpperCase()) { return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase(); } // Lower cased words. E.g. "test". return token.toLowerCase(); } /** * Interpolate a regexp string. * * @param {string} str * @param {Array} args * @return {string} */ function interpolate (str, args) { return str.replace(/\$(\d{1,2})/g, function (match, index) { return args[index] || ''; }); } /** * Replace a word using a rule. * * @param {string} word * @param {Array} rule * @return {string} */ function replace (word, rule) { return word.replace(rule[0], function (match, index) { var result = interpolate(rule[1], arguments); if (match === '') { return restoreCase(word[index - 1], result); } return restoreCase(match, result); }); } /** * Sanitize a word by passing in the word and sanitization rules. * * @param {string} token * @param {string} word * @param {Array} rules * @return {string} */ function sanitizeWord (token, word, rules) { // Empty string or doesn't need fixing. if (!token.length || uncountables.hasOwnProperty(token)) { return word; } var len = rules.length; // Iterate over the sanitization rules and use the first one to match. while (len--) { var rule = rules[len]; if (rule[0].test(word)) return replace(word, rule); } return word; } /** * Replace a word with the updated word. * * @param {Object} replaceMap * @param {Object} keepMap * @param {Array} rules * @return {Function} */ function replaceWord (replaceMap, keepMap, rules) { return function (word) { // Get the correct token and case restoration functions. var token = word.toLowerCase(); // Check against the keep object map. if (keepMap.hasOwnProperty(token)) { return restoreCase(word, token); } // Check against the replacement map for a direct word replacement. if (replaceMap.hasOwnProperty(token)) { return restoreCase(word, replaceMap[token]); } // Run all the rules against the word. return sanitizeWord(token, word, rules); }; } /** * Check if a word is part of the map. */ function checkWord (replaceMap, keepMap, rules, bool) { return function (word) { var token = word.toLowerCase(); if (keepMap.hasOwnProperty(token)) return true; if (replaceMap.hasOwnProperty(token)) return false; return sanitizeWord(token, token, rules) === token; }; } /** * Pluralize or singularize a word based on the passed in count. * * @param {string} word The word to pluralize * @param {number} count How many of the word exist * @param {boolean} inclusive Whether to prefix with the number (e.g. 3 ducks) * @return {string} */ function pluralize (word, count, inclusive) { var pluralized = count === 1 ? pluralize.singular(word) : pluralize.plural(word); return (inclusive ? count + ' ' : '') + pluralized; } /** * Pluralize a word. * * @type {Function} */ pluralize.plural = replaceWord( irregularSingles, irregularPlurals, pluralRules ); /** * Check if a word is plural. * * @type {Function} */ pluralize.isPlural = checkWord( irregularSingles, irregularPlurals, pluralRules ); /** * Singularize a word. * * @type {Function} */ pluralize.singular = replaceWord( irregularPlurals, irregularSingles, singularRules ); /** * Check if a word is singular. * * @type {Function} */ pluralize.isSingular = checkWord( irregularPlurals, irregularSingles, singularRules ); /** * Add a pluralization rule to the collection. * * @param {(string|RegExp)} rule * @param {string} replacement */ pluralize.addPluralRule = function (rule, replacement) { pluralRules.push([sanitizeRule(rule), replacement]); }; /** * Add a singularization rule to the collection. * * @param {(string|RegExp)} rule * @param {string} replacement */ pluralize.addSingularRule = function (rule, replacement) { singularRules.push([sanitizeRule(rule), replacement]); }; /** * Add an uncountable word rule. * * @param {(string|RegExp)} word */ pluralize.addUncountableRule = function (word) { if (typeof word === 'string') { uncountables[word.toLowerCase()] = true; return; } // Set singular and plural references for the word. pluralize.addPluralRule(word, '$0'); pluralize.addSingularRule(word, '$0'); }; /** * Add an irregular word definition. * * @param {string} single * @param {string} plural */ pluralize.addIrregularRule = function (single, plural) { plural = plural.toLowerCase(); single = single.toLowerCase(); irregularSingles[single] = plural; irregularPlurals[plural] = single; }; /** * Irregular rules. */ [ // Pronouns. ['I', 'we'], ['me', 'us'], ['he', 'they'], ['she', 'they'], ['them', 'them'], ['myself', 'ourselves'], ['yourself', 'yourselves'], ['itself', 'themselves'], ['herself', 'themselves'], ['himself', 'themselves'], ['themself', 'themselves'], ['is', 'are'], ['was', 'were'], ['has', 'have'], ['this', 'these'], ['that', 'those'], // Words ending in with a consonant and `o`. ['echo', 'echoes'], ['dingo', 'dingoes'], ['volcano', 'volcanoes'], ['tornado', 'tornadoes'], ['torpedo', 'torpedoes'], // Ends with `us`. ['genus', 'genera'], ['viscus', 'viscera'], // Ends with `ma`. ['stigma', 'stigmata'], ['stoma', 'stomata'], ['dogma', 'dogmata'], ['lemma', 'lemmata'], ['schema', 'schemata'], ['anathema', 'anathemata'], // Other irregular rules. ['ox', 'oxen'], ['axe', 'axes'], ['die', 'dice'], ['yes', 'yeses'], ['foot', 'feet'], ['eave', 'eaves'], ['goose', 'geese'], ['tooth', 'teeth'], ['quiz', 'quizzes'], ['human', 'humans'], ['proof', 'proofs'], ['carve', 'carves'], ['valve', 'valves'], ['looey', 'looies'], ['thief', 'thieves'], ['groove', 'grooves'], ['pickaxe', 'pickaxes'], ['passerby', 'passersby'] ].forEach(function (rule) { return pluralize.addIrregularRule(rule[0], rule[1]); }); /** * Pluralization rules. */ [ [/s?$/i, 's'], [/[^\u0000-\u007F]$/i, '$0'], [/([^aeiou]ese)$/i, '$1'], [/(ax|test)is$/i, '$1es'], [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, '$1es'], [/(e[mn]u)s?$/i, '$1s'], [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, '$1'], [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'], [/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'], [/(seraph|cherub)(?:im)?$/i, '$1im'], [/(her|at|gr)o$/i, '$1oes'], [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'], [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'], [/sis$/i, 'ses'], [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/([^ch][ieo][ln])ey$/i, '$1ies'], [/(x|ch|ss|sh|zz)$/i, '$1es'], [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'], [/\b((?:tit)?m|l)(?:ice|ouse)$/i, '$1ice'], [/(pe)(?:rson|ople)$/i, '$1ople'], [/(child)(?:ren)?$/i, '$1ren'], [/eaux$/i, '$0'], [/m[ae]n$/i, 'men'], ['thou', 'you'] ].forEach(function (rule) { return pluralize.addPluralRule(rule[0], rule[1]); }); /** * Singularization rules. */ [ [/s$/i, ''], [/(ss)$/i, '$1'], [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, '$1fe'], [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'], [/ies$/i, 'y'], [/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, '$1ie'], [/\b(mon|smil)ies$/i, '$1ey'], [/\b((?:tit)?m|l)ice$/i, '$1ouse'], [/(seraph|cherub)im$/i, '$1'], [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, '$1'], [/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, '$1sis'], [/(movie|twelve|abuse|e[mn]u)s$/i, '$1'], [/(test)(?:is|es)$/i, '$1is'], [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'], [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'], [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'], [/(alumn|alg|vertebr)ae$/i, '$1a'], [/(cod|mur|sil|vert|ind)ices$/i, '$1ex'], [/(matr|append)ices$/i, '$1ix'], [/(pe)(rson|ople)$/i, '$1rson'], [/(child)ren$/i, '$1'], [/(eau)x?$/i, '$1'], [/men$/i, 'man'] ].forEach(function (rule) { return pluralize.addSingularRule(rule[0], rule[1]); }); /** * Uncountable rules. */ [ // Singular words with no plurals. 'adulthood', 'advice', 'agenda', 'aid', 'aircraft', 'alcohol', 'ammo', 'analytics', 'anime', 'athletics', 'audio', 'bison', 'blood', 'bream', 'buffalo', 'butter', 'carp', 'cash', 'chassis', 'chess', 'clothing', 'cod', 'commerce', 'cooperation', 'corps', 'debris', 'diabetes', 'digestion', 'elk', 'energy', 'equipment', 'excretion', 'expertise', 'firmware', 'flounder', 'fun', 'gallows', 'garbage', 'graffiti', 'hardware', 'headquarters', 'health', 'herpes', 'highjinks', 'homework', 'housework', 'information', 'jeans', 'justice', 'kudos', 'labour', 'literature', 'machinery', 'mackerel', 'mail', 'media', 'mews', 'moose', 'music', 'mud', 'manga', 'news', 'only', 'personnel', 'pike', 'plankton', 'pliers', 'police', 'pollution', 'premises', 'rain', 'research', 'rice', 'salmon', 'scissors', 'series', 'sewage', 'shambles', 'shrimp', 'software', 'species', 'staff', 'swine', 'tennis', 'traffic', 'transportation', 'trout', 'tuna', 'wealth', 'welfare', 'whiting', 'wildebeest', 'wildlife', 'you', /pok[eé]mon$/i, // Regexes. /[^aeiou]ese$/i, // "chinese", "japanese" /deer$/i, // "deer", "reindeer" /fish$/i, // "fish", "blowfish", "angelfish" /measles$/i, /o[iu]s$/i, // "carnivorous" /pox$/i, // "chickpox", "smallpox" /sheep$/i ].forEach(pluralize.addUncountableRule); return pluralize; }); }); var unistUtilGenerated = generated; function generated(node) { return ( !node || !node.position || !node.position.start || !node.position.start.line || !node.position.start.column || !node.position.end || !node.position.end.line || !node.position.end.column ) } var remarkLintListItemBulletIndent = unifiedLintRule( 'remark-lint:list-item-bullet-indent', listItemBulletIndent ); function listItemBulletIndent(tree, file) { unistUtilVisit(tree, 'list', visitor); function visitor(list, _, grandparent) { list.children.forEach(visitItems); function visitItems(item) { var indent; var reason; if ( grandparent && grandparent.type === 'root' && !unistUtilGenerated(item) && !unistUtilGenerated(grandparent) ) { indent = item.position.start.column - grandparent.position.start.column; if (indent) { reason = 'Incorrect indentation before bullet: remove ' + indent + ' ' + pluralize('space', indent); file.message(reason, item.position.start); } } } } } var start$1 = factory$4('start'); var end = factory$4('end'); var unistUtilPosition = position$1; position$1.start = start$1; position$1.end = end; function position$1(node) { return {start: start$1(node), end: end(node)} } function factory$4(type) { point.displayName = type; return point function point(node) { var point = (node && node.position && node.position[type]) || {}; return { line: point.line || null, column: point.column || null, offset: isNaN(point.offset) ? null : point.offset } } } var remarkLintListItemIndent = unifiedLintRule('remark-lint:list-item-indent', listItemIndent); var start$2 = unistUtilPosition.start; var styles$1 = {'tab-size': true, mixed: true, space: true}; function listItemIndent(tree, file, option) { var contents = String(file); var preferred = typeof option === 'string' ? option : 'tab-size'; if (styles$1[preferred] !== true) { file.fail( 'Incorrect list-item indent style `' + preferred + "`: use either `'tab-size'`, `'space'`, or `'mixed'`" ); } unistUtilVisit(tree, 'list', visitor); function visitor(node) { var spread = node.spread || node.loose; if (!unistUtilGenerated(node)) { node.children.forEach(visitItem); } function visitItem(item) { var head = item.children[0]; var final = start$2(head); var marker; var bulletSize; var style; var diff; var reason; var abs; marker = contents .slice(start$2(item).offset, final.offset) .replace(/\[[x ]?]\s*$/i, ''); bulletSize = marker.replace(/\s+$/, '').length; style = preferred === 'tab-size' || (preferred === 'mixed' && spread) ? Math.ceil(bulletSize / 4) * 4 : bulletSize + 1; if (marker.length !== style) { diff = style - marker.length; abs = Math.abs(diff); reason = 'Incorrect list-item indent: ' + (diff > 0 ? 'add' : 'remove') + ' ' + abs + ' ' + pluralize('space', abs); file.message(reason, final); } } } } var remarkLintNoAutoLinkWithoutProtocol = unifiedLintRule( 'remark-lint:no-auto-link-without-protocol', noAutoLinkWithoutProtocol ); var start$3 = unistUtilPosition.start; var end$1 = unistUtilPosition.end; // Protocol expression. // See: . var protocol = /^[a-z][a-z+.-]+:\/?/i; var reason = 'All automatic links must start with a protocol'; function noAutoLinkWithoutProtocol(tree, file) { unistUtilVisit(tree, 'link', visitor); function visitor(node) { var children; if (!unistUtilGenerated(node)) { children = node.children; if ( start$3(node).column === start$3(children[0]).column - 1 && end$1(node).column === end$1(children[children.length - 1]).column + 1 && !protocol.test(mdastUtilToString(node)) ) { file.message(reason, node); } } } } var remarkLintNoBlockquoteWithoutMarker = unifiedLintRule( 'remark-lint:no-blockquote-without-marker', noBlockquoteWithoutMarker ); var reason$1 = 'Missing marker in block quote'; function noBlockquoteWithoutMarker(tree, file) { var contents = String(file); var location = vfileLocation(file); unistUtilVisit(tree, 'blockquote', visitor); function onquotedchild(node) { var line; var end; var column; var offset; if (node.type === 'paragraph' && !unistUtilGenerated(node)) { line = unistUtilPosition.start(node).line; end = unistUtilPosition.end(node).line; column = unistUtilPosition.start(node).column; // Skip past the first line. while (++line <= end) { offset = location.toOffset({line: line, column: column}); if (/>[\t ]+$/.test(contents.slice(offset - 5, offset))) { continue } // Roughly here. file.message(reason$1, {line: line, column: column - 2}); } } } function visitor(node) { node.children.forEach(onquotedchild); } } var remarkLintNoLiteralUrls = unifiedLintRule('remark-lint:no-literal-urls', noLiteralURLs); var start$4 = unistUtilPosition.start; var end$2 = unistUtilPosition.end; var mailto = 'mailto:'; var reason$2 = 'Don’t use literal URLs without angle brackets'; function noLiteralURLs(tree, file) { unistUtilVisit(tree, 'link', visitor); function visitor(node) { var children = node.children; var value = mdastUtilToString(node); if ( !unistUtilGenerated(node) && start$4(node).column === start$4(children[0]).column && end$2(node).column === end$2(children[children.length - 1]).column && (node.url === mailto + value || node.url === value) ) { file.message(reason$2, node); } } } var remarkLintOrderedListMarkerStyle = unifiedLintRule( 'remark-lint:ordered-list-marker-style', orderedListMarkerStyle ); var start$5 = unistUtilPosition.start; var styles$2 = { ')': true, '.': true, null: true }; function orderedListMarkerStyle(tree, file, option) { var contents = String(file); var preferred = typeof option !== 'string' || option === 'consistent' ? null : option; if (styles$2[preferred] !== true) { file.fail( 'Incorrect ordered list item marker style `' + preferred + "`: use either `'.'` or `')'`" ); } unistUtilVisit(tree, 'list', visitor); function visitor(node) { var children = node.children; var length = node.ordered ? children.length : 0; var index = -1; var marker; var child; while (++index < length) { child = children[index]; if (!unistUtilGenerated(child)) { marker = contents .slice(start$5(child).offset, start$5(child.children[0]).offset) .replace(/\s|\d/g, '') .replace(/\[[x ]?]\s*$/i, ''); if (preferred) { if (marker !== preferred) { file.message('Marker style should be `' + preferred + '`', child); } } else { preferred = marker; } } } } } var remarkLintHardBreakSpaces = unifiedLintRule('remark-lint:hard-break-spaces', hardBreakSpaces); var reason$3 = 'Use two spaces for hard line breaks'; function hardBreakSpaces(tree, file) { var contents = String(file); unistUtilVisit(tree, 'break', visitor); function visitor(node) { var value; if (!unistUtilGenerated(node)) { value = contents .slice(unistUtilPosition.start(node).offset, unistUtilPosition.end(node).offset) .split('\n', 1)[0] .replace(/\r$/, ''); if (value.length > 2) { file.message(reason$3, node); } } } } var remarkLintNoDuplicateDefinitions = unifiedLintRule( 'remark-lint:no-duplicate-definitions', noDuplicateDefinitions ); var reason$4 = 'Do not use definitions with the same identifier'; function noDuplicateDefinitions(tree, file) { var map = {}; unistUtilVisit(tree, ['definition', 'footnoteDefinition'], check); function check(node) { var identifier; var duplicate; if (!unistUtilGenerated(node)) { identifier = node.identifier; duplicate = map[identifier]; if (duplicate && duplicate.type) { file.message( reason$4 + ' (' + unistUtilStringifyPosition(unistUtilPosition.start(duplicate)) + ')', node ); } map[identifier] = node; } } } var mdastUtilHeadingStyle = style; function style(node, relative) { var last = node.children[node.children.length - 1]; var depth = node.depth; var pos = node && node.position && node.position.end; var final = last && last.position && last.position.end; if (!pos) { return null } // This can only occur for `'atx'` and `'atx-closed'` headings. // This might incorrectly match `'atx'` headings with lots of trailing white // space as an `'atx-closed'` heading. if (!last) { if (pos.column - 1 <= depth * 2) { return consolidate(depth, relative) } return 'atx-closed' } if (final.line + 1 === pos.line) { return 'setext' } if (final.column + depth < pos.column) { return 'atx-closed' } return consolidate(depth, relative) } // Get the probable style of an atx-heading, depending on preferred style. function consolidate(depth, relative) { return depth < 3 ? 'atx' : relative === 'atx' || relative === 'setext' ? relative : null } var remarkLintNoHeadingContentIndent = unifiedLintRule( 'remark-lint:no-heading-content-indent', noHeadingContentIndent ); var start$6 = unistUtilPosition.start; var end$3 = unistUtilPosition.end; function noHeadingContentIndent(tree, file) { unistUtilVisit(tree, 'heading', visitor); function visitor(node) { var depth; var children; var type; var head; var final; var diff; var reason; var abs; if (unistUtilGenerated(node)) { return } depth = node.depth; children = node.children; type = mdastUtilHeadingStyle(node, 'atx'); if (type === 'atx' || type === 'atx-closed') { head = start$6(children[0]).column; // Ignore empty headings. if (!head) { return } diff = head - start$6(node).column - 1 - depth; if (diff) { abs = Math.abs(diff); reason = 'Remove ' + abs + ' ' + pluralize('space', abs) + ' before this heading’s content'; file.message(reason, start$6(children[0])); } } // Closed ATX headings always must have a space between their content and // the final hashes, thus, there is no `add x spaces`. if (type === 'atx-closed') { final = end$3(children[children.length - 1]); diff = end$3(node).column - final.column - 1 - depth; if (diff) { reason = 'Remove ' + diff + ' ' + pluralize('space', diff) + ' after this heading’s content'; file.message(reason, final); } } } } var remarkLintNoInlinePadding = unifiedLintRule('remark-lint:no-inline-padding', noInlinePadding); function noInlinePadding(tree, file) { // Note: `emphasis`, `strong`, `delete` (GFM) can’t have padding anymore // since CM. unistUtilVisit(tree, ['link', 'linkReference'], visitor); function visitor(node) { var contents; if (!unistUtilGenerated(node)) { contents = mdastUtilToString(node); if ( contents.charAt(0) === ' ' || contents.charAt(contents.length - 1) === ' ' ) { file.message('Don’t pad `' + node.type + '` with inner spaces', node); } } } } var remarkLintNoShortcutReferenceImage = unifiedLintRule( 'remark-lint:no-shortcut-reference-image', noShortcutReferenceImage ); var reason$5 = 'Use the trailing [] on reference images'; function noShortcutReferenceImage(tree, file) { unistUtilVisit(tree, 'imageReference', visitor); function visitor(node) { if (!unistUtilGenerated(node) && node.referenceType === 'shortcut') { file.message(reason$5, node); } } } var remarkLintNoShortcutReferenceLink = unifiedLintRule( 'remark-lint:no-shortcut-reference-link', noShortcutReferenceLink ); var reason$6 = 'Use the trailing `[]` on reference links'; function noShortcutReferenceLink(tree, file) { unistUtilVisit(tree, 'linkReference', visitor); function visitor(node) { if (!unistUtilGenerated(node) && node.referenceType === 'shortcut') { file.message(reason$6, node); } } } var collapseWhiteSpace = collapse; // `collapse(' \t\nbar \nbaz\t') // ' bar baz '` function collapse(value) { return String(value).replace(/\s+/g, ' ') } var remarkLintNoUndefinedReferences = unifiedLintRule( 'remark-lint:no-undefined-references', noUndefinedReferences ); var reason$7 = 'Found reference to undefined definition'; // The identifier is upcased to avoid naming collisions with fields inherited // from `Object.prototype`. // If `Object.create(null)` was used in place of `{}`, downcasing would work // equally well. function normalize$2(s) { return collapseWhiteSpace(s.toUpperCase()) } function noUndefinedReferences(tree, file, option) { var contents = String(file); var location = vfileLocation(file); var lineEnding = /(\r?\n|\r)[\t ]*(>[\t ]*)*/g; var allow = ((option || {}).allow || []).map(normalize$2); var map = {}; unistUtilVisit(tree, ['definition', 'footnoteDefinition'], mark); unistUtilVisit(tree, ['imageReference', 'linkReference', 'footnoteReference'], find); unistUtilVisit(tree, ['paragraph', 'heading'], findInPhrasing); function mark(node) { if (!unistUtilGenerated(node)) { map[normalize$2(node.identifier)] = true; } } function find(node) { if ( !unistUtilGenerated(node) && !(normalize$2(node.identifier) in map) && allow.indexOf(normalize$2(node.identifier)) === -1 ) { file.message(reason$7, node); } } function findInPhrasing(node) { var ranges = []; unistUtilVisit(node, onchild); ranges.forEach(handleRange); return unistUtilVisit.SKIP function onchild(child) { var start; var end; var source; var lines; var last; var index; var match; var line; var code; var lineIndex; var next; var range; // Ignore the node itself. if (child === node) return // Can’t have links in links, so reset ranges. if (child.type === 'link' || child.type === 'linkReference') { ranges = []; return unistUtilVisit.SKIP } // Enter non-text. if (child.type !== 'text') return start = unistUtilPosition.start(child).offset; end = unistUtilPosition.end(child).offset; // Bail if there’s no positional info. if (!end) return unistUtilVisit.EXIT source = contents.slice(start, end); lines = [[start, '']]; last = 0; lineEnding.lastIndex = 0; match = lineEnding.exec(source); while (match) { index = match.index; lines[lines.length - 1][1] = source.slice(last, index); last = index + match[0].length; lines.push([start + last, '']); match = lineEnding.exec(source); } lines[lines.length - 1][1] = source.slice(last); lineIndex = -1; while (++lineIndex < lines.length) { line = lines[lineIndex][1]; index = 0; while (index < line.length) { code = line.charCodeAt(index); // Skip past escaped brackets. if (code === 92) { next = line.charCodeAt(index + 1); index++; if (next === 91 || next === 93) { index++; } } // Opening bracket. else if (code === 91) { ranges.push([lines[lineIndex][0] + index]); index++; } // Close bracket. else if (code === 93) { // No opening. if (ranges.length === 0) { index++; } else if (line.charCodeAt(index + 1) === 91) { index++; // Collapsed or full. range = ranges.pop(); range.push(lines[lineIndex][0] + index); // This is the end of a reference already. if (range.length === 4) { handleRange(range); range = []; } range.push(lines[lineIndex][0] + index); ranges.push(range); index++; } else { index++; // Shortcut or typical end of a reference. range = ranges.pop(); range.push(lines[lineIndex][0] + index); handleRange(range); } } // Anything else. else { index++; } } } } function handleRange(range) { var offset; if (range.length === 1) return if (range.length === 3) range.length = 2; // No need to warn for just `[]`. if (range.length === 2 && range[0] + 2 === range[1]) return offset = range.length === 4 && range[2] + 2 !== range[3] ? 2 : 0; find({ identifier: contents .slice(range[0 + offset] + 1, range[1 + offset] - 1) .replace(lineEnding, ' '), position: { start: location.toPosition(range[0]), end: location.toPosition(range[range.length - 1]) } }); } } } var remarkLintNoUnusedDefinitions = unifiedLintRule('remark-lint:no-unused-definitions', noUnusedDefinitions); var reason$8 = 'Found unused definition'; function noUnusedDefinitions(tree, file) { var map = {}; var identifier; var entry; unistUtilVisit(tree, ['definition', 'footnoteDefinition'], find); unistUtilVisit(tree, ['imageReference', 'linkReference', 'footnoteReference'], mark); for (identifier in map) { entry = map[identifier]; if (!entry.used) { file.message(reason$8, entry.node); } } function find(node) { if (!unistUtilGenerated(node)) { map[node.identifier.toUpperCase()] = {node: node, used: false}; } } function mark(node) { var info = map[node.identifier.toUpperCase()]; if (!unistUtilGenerated(node) && info) { info.used = true; } } } var plugins$1 = [ remarkLint$1, // Unix compatibility. remarkLintFinalNewline, // Rendering across vendors differs greatly if using other styles. remarkLintListItemBulletIndent, [remarkLintListItemIndent, 'tab-size'], // Differs or unsupported across vendors. remarkLintNoAutoLinkWithoutProtocol, remarkLintNoBlockquoteWithoutMarker, remarkLintNoLiteralUrls, [remarkLintOrderedListMarkerStyle, '.'], // Mistakes. remarkLintHardBreakSpaces, remarkLintNoDuplicateDefinitions, remarkLintNoHeadingContentIndent, remarkLintNoInlinePadding, remarkLintNoShortcutReferenceImage, remarkLintNoShortcutReferenceLink, remarkLintNoUndefinedReferences, remarkLintNoUnusedDefinitions ]; var remarkPresetLintRecommended = { plugins: plugins$1 }; var remarkLintBlockquoteIndentation = unifiedLintRule( 'remark-lint:blockquote-indentation', blockquoteIndentation ); function blockquoteIndentation(tree, file, option) { var preferred = typeof option === 'number' && !isNaN(option) ? option : null; unistUtilVisit(tree, 'blockquote', visitor); function visitor(node) { var abs; var diff; var reason; if (unistUtilGenerated(node) || node.children.length === 0) { return } if (preferred) { diff = preferred - check$3(node); if (diff !== 0) { abs = Math.abs(diff); reason = (diff > 0 ? 'Add' : 'Remove') + ' ' + abs + ' ' + pluralize('space', abs) + ' between block quote and content'; file.message(reason, unistUtilPosition.start(node.children[0])); } } else { preferred = check$3(node); } } } function check$3(node) { var head = node.children[0]; var indentation = unistUtilPosition.start(head).column - unistUtilPosition.start(node).column; var padding = mdastUtilToString(head).match(/^ +/); if (padding) { indentation += padding[0].length; } return indentation } var remarkLintCheckboxCharacterStyle = unifiedLintRule( 'remark-lint:checkbox-character-style', checkboxCharacterStyle ); var start$7 = unistUtilPosition.start; var end$4 = unistUtilPosition.end; var checked = {x: true, X: true}; var unchecked = {' ': true, '\t': true}; var types$1 = {true: 'checked', false: 'unchecked'}; function checkboxCharacterStyle(tree, file, option) { var contents = String(file); var preferred = typeof option === 'object' ? option : {}; if (preferred.unchecked && unchecked[preferred.unchecked] !== true) { file.fail( 'Incorrect unchecked checkbox marker `' + preferred.unchecked + "`: use either `'\\t'`, or `' '`" ); } if (preferred.checked && checked[preferred.checked] !== true) { file.fail( 'Incorrect checked checkbox marker `' + preferred.checked + "`: use either `'x'`, or `'X'`" ); } unistUtilVisit(tree, 'listItem', visitor); function visitor(node) { var type; var point; var value; var style; var reason; // Exit early for items without checkbox. if (typeof node.checked !== 'boolean' || unistUtilGenerated(node)) { return } type = types$1[node.checked]; /* istanbul ignore next - a list item cannot be checked and empty, according * to GFM, but theoretically it makes sense to get the end if that were * possible. */ point = node.children.length === 0 ? end$4(node) : start$7(node.children[0]); // Move back to before `] `. point.offset -= 2; point.column -= 2; // Assume we start with a checkbox, because well, `checked` is set. value = /\[([\t Xx])]/.exec( contents.slice(point.offset - 2, point.offset + 1) ); /* istanbul ignore if - failsafe to make sure we don‘t crash if there * actually isn’t a checkbox. */ if (!value) return style = preferred[type]; if (style) { if (value[1] !== style) { reason = type.charAt(0).toUpperCase() + type.slice(1) + ' checkboxes should use `' + style + '` as a marker'; file.message(reason, point); } } else { preferred[type] = value[1]; } } } var remarkLintCheckboxContentIndent = unifiedLintRule( 'remark-lint:checkbox-content-indent', checkboxContentIndent ); var start$8 = unistUtilPosition.start; var end$5 = unistUtilPosition.end; var reason$9 = 'Checkboxes should be followed by a single character'; function checkboxContentIndent(tree, file) { var contents = String(file); var location = vfileLocation(file); unistUtilVisit(tree, 'listItem', visitor); function visitor(node) { var initial; var final; var value; var point; // Exit early for items without checkbox. if (typeof node.checked !== 'boolean' || unistUtilGenerated(node)) { return } /* istanbul ignore next - a list item cannot be checked and empty, according * to GFM, but theoretically it makes sense to get the end if that were * possible. */ point = node.children.length === 0 ? end$5(node) : start$8(node.children[0]); // Assume we start with a checkbox, because well, `checked` is set. value = /\[([\t xX])]/.exec( contents.slice(point.offset - 4, point.offset + 1) ); /* istanbul ignore if - failsafe to make sure we don‘t crash if there * actually isn’t a checkbox. */ if (!value) return // Move past checkbox. initial = point.offset; final = initial; while (/[\t ]/.test(contents.charAt(final))) final++; if (final - initial > 0) { file.message(reason$9, { start: location.toPosition(initial), end: location.toPosition(final) }); } } } var remarkLintCodeBlockStyle = unifiedLintRule('remark-lint:code-block-style', codeBlockStyle); var start$9 = unistUtilPosition.start; var end$6 = unistUtilPosition.end; var styles$3 = {null: true, fenced: true, indented: true}; function codeBlockStyle(tree, file, option) { var contents = String(file); var preferred = typeof option === 'string' && option !== 'consistent' ? option : null; if (styles$3[preferred] !== true) { file.fail( 'Incorrect code block style `' + preferred + "`: use either `'consistent'`, `'fenced'`, or `'indented'`" ); } unistUtilVisit(tree, 'code', visitor); function visitor(node) { var initial; var final; var current; if (unistUtilGenerated(node)) { return null } initial = start$9(node).offset; final = end$6(node).offset; current = node.lang || /^\s*([~`])\1{2,}/.test(contents.slice(initial, final)) ? 'fenced' : 'indented'; if (preferred) { if (preferred !== current) { file.message('Code blocks should be ' + preferred, node); } } else { preferred = current; } } } var remarkLintDefinitionSpacing = unifiedLintRule('remark-lint:definition-spacing', definitionSpacing); var label = /^\s*\[((?:\\[\s\S]|[^[\]])+)]/; var reason$a = 'Do not use consecutive whitespace in definition labels'; function definitionSpacing(tree, file) { var contents = String(file); unistUtilVisit(tree, ['definition', 'footnoteDefinition'], check); function check(node) { var start = unistUtilPosition.start(node).offset; var end = unistUtilPosition.end(node).offset; if ( !unistUtilGenerated(node) && /[ \t\n]{2,}/.test(contents.slice(start, end).match(label)[1]) ) { file.message(reason$a, node); } } } var remarkLintFencedCodeFlag = unifiedLintRule('remark-lint:fenced-code-flag', fencedCodeFlag); var start$a = unistUtilPosition.start; var end$7 = unistUtilPosition.end; var fence = /^ {0,3}([~`])\1{2,}/; var reasonIncorrect = 'Incorrect code language flag'; var reasonMissing = 'Missing code language flag'; function fencedCodeFlag(tree, file, option) { var contents = String(file); var allowEmpty = false; var allowed = []; var flags = option; if (typeof flags === 'object' && !('length' in flags)) { allowEmpty = Boolean(flags.allowEmpty); flags = flags.flags; } if (typeof flags === 'object' && 'length' in flags) { allowed = String(flags).split(','); } unistUtilVisit(tree, 'code', visitor); function visitor(node) { var value; if (!unistUtilGenerated(node)) { if (node.lang) { if (allowed.length !== 0 && allowed.indexOf(node.lang) === -1) { file.message(reasonIncorrect, node); } } else { value = contents.slice(start$a(node).offset, end$7(node).offset); if (!allowEmpty && fence.test(value)) { file.message(reasonMissing, node); } } } } } var remarkLintFencedCodeMarker = unifiedLintRule('remark-lint:fenced-code-marker', fencedCodeMarker); var markers = { '`': true, '~': true, null: true }; function fencedCodeMarker(tree, file, option) { var contents = String(file); var preferred = typeof option === 'string' && option !== 'consistent' ? option : null; if (markers[preferred] !== true) { file.fail( 'Incorrect fenced code marker `' + preferred + "`: use either `'consistent'`, `` '`' ``, or `'~'`" ); } unistUtilVisit(tree, 'code', visitor); function visitor(node) { var start; var marker; var label; if (!unistUtilGenerated(node)) { start = unistUtilPosition.start(node).offset; marker = contents .slice(start, start + 4) .replace(/^\s+/, '') .charAt(0); // Ignore unfenced code blocks. if (markers[marker] === true) { if (preferred) { if (marker !== preferred) { label = preferred === '~' ? preferred : '` ` `'; file.message( 'Fenced code should use `' + label + '` as a marker', node ); } } else { preferred = marker; } } } } } var remarkLintFileExtension = unifiedLintRule('remark-lint:file-extension', fileExtension); function fileExtension(tree, file, option) { var ext = file.extname; var preferred = typeof option === 'string' ? option : 'md'; if (ext && ext.slice(1) !== preferred) { file.message('Incorrect extension: use `' + preferred + '`'); } } var remarkLintFinalDefinition = unifiedLintRule('remark-lint:final-definition', finalDefinition); var start$b = unistUtilPosition.start; function finalDefinition(tree, file) { var last = null; unistUtilVisit(tree, visitor, true); function visitor(node) { var line = start$b(node).line; // Ignore generated and HTML comment nodes. if (node.type === 'root' || unistUtilGenerated(node) || (node.type === 'html' && /^\s*".length)); validateMeta(node, file, meta); } catch (e) { file.message(e, node); } }); } var remarkLintNodejsYamlComments = unifiedLintRule("remark-lint:nodejs-yaml-comments", validateYAMLComments); var escapeStringRegexp$1 = string => { if (typeof string !== 'string') { throw new TypeError('Expected a string'); } // Escape characters with special meaning either inside or outside character sets. // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. return string .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') .replace(/-/g, '\\x2d'); }; const start$f = unistUtilPosition.start; var remarkLintProhibitedStrings = unifiedLintRule('remark-lint:prohibited-strings', prohibitedStrings); function testProhibited (val, content) { let regexpFlags = 'g'; let no = val.no; if (!no) { no = escapeStringRegexp$1(val.yes); regexpFlags += 'i'; } let regexpString = '(? { const results = testProhibited(val, content); if (results.length) { results.forEach(({ result, index }) => { const message = val.yes ? `Use "${val.yes}" instead of "${result}"` : `Do not use "${result}"`; file.message(message, { start: location.toPosition(initial + index), end: location.toPosition(initial + index + [...result].length) }); }); } }); } } var rule = unifiedLintRule; var remarkLintRuleStyle = rule('remark-lint:rule-style', ruleStyle); var start$g = unistUtilPosition.start; var end$9 = unistUtilPosition.end; function ruleStyle(tree, file, option) { var contents = String(file); var preferred = typeof option === 'string' && option !== 'consistent' ? option : null; if (preferred !== null && /[^-_* ]/.test(preferred)) { file.fail( "Incorrect preferred rule style: provide a correct markdown rule or `'consistent'`" ); } unistUtilVisit(tree, 'thematicBreak', visitor); function visitor(node) { var initial = start$g(node).offset; var final = end$9(node).offset; var rule; if (!unistUtilGenerated(node)) { rule = contents.slice(initial, final); if (preferred) { if (rule !== preferred) { file.message('Rules should use `' + preferred + '`', node); } } else { preferred = rule; } } } } var remarkLintStrongMarker = unifiedLintRule('remark-lint:strong-marker', strongMarker); var markers$1 = {'*': true, _: true, null: true}; function strongMarker(tree, file, option) { var contents = String(file); var preferred = typeof option === 'string' && option !== 'consistent' ? option : null; if (markers$1[preferred] !== true) { file.fail( 'Incorrect strong marker `' + preferred + "`: use either `'consistent'`, `'*'`, or `'_'`" ); } unistUtilVisit(tree, 'strong', visitor); function visitor(node) { var marker = contents.charAt(unistUtilPosition.start(node).offset); if (!unistUtilGenerated(node)) { if (preferred) { if (marker !== preferred) { file.message( 'Strong should use `' + preferred + '` as a marker', node ); } } else { preferred = marker; } } } } var remarkLintTableCellPadding = unifiedLintRule('remark-lint:table-cell-padding', tableCellPadding); var start$h = unistUtilPosition.start; var end$a = unistUtilPosition.end; var styles$4 = {null: true, padded: true, compact: true}; function tableCellPadding(tree, file, option) { var preferred = typeof option === 'string' && option !== 'consistent' ? option : null; if (styles$4[preferred] !== true) { file.fail( 'Incorrect table cell padding style `' + preferred + "`, expected `'padded'`, `'compact'`, or `'consistent'`" ); } unistUtilVisit(tree, 'table', visitor); function visitor(node) { var rows = node.children; var sizes = new Array(node.align.length); var length = unistUtilGenerated(node) ? -1 : rows.length; var index = -1; var entries = []; var style; var row; var cells; var column; var cellCount; var cell; var entry; var contentStart; var contentEnd; // Check rows. while (++index < length) { row = rows[index]; cells = row.children; cellCount = cells.length; column = -1; // Check fences (before, between, and after cells). while (++column < cellCount) { cell = cells[column]; if (cell && cell.children.length !== 0) { contentStart = start$h(cell.children[0]).offset; contentEnd = end$a(cell.children[cell.children.length - 1]).offset; entries.push({ node: cell, start: contentStart - start$h(cell).offset - (column ? 0 : 1), end: end$a(cell).offset - contentEnd - 1, column: column }); // Detect max space per column. sizes[column] = Math.max( sizes[column] || 0, contentEnd - contentStart ); } } } if (preferred) { style = preferred === 'padded' ? 1 : 0; } else { style = entries[0] && (!entries[0].start || !entries[0].end) ? 0 : 1; } index = -1; length = entries.length; while (++index < length) { entry = entries[index]; checkSide('start', entry, style, sizes); checkSide('end', entry, style, sizes); } return unistUtilVisit.SKIP } function checkSide(side, entry, style, sizes) { var cell = entry.node; var spacing = entry[side]; var column = entry.column; var reason; var point; if (spacing === undefined || spacing === style) { return } reason = 'Cell should be '; if (style === 0) { // Ignore every cell except the biggest in the column. if (size(cell) < sizes[column]) { return } reason += 'compact'; } else { reason += 'padded'; if (spacing > style) { // May be right or center aligned. if (size(cell) < sizes[column]) { return } reason += ' with 1 space, not ' + spacing; } } if (side === 'start') { point = start$h(cell); if (!column) { point.column++; point.offset++; } } else { point = end$a(cell); point.column--; point.offset--; } file.message(reason, point); } } function size(node) { return ( end$a(node.children[node.children.length - 1]).offset - start$h(node.children[0]).offset ) } var remarkLintTablePipes = unifiedLintRule('remark-lint:table-pipes', tablePipes); var start$i = unistUtilPosition.start; var end$b = unistUtilPosition.end; var reasonStart = 'Missing initial pipe in table fence'; var reasonEnd = 'Missing final pipe in table fence'; function tablePipes(tree, file) { var contents = String(file); unistUtilVisit(tree, 'table', visitor); function visitor(node) { var rows = node.children; var length = rows.length; var index = -1; var row; while (++index < length) { row = rows[index]; if (!unistUtilGenerated(row)) { if (contents.charCodeAt(start$i(row).offset) !== 124) { file.message(reasonStart, start$i(row)); } if (contents.charCodeAt(end$b(row).offset - 1) !== 124) { file.message(reasonEnd, end$b(row)); } } } } } var remarkLintUnorderedListMarkerStyle = unifiedLintRule( 'remark-lint:unordered-list-marker-style', unorderedListMarkerStyle ); var start$j = unistUtilPosition.start; var styles$5 = { '-': true, '*': true, '+': true, null: true }; function unorderedListMarkerStyle(tree, file, option) { var contents = String(file); var preferred = typeof option === 'string' && option !== 'consistent' ? option : null; if (styles$5[preferred] !== true) { file.fail( 'Incorrect unordered list item marker style `' + preferred + "`: use either `'-'`, `'*'`, or `'+'`" ); } unistUtilVisit(tree, 'list', visitor); function visitor(node) { var children = node.children; var length = node.ordered ? 0 : children.length; var index = -1; var child; var marker; while (++index < length) { child = children[index]; if (!unistUtilGenerated(child)) { marker = contents .slice(start$j(child).offset, start$j(child.children[0]).offset) .replace(/\[[x ]?]\s*$/i, '') .replace(/\s/g, ''); if (preferred) { if (marker !== preferred) { file.message('Marker style should be `' + preferred + '`', child); } } else { preferred = marker; } } } } } // Add in rules alphabetically var plugins$2 = [ remarkLint, // Leave preset at the top so it can be overridden remarkPresetLintRecommended, [remarkLintBlockquoteIndentation, 2], [ remarkLintCheckboxCharacterStyle, { checked: "x", unchecked: " ", }, ], remarkLintCheckboxContentIndent, [remarkLintCodeBlockStyle, "fenced"], remarkLintDefinitionSpacing, [ remarkLintFencedCodeFlag, { flags: [ "bash", "c", "coffee", "console", "cpp", "diff", "http", "js", "json", "markdown", "powershell", "r", "text", ], }, ], [remarkLintFencedCodeMarker, "`"], [remarkLintFileExtension, "md"], remarkLintFinalDefinition, [remarkLintFirstHeadingLevel, 1], [remarkLintHeadingStyle, "atx"], [remarkLintListItemIndent, "space"], remarkLintMaximumLineLength, remarkLintNoConsecutiveBlankLines, remarkLintNoFileNameArticles, remarkLintNoFileNameConsecutiveDashes, remarkLintNoFileNameOuterDashes, remarkLintNoHeadingIndent, remarkLintNoMultipleToplevelHeadings, remarkLintNoShellDollars, remarkLintNoTableIndentation, remarkLintNoTabs, remarkLintNoTrailingSpaces, remarkLintNodejsYamlComments, [ remarkLintProhibitedStrings, [ { yes: "End-of-Life" }, { yes: "GitHub" }, { no: "hostname", yes: "host name" }, { yes: "JavaScript" }, { no: "Node", yes: "Node.js" }, { yes: "Node.js" }, { no: "Node[Jj][Ss]", yes: "Node.js" }, { no: "Node\\.js's?", yes: "the Node.js" }, { no: "[Nn]ote that", yes: "" }, { yes: "RFC" }, { no: "[Rr][Ff][Cc]\\d+", yes: "RFC " }, { yes: "Unix" }, { yes: "V8" }, ], ], remarkLintRuleStyle, [remarkLintStrongMarker, "*"], [remarkLintTableCellPadding, "padded"], remarkLintTablePipes, [remarkLintUnorderedListMarkerStyle, "*"], ]; var remarkPresetLintNode = { plugins: plugins$2 }; var domain = {tokenize: tokenizeDomain}; var path$1 = {tokenize: tokenizePath}; var punctuation = {tokenize: tokenizePunctuation}; var paren = {tokenize: tokenizeParen}; var namedCharacterReference = {tokenize: tokenizeNamedCharacterReference}; var wwwAutolink = {tokenize: tokenizeWwwAutolink, previous: previous$1}; var httpAutolink = {tokenize: tokenizeHttpAutolink, previous: previous$1}; var emailAutolink = {tokenize: tokenizeEmailAutolink, previous: previous$1}; var text$4 = {}; // Export hooked constructs. var text_1$2 = text$4; // `0` var code$2 = 48; // While the code is smaller than `{`. while (code$2 < 123) { text$4[code$2] = emailAutolink; code$2++; // Jump from `:` -> `A` if (code$2 === 58) code$2 = 65; // Jump from `[` -> `a` else if (code$2 === 91) code$2 = 97; } // `+` text$4[43] = emailAutolink; // `-` text$4[45] = emailAutolink; // `.` text$4[46] = emailAutolink; // `_` text$4[95] = emailAutolink; // `h`. text$4[72] = [emailAutolink, httpAutolink]; text$4[104] = [emailAutolink, httpAutolink]; // `w`. text$4[87] = [emailAutolink, wwwAutolink]; text$4[119] = [emailAutolink, wwwAutolink]; function tokenizeEmailAutolink(effects, ok, nok) { var self = this; var hasDot; return start function start(code) { /* istanbul ignore next - hooks. */ if (!gfmAtext(code) || !previous$1(self.previous)) { return nok(code) } effects.enter('literalAutolink'); effects.enter('literalAutolinkEmail'); return atext(code) } function atext(code) { if (gfmAtext(code)) { effects.consume(code); return atext } // `@` if (code === 64) { effects.consume(code); return label } return nok(code) } function label(code) { // `.` if (code === 46) { return effects.check(punctuation, done, dotContinuation)(code) } if ( // `-` code === 45 || // `_` code === 95 ) { return effects.check(punctuation, nok, dashOrUnderscoreContinuation)(code) } if (asciiAlphanumeric(code)) { effects.consume(code); return label } return done(code) } function dotContinuation(code) { effects.consume(code); hasDot = true; return label } function dashOrUnderscoreContinuation(code) { effects.consume(code); return afterDashOrUnderscore } function afterDashOrUnderscore(code) { // `.` if (code === 46) { return effects.check(punctuation, nok, dotContinuation)(code) } return label(code) } function done(code) { if (hasDot) { effects.exit('literalAutolinkEmail'); effects.exit('literalAutolink'); return ok(code) } return nok(code) } } function tokenizeWwwAutolink(effects, ok, nok) { var self = this; return start function start(code) { /* istanbul ignore next - hooks. */ if ((code !== 87 && code - 32 !== 87) || !previous$1(self.previous)) { return nok(code) } effects.enter('literalAutolink'); effects.enter('literalAutolinkWww'); effects.consume(code); return w2 } function w2(code) { // `w` if (code === 87 || code - 32 === 87) { effects.consume(code); return w3 } return nok(code) } function w3(code) { // `w` if (code === 87 || code - 32 === 87) { effects.consume(code); return dot } return nok(code) } function dot(code) { // `.` if (code === 46) { effects.consume(code); return effects.attempt(domain, effects.attempt(path$1, done), nok) } return nok(code) } function done(code) { effects.exit('literalAutolinkWww'); effects.exit('literalAutolink'); return ok(code) } } function tokenizeHttpAutolink(effects, ok, nok) { var self = this; return start function start(code) { /* istanbul ignore next - hooks. */ if ((code !== 72 && code - 32 !== 72) || !previous$1(self.previous)) { return nok(code) } effects.enter('literalAutolink'); effects.enter('literalAutolinkHttp'); effects.consume(code); return t1 } function t1(code) { // `t` if (code === 84 || code - 32 === 84) { effects.consume(code); return t2 } return nok(code) } function t2(code) { // `t` if (code === 84 || code - 32 === 84) { effects.consume(code); return p } return nok(code) } function p(code) { // `p` if (code === 80 || code - 32 === 80) { effects.consume(code); return s } return nok(code) } function s(code) { // `s` if (code === 83 || code - 32 === 83) { effects.consume(code); return colon } return colon(code) } function colon(code) { // `:` if (code === 58) { effects.consume(code); return slash1 } return nok(code) } function slash1(code) { // `/` if (code === 47) { effects.consume(code); return slash2 } return nok(code) } function slash2(code) { // `/` if (code === 47) { effects.consume(code); return effects.attempt(domain, effects.attempt(path$1, done), nok) } return nok(code) } function done(code) { effects.exit('literalAutolinkHttp'); effects.exit('literalAutolink'); return ok(code) } } function tokenizeDomain(effects, ok, nok) { var hasUnderscoreInLastSegment; var hasUnderscoreInLastLastSegment; var hasDot; return start function start(code) { effects.enter('literalAutolinkDomain'); return domain(code) } function domain(code) { if ( // `-` code === 45 || // `_` code === 95 || asciiAlphanumeric(code) ) { if (code === 95) { hasUnderscoreInLastSegment = true; } effects.consume(code); return domain } // `.` if (code === 46) { return effects.check(punctuation, done, dotContinuation)(code) } return done(code) } function dotContinuation(code) { effects.consume(code); hasDot = true; hasUnderscoreInLastLastSegment = hasUnderscoreInLastSegment; hasUnderscoreInLastSegment = undefined; return domain } function done(code) { if ( hasDot && !hasUnderscoreInLastLastSegment && !hasUnderscoreInLastSegment ) { effects.exit('literalAutolinkDomain'); return ok(code) } return nok(code) } } function tokenizePath(effects, ok) { var balance = 0; return start function start(code) { if (pathEnd(code)) { return ok(code) } if (trailingPunctuation(code)) { return effects.check(punctuation, ok, atPathStart)(code) } return atPathStart(code) } function atPathStart(code) { effects.enter('literalAutolinkWwwPath'); return inPath(code) } function inPath(code) { // `&` if (code === 38) { return effects.check( namedCharacterReference, atPathEnd, continuedPunctuation )(code) } // `(` if (code === 40) { balance++; } // `)` if (code === 41) { return effects.check(paren, parenAtPathEnd, continuedPunctuation)(code) } if (pathEnd(code)) { return atPathEnd(code) } if (trailingPunctuation(code)) { return effects.check(punctuation, atPathEnd, continuedPunctuation)(code) } effects.consume(code); return inPath } function continuedPunctuation(code) { effects.consume(code); return inPath } function parenAtPathEnd(code) { balance--; return balance < 0 ? atPathEnd(code) : continuedPunctuation(code) } function atPathEnd(code) { effects.exit('literalAutolinkWwwPath'); return ok(code) } } function tokenizeNamedCharacterReference(effects, ok, nok) { return start function start(code) { // Assume an ampersand. effects.enter('literalAutolinkCharacterReferenceNamed'); effects.consume(code); return inside } function inside(code) { if (asciiAlpha(code)) { effects.consume(code); return inside } // `;` if (code === 59) { effects.consume(code); return after } return nok(code) } function after(code) { // If the named character reference is followed by the end of the path, it’s // not continued punctuation. effects.exit('literalAutolinkCharacterReferenceNamed'); return pathEnd(code) ? ok(code) : nok(code) } } function tokenizeParen(effects, ok, nok) { return start function start(code) { // Assume a right paren. effects.enter('literalAutolinkParen'); effects.consume(code); return after } function after(code) { // If the punctuation marker is followed by the end of the path, it’s not // continued punctuation. effects.exit('literalAutolinkParen'); return pathEnd(code) || // `)` code === 41 ? ok(code) : nok(code) } } function tokenizePunctuation(effects, ok, nok) { return start function start(code) { effects.enter('literalAutolinkPunctuation'); // Always a valid trailing punctuation marker. effects.consume(code); return after } function after(code) { // If the punctuation marker is followed by the end of the path, it’s not // continued punctuation. effects.exit('literalAutolinkPunctuation'); return pathEnd(code) ? ok(code) : nok(code) } } function trailingPunctuation(code) { return ( // Exclamation mark. code === 33 || // Asterisk. code === 42 || // Comma. code === 44 || // Dot. code === 46 || // Colon. code === 58 || // Question mark. code === 63 || // Underscore. code === 95 || // Tilde. code === 126 ) } function pathEnd(code) { return ( // EOF. code === null || // CR, LF, CRLF, HT, VS. code < 0 || // Space. code === 32 || // Less than. code === 60 ) } function gfmAtext(code) { return ( // `+` code === 43 || // `-` code === 45 || // `.` code === 46 || // `_` code === 95 || asciiAlphanumeric(code) ) } function previous$1(code) { return ( // EOF. code === null || // CR, LF, CRLF, HT, VS. code < 0 || // Space. code === 32 || // Left paren. code === 40 || // Asterisk. code === 42 || // Underscore. code === 95 || // Tilde. code === 126 ) } var syntax = { text: text_1$2 }; var micromarkExtensionGfmAutolinkLiteral = syntax; var micromarkExtensionGfmStrikethrough = create$2; function create$2(options) { var settings = options || {}; var single = settings.singleTilde; var tokenizer = { tokenize: tokenizeStrikethrough, resolveAll: resolveAllStrikethrough }; if (single === null || single === undefined) { single = true; } return {text: {126: tokenizer}, insideSpan: {null: tokenizer}} // Take events and resolve strikethrough. function resolveAllStrikethrough(events, context) { var index = -1; var strikethrough; var text; var open; var nextEvents; // Walk through all events. while (++index < events.length) { // Find a token that can close. if ( events[index][0] === 'enter' && events[index][1].type === 'strikethroughSequenceTemporary' && events[index][1]._close ) { open = index; // Now walk back to find an opener. while (open--) { // Find a token that can open the closer. if ( events[open][0] === 'exit' && events[open][1].type === 'strikethroughSequenceTemporary' && events[open][1]._open && // If the sizes are the same: events[index][1].end.offset - events[index][1].start.offset === events[open][1].end.offset - events[open][1].start.offset ) { events[index][1].type = 'strikethroughSequence'; events[open][1].type = 'strikethroughSequence'; strikethrough = { type: 'strikethrough', start: shallow_1(events[open][1].start), end: shallow_1(events[index][1].end) }; text = { type: 'strikethroughText', start: shallow_1(events[open][1].end), end: shallow_1(events[index][1].start) }; // Opening. nextEvents = [ ['enter', strikethrough, context], ['enter', events[open][1], context], ['exit', events[open][1], context], ['enter', text, context] ]; // Between. chunkedSplice_1( nextEvents, nextEvents.length, 0, resolveAll_1( context.parser.constructs.insideSpan.null, events.slice(open + 1, index), context ) ); // Closing. chunkedSplice_1(nextEvents, nextEvents.length, 0, [ ['exit', text, context], ['enter', events[index][1], context], ['exit', events[index][1], context], ['exit', strikethrough, context] ]); chunkedSplice_1(events, open - 1, index - open + 3, nextEvents); index = open + nextEvents.length - 2; break } } } } return removeRemainingSequences(events) } function removeRemainingSequences(events) { var index = -1; var length = events.length; while (++index < length) { if (events[index][1].type === 'strikethroughSequenceTemporary') { events[index][1].type = 'data'; } } return events } function tokenizeStrikethrough(effects, ok, nok) { var previous = this.previous; var events = this.events; var size = 0; return start function start(code) { if ( code !== 126 || (previous === 126 && events[events.length - 1][1].type !== 'characterEscape') ) { return nok(code) } effects.enter('strikethroughSequenceTemporary'); return more(code) } function more(code) { var before = classifyCharacter_1(previous); var token; var after; if (code === 126) { // If this is the third marker, exit. if (size > 1) return nok(code) effects.consume(code); size++; return more } if (size < 2 && !single) return nok(code) token = effects.exit('strikethroughSequenceTemporary'); after = classifyCharacter_1(code); token._open = !after || (after === 2 && before); token._close = !before || (before === 2 && after); return ok(code) } } } var flow$3 = { null: {tokenize: tokenizeTable, resolve: resolveTable, interruptible: true} }; var setextUnderlineMini = {tokenize: tokenizeSetextUnderlineMini, partial: true}; var nextPrefixedOrBlank = {tokenize: tokenizeNextPrefixedOrBlank, partial: true}; function resolveTable(events, context) { var length = events.length; var index = -1; var token; var inHead; var inDelimiterRow; var inRow; var cell; var content; var text; var contentStart; var contentEnd; var cellStart; while (++index < length) { token = events[index][1]; if (inRow) { if (token.type === 'temporaryTableCellContent') { contentStart = contentStart || index; contentEnd = index; } if ( // Combine separate content parts into one. (token.type === 'tableCellDivider' || token.type === 'tableRow') && contentEnd ) { content = { type: 'tableContent', start: events[contentStart][1].start, end: events[contentEnd][1].end }; text = { type: 'chunkText', start: content.start, end: content.end, contentType: 'text' }; events.splice( contentStart, contentEnd - contentStart + 1, ['enter', content, context], ['enter', text, context], ['exit', text, context], ['exit', content, context] ); index -= contentEnd - contentStart - 3; length = events.length; contentStart = undefined; contentEnd = undefined; } } if ( events[index][0] === 'exit' && (token.type === 'tableCellDivider' || token.type === 'tableRow') && cellStart && cellStart + 1 < index ) { cell = { type: inDelimiterRow ? 'tableDelimiter' : inHead ? 'tableHeader' : 'tableData', start: events[cellStart][1].start, end: events[index][1].end }; events.splice(index + (token.type === 'tableCellDivider' ? 1 : 0), 0, [ 'exit', cell, context ]); events.splice(cellStart, 0, ['enter', cell, context]); index += 2; length = events.length; cellStart = index + 1; } if (token.type === 'tableRow') { inRow = events[index][0] === 'enter'; if (inRow) { cellStart = index + 1; } } if (token.type === 'tableDelimiterRow') { inDelimiterRow = events[index][0] === 'enter'; if (inDelimiterRow) { cellStart = index + 1; } } if (token.type === 'tableHead') { inHead = events[index][0] === 'enter'; } } return events } function tokenizeTable(effects, ok, nok) { var align = []; var tableHeaderCount = 0; var seenDelimiter; var hasDash; return start function start(code) { /* istanbul ignore if - used to be passed in beta micromark versions. */ if (code === null || code === -5 || code === -4 || code === -3) { return nok(code) } effects.enter('table')._align = align; effects.enter('tableHead'); effects.enter('tableRow'); // If we start with a pipe, we open a cell marker. if (code === 124) { return cellDividerHead(code) } tableHeaderCount++; effects.enter('temporaryTableCellContent'); // Can’t be space or eols at the start of a construct, so we’re in a cell. return inCellContentHead(code) } function cellDividerHead(code) { // Always a pipe. effects.enter('tableCellDivider'); effects.consume(code); effects.exit('tableCellDivider'); seenDelimiter = true; return cellBreakHead } function cellBreakHead(code) { // EOF, CR, LF, CRLF. if (code === null || code === -5 || code === -4 || code === -3) { return atRowEndHead(code) } // HT, VS, SP. if (code === -2 || code === -1 || code === 32) { effects.enter('whitespace'); effects.consume(code); return inWhitespaceHead } if (seenDelimiter) { seenDelimiter = undefined; tableHeaderCount++; } // `|` if (code === 124) { return cellDividerHead(code) } // Anything else is cell content. effects.enter('temporaryTableCellContent'); return inCellContentHead(code) } function inWhitespaceHead(code) { // HT, VS, SP. if (code === -2 || code === -1 || code === 32) { effects.consume(code); return inWhitespaceHead } effects.exit('whitespace'); return cellBreakHead(code) } function inCellContentHead(code) { // EOF, whitespace, pipe if (code === null || code < 0 || code === 32 || code === 124) { effects.exit('temporaryTableCellContent'); return cellBreakHead(code) } effects.consume(code); // `\` return code === 92 ? inCellContentEscapeHead : inCellContentHead } function inCellContentEscapeHead(code) { // `\` or `|` if (code === 92 || code === 124) { effects.consume(code); return inCellContentHead } // Anything else. return inCellContentHead(code) } function atRowEndHead(code) { if (code === null) { return nok(code) } effects.exit('tableRow'); effects.exit('tableHead'); // Always a line ending. effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); // If a setext heading, exit. return effects.check( setextUnderlineMini, nok, // Support an indent before the delimiter row. factorySpace(effects, rowStartDelimiter, 'linePrefix', 4) ) } function rowStartDelimiter(code) { // If there’s another space, or we’re at the EOL/EOF, exit. if (code === null || code < 0 || code === 32) { return nok(code) } effects.enter('tableDelimiterRow'); return atDelimiterRowBreak(code) } function atDelimiterRowBreak(code) { // EOF, CR, LF, CRLF. if (code === null || code === -5 || code === -4 || code === -3) { return rowEndDelimiter(code) } // HT, VS, SP. if (code === -2 || code === -1 || code === 32) { effects.enter('whitespace'); effects.consume(code); return inWhitespaceDelimiter } // `-` if (code === 45) { effects.enter('tableDelimiterFiller'); effects.consume(code); hasDash = true; align.push(null); return inFillerDelimiter } // `:` if (code === 58) { effects.enter('tableDelimiterAlignment'); effects.consume(code); effects.exit('tableDelimiterAlignment'); align.push('left'); return afterLeftAlignment } // If we start with a pipe, we open a cell marker. if (code === 124) { effects.enter('tableCellDivider'); effects.consume(code); effects.exit('tableCellDivider'); return atDelimiterRowBreak } return nok(code) } function inWhitespaceDelimiter(code) { // HT, VS, SP. if (code === -2 || code === -1 || code === 32) { effects.consume(code); return inWhitespaceDelimiter } effects.exit('whitespace'); return atDelimiterRowBreak(code) } function inFillerDelimiter(code) { // `-` if (code === 45) { effects.consume(code); return inFillerDelimiter } effects.exit('tableDelimiterFiller'); // `:` if (code === 58) { effects.enter('tableDelimiterAlignment'); effects.consume(code); effects.exit('tableDelimiterAlignment'); align[align.length - 1] = align[align.length - 1] === 'left' ? 'center' : 'right'; return afterRightAlignment } return atDelimiterRowBreak(code) } function afterLeftAlignment(code) { // `-` if (code === 45) { effects.enter('tableDelimiterFiller'); effects.consume(code); hasDash = true; return inFillerDelimiter } // Anything else is not ok. return nok(code) } function afterRightAlignment(code) { // EOF, CR, LF, CRLF. if (code === null || code === -5 || code === -4 || code === -3) { return rowEndDelimiter(code) } // HT, VS, SP. if (code === -2 || code === -1 || code === 32) { effects.enter('whitespace'); effects.consume(code); return inWhitespaceDelimiter } // `|` if (code === 124) { effects.enter('tableCellDivider'); effects.consume(code); effects.exit('tableCellDivider'); return atDelimiterRowBreak } return nok(code) } function rowEndDelimiter(code) { effects.exit('tableDelimiterRow'); // Exit if there was no dash at all, or if the header cell count is not the // delimiter cell count. if (!hasDash || tableHeaderCount !== align.length) { return nok(code) } if (code === null) { return tableClose(code) } return effects.check(nextPrefixedOrBlank, tableClose, tableContinue)(code) } function tableClose(code) { effects.exit('table'); return ok(code) } function tableContinue(code) { // Always a line ending. effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); // We checked that it’s not a prefixed or blank line, so we’re certain a // body is coming, though it may be indented. return factorySpace(effects, bodyStart, 'linePrefix', 4) } function bodyStart(code) { effects.enter('tableBody'); return rowStartBody(code) } function rowStartBody(code) { effects.enter('tableRow'); // If we start with a pipe, we open a cell marker. if (code === 124) { return cellDividerBody(code) } effects.enter('temporaryTableCellContent'); // Can’t be space or eols at the start of a construct, so we’re in a cell. return inCellContentBody(code) } function cellDividerBody(code) { // Always a pipe. effects.enter('tableCellDivider'); effects.consume(code); effects.exit('tableCellDivider'); return cellBreakBody } function cellBreakBody(code) { // EOF, CR, LF, CRLF. if (code === null || code === -5 || code === -4 || code === -3) { return atRowEndBody(code) } // HT, VS, SP. if (code === -2 || code === -1 || code === 32) { effects.enter('whitespace'); effects.consume(code); return inWhitespaceBody } // `|` if (code === 124) { return cellDividerBody(code) } // Anything else is cell content. effects.enter('temporaryTableCellContent'); return inCellContentBody(code) } function inWhitespaceBody(code) { // HT, VS, SP. if (code === -2 || code === -1 || code === 32) { effects.consume(code); return inWhitespaceBody } effects.exit('whitespace'); return cellBreakBody(code) } function inCellContentBody(code) { // EOF, whitespace, pipe if (code === null || code < 0 || code === 32 || code === 124) { effects.exit('temporaryTableCellContent'); return cellBreakBody(code) } effects.consume(code); // `\` return code === 92 ? inCellContentEscapeBody : inCellContentBody } function inCellContentEscapeBody(code) { // `\` or `|` if (code === 92 || code === 124) { effects.consume(code); return inCellContentBody } // Anything else. return inCellContentBody(code) } function atRowEndBody(code) { effects.exit('tableRow'); if (code === null) { return tableBodyClose(code) } return effects.check( nextPrefixedOrBlank, tableBodyClose, tableBodyContinue )(code) } function tableBodyClose(code) { effects.exit('tableBody'); return tableClose(code) } function tableBodyContinue(code) { // Always a line ending. effects.enter('lineEnding'); effects.consume(code); effects.exit('lineEnding'); // Support an optional prefix, then start a body row. return factorySpace(effects, rowStartBody, 'linePrefix', 4) } } // Based on micromark, but that won’t work as we’re in a table, and that expects // content. // function tokenizeSetextUnderlineMini(effects, ok, nok) { return start function start(code) { // `-` if (code !== 45) { return nok(code) } effects.enter('setextUnderline'); return sequence(code) } function sequence(code) { if (code === 45) { effects.consume(code); return sequence } return whitespace(code) } function whitespace(code) { if (code === -2 || code === -1 || code === 32) { effects.consume(code); return whitespace } if (code === null || code === -5 || code === -4 || code === -3) { return ok(code) } return nok(code) } } function tokenizeNextPrefixedOrBlank(effects, ok, nok) { var size = 0; return start function start(code) { // This is a check, so we don’t care about tokens, but we open a bogus one // so we’re valid. effects.enter('check'); // EOL. effects.consume(code); return whitespace } function whitespace(code) { // VS or SP. if (code === -1 || code === 32) { effects.consume(code); size++; return size === 4 ? ok : whitespace } // EOF or whitespace if (code === null || code < 0) { return ok(code) } // Anything else. return nok(code) } } var syntax$1 = { flow: flow$3 }; var micromarkExtensionGfmTable = syntax$1; var tasklistCheck = {tokenize: tokenizeTasklistCheck}; var text$5 = {91: tasklistCheck}; function tokenizeTasklistCheck(effects, ok, nok) { var self = this; return open function open(code) { if ( // Exit if not `[`. code !== 91 || // Exit if there’s stuff before. self.previous !== null || // Exit if not in the first content that is the first child of a list // item. !self._gfmTasklistFirstContentOfListItem ) { return nok(code) } effects.enter('taskListCheck'); effects.enter('taskListCheckMarker'); effects.consume(code); effects.exit('taskListCheckMarker'); return inside } function inside(code) { // Tab or space. if (code === -2 || code === 32) { effects.enter('taskListCheckValueUnchecked'); effects.consume(code); effects.exit('taskListCheckValueUnchecked'); return close } // Upper- and lower `x`. if (code === 88 || code === 120) { effects.enter('taskListCheckValueChecked'); effects.consume(code); effects.exit('taskListCheckValueChecked'); return close } return nok(code) } function close(code) { // `]` if (code === 93) { effects.enter('taskListCheckMarker'); effects.consume(code); effects.exit('taskListCheckMarker'); effects.exit('taskListCheck'); return after } return nok(code) } function after(code) { // Tab or space. if (code === -2 || code === 32) { return ok(code) } return nok(code) } } var syntax$2 = { text: text$5 }; var micromarkExtensionGfmTaskListItem = syntax$2; var syntax$3 = create$3; function create$3(options) { return combineExtensions_1([micromarkExtensionGfmAutolinkLiteral, micromarkExtensionGfmStrikethrough(options), micromarkExtensionGfmTable, micromarkExtensionGfmTaskListItem]) } var micromarkExtensionGfm = syntax$3; var enter = { literalAutolink: enterLiteralAutolink, literalAutolinkEmail: enterLiteralAutolinkValue, literalAutolinkHttp: enterLiteralAutolinkValue, literalAutolinkWww: enterLiteralAutolinkValue }; var exit = { literalAutolink: exitLiteralAutolink, literalAutolinkEmail: exitLiteralAutolinkEmail, literalAutolinkHttp: exitLiteralAutolinkHttp, literalAutolinkWww: exitLiteralAutolinkWww }; function enterLiteralAutolink(token) { this.enter({type: 'link', title: null, url: '', children: []}, token); } function enterLiteralAutolinkValue(token) { this.config.enter.autolinkProtocol.call(this, token); } function exitLiteralAutolinkHttp(token) { this.config.exit.autolinkProtocol.call(this, token); } function exitLiteralAutolinkWww(token) { this.config.exit.data.call(this, token); this.stack[this.stack.length - 1].url = 'http://' + this.sliceSerialize(token); } function exitLiteralAutolinkEmail(token) { this.config.exit.autolinkEmail.call(this, token); } function exitLiteralAutolink(token) { this.exit(token); } var fromMarkdown$1 = { enter: enter, exit: exit }; var canContainEols = ['delete']; var enter$1 = {strikethrough: enterStrikethrough}; var exit$1 = {strikethrough: exitStrikethrough}; function enterStrikethrough(token) { this.enter({type: 'delete', children: []}, token); } function exitStrikethrough(token) { this.exit(token); } var fromMarkdown$2 = { canContainEols: canContainEols, enter: enter$1, exit: exit$1 }; var enter$2 = { table: enterTable, tableData: enterCell, tableHeader: enterCell, tableRow: enterRow }; var exit_1 = { codeText: exitCodeText, table: exitTable, tableData: exit$2, tableHeader: exit$2, tableRow: exit$2 }; function enterTable(token) { this.enter({type: 'table', align: token._align, children: []}, token); this.setData('inTable', true); } function exitTable(token) { this.exit(token); this.setData('inTable'); } function enterRow(token) { this.enter({type: 'tableRow', children: []}, token); } function exit$2(token) { this.exit(token); } function enterCell(token) { this.enter({type: 'tableCell', children: []}, token); } // Overwrite the default code text data handler to unescape escaped pipes when // they are in tables. function exitCodeText(token) { var value = this.resume(); if (this.getData('inTable')) { value = value.replace(/\\([\\|])/g, replace); } this.stack[this.stack.length - 1].value = value; this.exit(token); } function replace($0, $1) { // Pipes work, backslashes don’t (but can’t escape pipes). return $1 === '|' ? $1 : $0 } var fromMarkdown$3 = { enter: enter$2, exit: exit_1 }; var exit$3 = { taskListCheckValueChecked: exitCheck, taskListCheckValueUnchecked: exitCheck, paragraph: exitParagraphWithTaskListItem }; function exitCheck(token) { // We’re always in a paragraph, in a list item. this.stack[this.stack.length - 2].checked = token.type === 'taskListCheckValueChecked'; } function exitParagraphWithTaskListItem(token) { var node = this.stack[this.stack.length - 1]; var parent = this.stack[this.stack.length - 2]; var head = node.children[0]; if ( parent.type === 'listItem' && typeof parent.checked === 'boolean' && head && head.type === 'text' ) { // Must start with a space or a tab. head.value = head.value.slice(1); if (head.value.length === 0) { node.children.shift(); } else { head.position.start.column++; head.position.start.offset++; node.position.start = Object.assign({}, head.position.start); } } this.exit(token); } var fromMarkdown$4 = { exit: exit$3 }; var own$5 = {}.hasOwnProperty; var fromMarkdown$5 = configure$4([ fromMarkdown$1, fromMarkdown$2, fromMarkdown$3, fromMarkdown$4 ]); function configure$4(extensions) { var config = {canContainEols: []}; var length = extensions.length; var index = -1; while (++index < length) { extension$3(config, extensions[index]); } return config } function extension$3(config, extension) { var key; var left; var right; for (key in extension) { left = own$5.call(config, key) ? config[key] : (config[key] = {}); right = extension[key]; if (key === 'canContainEols') { config[key] = [].concat(left, right); } else { Object.assign(left, right); } } } var inConstruct = 'phrasing'; var notInConstruct = ['autolink', 'link', 'image']; var unsafe$1 = [ { character: '@', before: '[+\\-.\\w]', after: '[\\-.\\w]', inConstruct: inConstruct, notInConstruct: notInConstruct }, { character: '.', before: '[Ww]', after: '[\\-.\\w]', inConstruct: inConstruct, notInConstruct: notInConstruct }, { character: ':', before: '[ps]', after: '\\/', inConstruct: inConstruct, notInConstruct: notInConstruct } ]; var toMarkdown$1 = { unsafe: unsafe$1 }; var unsafe$2 = [{character: '~', inConstruct: 'phrasing'}]; var handlers = {delete: handleDelete}; handleDelete.peek = peekDelete; function handleDelete(node, _, context) { var exit = context.enter('emphasis'); var value = containerPhrasing(node, context, {before: '~', after: '~'}); exit(); return '~~' + value + '~~' } function peekDelete() { return '~' } var toMarkdown$2 = { unsafe: unsafe$2, handlers: handlers }; var markdownTable_1 = markdownTable; var trailingWhitespace = / +$/; // Characters. var space = ' '; var lineFeed = '\n'; var dash$1 = '-'; var colon$1 = ':'; var verticalBar = '|'; var x = 0; var C = 67; var L$1 = 76; var R = 82; var c$1 = 99; var l$1 = 108; var r = 114; // Create a table from a matrix of strings. function markdownTable(table, options) { var settings = options || {}; var padding = settings.padding !== false; var start = settings.delimiterStart !== false; var end = settings.delimiterEnd !== false; var align = (settings.align || []).concat(); var alignDelimiters = settings.alignDelimiters !== false; var alignments = []; var stringLength = settings.stringLength || defaultStringLength; var rowIndex = -1; var rowLength = table.length; var cellMatrix = []; var sizeMatrix = []; var row = []; var sizes = []; var longestCellByColumn = []; var mostCellsPerRow = 0; var cells; var columnIndex; var columnLength; var largest; var size; var cell; var lines; var line; var before; var after; var code; // This is a superfluous loop if we don’t align delimiters, but otherwise we’d // do superfluous work when aligning, so optimize for aligning. while (++rowIndex < rowLength) { cells = table[rowIndex]; columnIndex = -1; columnLength = cells.length; row = []; sizes = []; if (columnLength > mostCellsPerRow) { mostCellsPerRow = columnLength; } while (++columnIndex < columnLength) { cell = serialize(cells[columnIndex]); if (alignDelimiters === true) { size = stringLength(cell); sizes[columnIndex] = size; largest = longestCellByColumn[columnIndex]; if (largest === undefined || size > largest) { longestCellByColumn[columnIndex] = size; } } row.push(cell); } cellMatrix[rowIndex] = row; sizeMatrix[rowIndex] = sizes; } // Figure out which alignments to use. columnIndex = -1; columnLength = mostCellsPerRow; if (typeof align === 'object' && 'length' in align) { while (++columnIndex < columnLength) { alignments[columnIndex] = toAlignment(align[columnIndex]); } } else { code = toAlignment(align); while (++columnIndex < columnLength) { alignments[columnIndex] = code; } } // Inject the alignment row. columnIndex = -1; columnLength = mostCellsPerRow; row = []; sizes = []; while (++columnIndex < columnLength) { code = alignments[columnIndex]; before = ''; after = ''; if (code === l$1) { before = colon$1; } else if (code === r) { after = colon$1; } else if (code === c$1) { before = colon$1; after = colon$1; } // There *must* be at least one hyphen-minus in each alignment cell. size = alignDelimiters ? Math.max( 1, longestCellByColumn[columnIndex] - before.length - after.length ) : 1; cell = before + repeatString(dash$1, size) + after; if (alignDelimiters === true) { size = before.length + size + after.length; if (size > longestCellByColumn[columnIndex]) { longestCellByColumn[columnIndex] = size; } sizes[columnIndex] = size; } row[columnIndex] = cell; } // Inject the alignment row. cellMatrix.splice(1, 0, row); sizeMatrix.splice(1, 0, sizes); rowIndex = -1; rowLength = cellMatrix.length; lines = []; while (++rowIndex < rowLength) { row = cellMatrix[rowIndex]; sizes = sizeMatrix[rowIndex]; columnIndex = -1; columnLength = mostCellsPerRow; line = []; while (++columnIndex < columnLength) { cell = row[columnIndex] || ''; before = ''; after = ''; if (alignDelimiters === true) { size = longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0); code = alignments[columnIndex]; if (code === r) { before = repeatString(space, size); } else if (code === c$1) { if (size % 2 === 0) { before = repeatString(space, size / 2); after = before; } else { before = repeatString(space, size / 2 + 0.5); after = repeatString(space, size / 2 - 0.5); } } else { after = repeatString(space, size); } } if (start === true && columnIndex === 0) { line.push(verticalBar); } if ( padding === true && // Don’t add the opening space if we’re not aligning and the cell is // empty: there will be a closing space. !(alignDelimiters === false && cell === '') && (start === true || columnIndex !== 0) ) { line.push(space); } if (alignDelimiters === true) { line.push(before); } line.push(cell); if (alignDelimiters === true) { line.push(after); } if (padding === true) { line.push(space); } if (end === true || columnIndex !== columnLength - 1) { line.push(verticalBar); } } line = line.join(''); if (end === false) { line = line.replace(trailingWhitespace, ''); } lines.push(line); } return lines.join(lineFeed) } function serialize(value) { return value === null || value === undefined ? '' : String(value) } function defaultStringLength(value) { return value.length } function toAlignment(value) { var code = typeof value === 'string' ? value.charCodeAt(0) : x; return code === L$1 || code === l$1 ? l$1 : code === R || code === r ? r : code === C || code === c$1 ? c$1 : x } var toMarkdown_1 = toMarkdown$3; function toMarkdown$3(options) { var settings = options || {}; var padding = settings.tableCellPadding; var alignDelimiters = settings.tablePipeAlign; var stringLength = settings.stringLength; var around = padding ? ' ' : '|'; return { unsafe: [ {character: '\r', inConstruct: 'tableCell'}, {character: '\n', inConstruct: 'tableCell'}, // A pipe, when followed by a tab or space (padding), or a dash or colon // (unpadded delimiter row), could result in a table. {atBreak: true, character: '|', after: '[\t :-]'}, // A pipe in a cell must be encoded. {character: '|', inConstruct: 'tableCell'}, // A colon must be followed by a dash, in which case it could start a // delimiter row. {atBreak: true, character: ':', after: '-'}, // A delimiter row can also start with a dash, when followed by more // dashes, a colon, or a pipe. // This is a stricter version than the built in check for lists, thematic // breaks, and setex heading underlines though: // {atBreak: true, character: '-', after: '[:|-]'} ], handlers: { table: handleTable, tableRow: handleTableRow, tableCell: handleTableCell, inlineCode: inlineCodeWithTable } } function handleTable(node, _, context) { return serializeData(handleTableAsData(node, context), node.align) } // This function isn’t really used normally, because we handle rows at the // table level. // But, if someone passes in a table row, this ensures we make somewhat sense. function handleTableRow(node, _, context) { var row = handleTableRowAsData(node, context); // `markdown-table` will always add an align row var value = serializeData([row]); return value.slice(0, value.indexOf('\n')) } function handleTableCell(node, _, context) { var exit = context.enter('tableCell'); var value = containerPhrasing(node, context, {before: around, after: around}); exit(); return value } function serializeData(matrix, align) { return markdownTable_1(matrix, { align: align, alignDelimiters: alignDelimiters, padding: padding, stringLength: stringLength }) } function handleTableAsData(node, context) { var children = node.children; var index = -1; var length = children.length; var result = []; var subexit = context.enter('table'); while (++index < length) { result[index] = handleTableRowAsData(children[index], context); } subexit(); return result } function handleTableRowAsData(node, context) { var children = node.children; var index = -1; var length = children.length; var result = []; var subexit = context.enter('tableRow'); while (++index < length) { result[index] = handleTableCell(children[index], node, context); } subexit(); return result } function inlineCodeWithTable(node, parent, context) { var value = inlineCode_1(node); if (context.stack.indexOf('tableCell') !== -1) { value = value.replace(/\|/, '\\$&'); } return value } } var unsafe$3 = [{atBreak: true, character: '-', after: '[:|-]'}]; var handlers$1 = { listItem: listItemWithTaskListItem }; function listItemWithTaskListItem(node, parent, context) { var value = listItem_1(node, parent, context); var head = node.children[0]; if (typeof node.checked === 'boolean' && head && head.type === 'paragraph') { value = value.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/, check); } return value function check($0) { return $0 + '[' + (node.checked ? 'x' : ' ') + '] ' } } var toMarkdown$4 = { unsafe: unsafe$3, handlers: handlers$1 }; var toMarkdown_1$1 = toMarkdown$5; function toMarkdown$5(options) { var extensions = [ toMarkdown$1, toMarkdown$2, toMarkdown_1(options), toMarkdown$4 ]; var length = extensions.length; var index = -1; var extension; var unsafe = []; var handlers = {}; while (++index < length) { extension = extensions[index]; // istanbul ignore next - unsafe always exists, for now. unsafe = unsafe.concat(extension.unsafe || []); handlers = Object.assign(handlers, extension.handlers || {}); } return {unsafe: unsafe, handlers: handlers} } var warningIssued; var remarkGfm = gfm; function gfm(options) { var data = this.data(); /* istanbul ignore next - old remark. */ if ( !warningIssued && ((this.Parser && this.Parser.prototype && this.Parser.prototype.blockTokenizers) || (this.Compiler && this.Compiler.prototype && this.Compiler.prototype.visitors)) ) { warningIssued = true; console.warn( '[remark-gfm] Warning: please upgrade to remark 13 to use this plugin' ); } add('micromarkExtensions', micromarkExtensionGfm(options)); add('fromMarkdownExtensions', fromMarkdown$5); add('toMarkdownExtensions', toMarkdown_1$1(options)); function add(field, value) { /* istanbul ignore if - other extensions. */ if (data[field]) data[field].push(value); else data[field] = [value]; } } var proc = getCjsExportFromNamespace(_package$1); var cli = getCjsExportFromNamespace(_package$3); // To aid in future maintenance, this layout closely matches remark-cli/cli.js. // https://github.com/remarkjs/remark/blob/master/packages/remark-cli/cli.js unifiedArgs({ processor: remark().use(remarkGfm).use(remarkPresetLintNode), name: proc.name, description: cli.description, version: [ proc.name + ': ' + proc.version, cli.name + ': ' + cli.version, ].join(', '), pluginPrefix: proc.name, presetPrefix: proc.name + '-preset', packageField: proc.name + 'Config', rcName: '.' + proc.name + 'rc', ignoreName: '.' + proc.name + 'ignore', extensions: markdownExtensions$2, detectConfig: false, });