n(resultPromise); return dispose(resources, inspection); }); resources.promise = promise; promise._setOnCancel(resources); return promise; }; Promise.prototype._setDisposable = function (disposer) { this._bitField = this._bitField | 131072; this._disposer = disposer; }; Promise.prototype._isDisposable = function () { return (this._bitField & 131072) > 0; }; Promise.prototype._getDisposer = function () { return this._disposer; }; Promise.prototype._unsetDisposable = function () { this._bitField = this._bitField & (~131072); this._disposer = undefined; }; Promise.prototype.disposer = function (fn) { if (typeof fn === "function") { return new FunctionDisposer(fn, this, createContext()); } throw new TypeError(); }; }; var timers$1 = function(Promise, INTERNAL, debug) { var util$$1 = util$5; var TimeoutError = Promise.TimeoutError; function HandleWrapper(handle) { this.handle = handle; } HandleWrapper.prototype._resultCancelled = function() { clearTimeout(this.handle); }; var afterValue = function(value) { return delay(+this).thenReturn(value); }; var delay = Promise.delay = function (ms, value) { var ret; var handle; if (value !== undefined) { ret = Promise.resolve(value) ._then(afterValue, null, null, ms, undefined); if (debug.cancellation() && value instanceof Promise) { ret._setOnCancel(value); } } else { ret = new Promise(INTERNAL); handle = setTimeout(function() { ret._fulfill(); }, +ms); if (debug.cancellation()) { ret._setOnCancel(new HandleWrapper(handle)); } ret._captureStackTrace(); } ret._setAsyncGuaranteed(); return ret; }; Promise.prototype.delay = function (ms) { return delay(ms, this); }; var afterTimeout = function (promise, message, parent) { var err; if (typeof message !== "string") { if (message instanceof Error) { err = message; } else { err = new TimeoutError("operation timed out"); } } else { err = new TimeoutError(message); } util$$1.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); promise._reject(err); if (parent != null) { parent.cancel(); } }; function successClear(value) { clearTimeout(this.handle); return value; } function failureClear(reason) { clearTimeout(this.handle); throw reason; } Promise.prototype.timeout = function (ms, message) { ms = +ms; var ret, parent; var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { if (ret.isPending()) { afterTimeout(ret, message, parent); } }, ms)); if (debug.cancellation()) { parent = this.then(); ret = parent._then(successClear, failureClear, undefined, handleWrapper, undefined); ret._setOnCancel(handleWrapper); } else { ret = this._then(successClear, failureClear, undefined, handleWrapper, undefined); } return ret; }; }; var generators = function(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug) { var errors = errors$3; var TypeError = errors.TypeError; var util$$1 = util$5; var errorObj = util$$1.errorObj; var tryCatch = util$$1.tryCatch; var yieldHandlers = []; function promiseFromYieldHandler(value, yieldHandlers, traceParent) { for (var i = 0; i < yieldHandlers.length; ++i) { traceParent._pushContext(); var result = tryCatch(yieldHandlers[i])(value); traceParent._popContext(); if (result === errorObj) { traceParent._pushContext(); var ret = Promise.reject(errorObj.e); traceParent._popContext(); return ret; } var maybePromise = tryConvertToPromise(result, traceParent); if (maybePromise instanceof Promise) return maybePromise; } return null; } function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { if (debug.cancellation()) { var internal = new Promise(INTERNAL); var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); this._promise = internal.lastly(function() { return _finallyPromise; }); internal._captureStackTrace(); internal._setOnCancel(this); } else { var promise = this._promise = new Promise(INTERNAL); promise._captureStackTrace(); } this._stack = stack; this._generatorFunction = generatorFunction; this._receiver = receiver; this._generator = undefined; this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers; this._yieldedPromise = null; this._cancellationPhase = false; } util$$1.inherits(PromiseSpawn, Proxyable); PromiseSpawn.prototype._isResolved = function() { return this._promise === null; }; PromiseSpawn.prototype._cleanup = function() { this._promise = this._generator = null; if (debug.cancellation() && this._finallyPromise !== null) { this._finallyPromise._fulfill(); this._finallyPromise = null; } }; PromiseSpawn.prototype._promiseCancelled = function() { if (this._isResolved()) return; var implementsReturn = typeof this._generator["return"] !== "undefined"; var result; if (!implementsReturn) { var reason = new Promise.CancellationError( "generator .return() sentinel"); Promise.coroutine.returnSentinel = reason; this._promise._attachExtraTrace(reason); this._promise._pushContext(); result = tryCatch(this._generator["throw"]).call(this._generator, reason); this._promise._popContext(); } else { this._promise._pushContext(); result = tryCatch(this._generator["return"]).call(this._generator, undefined); this._promise._popContext(); } this._cancellationPhase = true; this._yieldedPromise = null; this._continue(result); }; PromiseSpawn.prototype._promiseFulfilled = function(value) { this._yieldedPromise = null; this._promise._pushContext(); var result = tryCatch(this._generator.next).call(this._generator, value); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._promiseRejected = function(reason) { this._yieldedPromise = null; this._promise._attachExtraTrace(reason); this._promise._pushContext(); var result = tryCatch(this._generator["throw"]) .call(this._generator, reason); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._resultCancelled = function() { if (this._yieldedPromise instanceof Promise) { var promise = this._yieldedPromise; this._yieldedPromise = null; promise.cancel(); } }; PromiseSpawn.prototype.promise = function () { return this._promise; }; PromiseSpawn.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver); this._receiver = this._generatorFunction = undefined; this._promiseFulfilled(undefined); }; PromiseSpawn.prototype._continue = function (result) { var promise = this._promise; if (result === errorObj) { this._cleanup(); if (this._cancellationPhase) { return promise.cancel(); } else { return promise._rejectCallback(result.e, false); } } var value = result.value; if (result.done === true) { this._cleanup(); if (this._cancellationPhase) { return promise.cancel(); } else { return promise._resolveCallback(value); } } else { var maybePromise = tryConvertToPromise(value, this._promise); if (!(maybePromise instanceof Promise)) { maybePromise = promiseFromYieldHandler(maybePromise, this._yieldHandlers, this._promise); if (maybePromise === null) { this._promiseRejected( new TypeError( "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) ); return; } } maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; if (((bitField & 50397184) === 0)) { this._yieldedPromise = maybePromise; maybePromise._proxy(this, null); } else if (((bitField & 33554432) !== 0)) { Promise._async.invoke( this._promiseFulfilled, this, maybePromise._value() ); } else if (((bitField & 16777216) !== 0)) { Promise._async.invoke( this._promiseRejected, this, maybePromise._reason() ); } else { this._promiseCancelled(); } } }; Promise.coroutine = function (generatorFunction, options) { if (typeof generatorFunction !== "function") { throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var yieldHandler = Object(options).yieldHandler; var PromiseSpawn$ = PromiseSpawn; var stack = new Error().stack; return function () { var generator = generatorFunction.apply(this, arguments); var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack); var ret = spawn.promise(); spawn._generator = generator; spawn._promiseFulfilled(undefined); return ret; }; }; Promise.coroutine.addYieldHandler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util$$1.classString(fn)); } yieldHandlers.push(fn); }; Promise.spawn = function (generatorFunction) { debug.deprecated("Promise.spawn()", "Promise.coroutine()"); if (typeof generatorFunction !== "function") { return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var spawn = new PromiseSpawn(generatorFunction, this); var ret = spawn.promise(); spawn._run(Promise.spawn); return ret; }; }; var nodeify = function(Promise) { var util$$1 = util$5; var async = Promise._async; var tryCatch = util$$1.tryCatch; var errorObj = util$$1.errorObj; function spreadAdapter(val, nodeback) { var promise = this; if (!util$$1.isArray(val)) return successAdapter.call(promise, val, nodeback); var ret = tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); if (ret === errorObj) { async.throwLater(ret.e); } } function successAdapter(val, nodeback) { var promise = this; var receiver = promise._boundValue(); var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val); if (ret === errorObj) { async.throwLater(ret.e); } } function errorAdapter(reason, nodeback) { var promise = this; if (!reason) { var newReason = new Error(reason + ""); newReason.cause = reason; reason = newReason; } var ret = tryCatch(nodeback).call(promise._boundValue(), reason); if (ret === errorObj) { async.throwLater(ret.e); } } Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) { if (typeof nodeback == "function") { var adapter = successAdapter; if (options !== undefined && Object(options).spread) { adapter = spreadAdapter; } this._then( adapter, errorAdapter, undefined, this, nodeback ); } return this; }; }; var promisify = function(Promise, INTERNAL) { var THIS = {}; var util$$1 = util$5; var nodebackForPromise = nodeback; var withAppended = util$$1.withAppended; var maybeWrapAsError = util$$1.maybeWrapAsError; var canEvaluate = util$$1.canEvaluate; var TypeError = errors$3.TypeError; var defaultSuffix = "Async"; var defaultPromisified = {__isPromisified__: true}; var noCopyProps = [ "arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__" ]; var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); var defaultFilter = function(name) { return util$$1.isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor"; }; function propsFilter(key) { return !noCopyPropsPattern.test(key); } function isPromisified(fn) { try { return fn.__isPromisified__ === true; } catch (e) { return false; } } function hasPromisified(obj, key, suffix) { var val = util$$1.getDataPropertyOrDefault(obj, key + suffix, defaultPromisified); return val ? isPromisified(val) : false; } function checkValid(ret, suffix, suffixRegexp) { for (var i = 0; i < ret.length; i += 2) { var key = ret[i]; if (suffixRegexp.test(key)) { var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); for (var j = 0; j < ret.length; j += 2) { if (ret[j] === keyWithoutAsyncSuffix) { throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" .replace("%s", suffix)); } } } } } function promisifiableMethods(obj, suffix, suffixRegexp, filter) { var keys = util$$1.inheritedDataKeys(obj); var ret = []; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var value = obj[key]; var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj); if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && filter(key, value, obj, passesDefaultFilter)) { ret.push(key, value); } } checkValid(ret, suffix, suffixRegexp); return ret; } var escapeIdentRegex = function(str) { return str.replace(/([$])/, "\\$"); }; var makeNodePromisifiedEval; { var switchCaseArgumentOrder = function(likelyArgumentCount) { var ret = [likelyArgumentCount]; var min = Math.max(0, likelyArgumentCount - 1 - 3); for(var i = likelyArgumentCount - 1; i >= min; --i) { ret.push(i); } for(var i = likelyArgumentCount + 1; i <= 3; ++i) { ret.push(i); } return ret; }; var argumentSequence = function(argumentCount) { return util$$1.filledRange(argumentCount, "_arg", ""); }; var parameterDeclaration = function(parameterCount) { return util$$1.filledRange( Math.max(parameterCount, 3), "_arg", ""); }; var parameterCount = function(fn) { if (typeof fn.length === "number") { return Math.max(Math.min(fn.length, 1023 + 1), 0); } return 0; }; makeNodePromisifiedEval = function(callback, receiver, originalName, fn, _, multiArgs) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); var shouldProxyThis = typeof callback === "string" || receiver === THIS; function generateCallForArgumentCount(count) { var args = argumentSequence(count).join(", "); var comma = count > 0 ? ", " : ""; var ret; if (shouldProxyThis) { ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; } else { ret = receiver === undefined ? "ret = callback({{args}}, nodeback); break;\n" : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; } return ret.replace("{{args}}", args).replace(", ", comma); } function generateArgumentSwitchCase() { var ret = ""; for (var i = 0; i < argumentOrder.length; ++i) { ret += "case " + argumentOrder[i] +":" + generateCallForArgumentCount(argumentOrder[i]); } ret += " \n\ default: \n\ var args = new Array(len + 1); \n\ var i = 0; \n\ for (var i = 0; i < len; ++i) { \n\ args[i] = arguments[i]; \n\ } \n\ args[i] = nodeback; \n\ [CodeForCall] \n\ break; \n\ ".replace("[CodeForCall]", (shouldProxyThis ? "ret = callback.apply(this, args);\n" : "ret = callback.apply(receiver, args);\n")); return ret; } var getFunctionCode = typeof callback === "string" ? ("this != null ? this['"+callback+"'] : fn") : "fn"; var body = "'use strict'; \n\ var ret = function (Parameters) { \n\ 'use strict'; \n\ var len = arguments.length; \n\ var promise = new Promise(INTERNAL); \n\ promise._captureStackTrace(); \n\ var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ var ret; \n\ var callback = tryCatch([GetFunctionCode]); \n\ switch(len) { \n\ [CodeForSwitchCase] \n\ } \n\ if (ret === errorObj) { \n\ promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ } \n\ if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ return promise; \n\ }; \n\ notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) .replace("[GetFunctionCode]", getFunctionCode); body = body.replace("Parameters", parameterDeclaration(newParameterCount)); return new Function("Promise", "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", "tryCatch", "errorObj", "notEnumerableProp", "INTERNAL", body)( Promise, fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, util$$1.tryCatch, util$$1.errorObj, util$$1.notEnumerableProp, INTERNAL); }; } function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { var defaultThis = (function() {return this;})(); var method = callback; if (typeof method === "string") { callback = fn; } function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; var promise = new Promise(INTERNAL); promise._captureStackTrace(); var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback; var fn = nodebackForPromise(promise, multiArgs); try { cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { promise._rejectCallback(maybeWrapAsError(e), true, true); } if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); return promise; } util$$1.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); for (var i = 0, len = methods.length; i < len; i+= 2) { var key = methods[i]; var fn = methods[i+1]; var promisifiedKey = key + suffix; if (promisifier === makeNodePromisified) { obj[promisifiedKey] = makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); } else { var promisified = promisifier(fn, function() { return makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); }); util$$1.notEnumerableProp(promisified, "__isPromisified__", true); obj[promisifiedKey] = promisified; } } util$$1.toFastProperties(obj); return obj; } function promisify(callback, receiver, multiArgs) { return makeNodePromisified(callback, receiver, undefined, callback, null, multiArgs); } Promise.promisify = function (fn, options) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util$$1.classString(fn)); } if (isPromisified(fn)) { return fn; } options = Object(options); var receiver = options.context === undefined ? THIS : options.context; var multiArgs = !!options.multiArgs; var ret = promisify(fn, receiver, multiArgs); util$$1.copyDescriptors(fn, ret, propsFilter); return ret; }; Promise.promisifyAll = function (target, options) { if (typeof target !== "function" && typeof target !== "object") { throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } options = Object(options); var multiArgs = !!options.multiArgs; var suffix = options.suffix; if (typeof suffix !== "string") suffix = defaultSuffix; var filter = options.filter; if (typeof filter !== "function") filter = defaultFilter; var promisifier = options.promisifier; if (typeof promisifier !== "function") promisifier = makeNodePromisified; if (!util$$1.isIdentifier(suffix)) { throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var keys = util$$1.inheritedDataKeys(target); for (var i = 0; i < keys.length; ++i) { var value = target[keys[i]]; if (keys[i] !== "constructor" && util$$1.isClass(value)) { promisifyAll(value.prototype, suffix, filter, promisifier, multiArgs); promisifyAll(value, suffix, filter, promisifier, multiArgs); } } return promisifyAll(target, suffix, filter, promisifier, multiArgs); }; }; var props = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { var util$$1 = util$5; var isObject = util$$1.isObject; var es5$$2 = es5; var Es6Map; if (typeof Map === "function") Es6Map = Map; var mapToEntries = (function() { var index = 0; var size = 0; function extractEntry(value, key) { this[index] = value; this[index + size] = key; index++; } return function mapToEntries(map) { size = map.size; index = 0; var ret = new Array(map.size * 2); map.forEach(extractEntry, ret); return ret; }; })(); var entriesToMap = function(entries) { var ret = new Es6Map(); var length = entries.length / 2 | 0; for (var i = 0; i < length; ++i) { var key = entries[length + i]; var value = entries[i]; ret.set(key, value); } return ret; }; function PropertiesPromiseArray(obj) { var isMap = false; var entries; if (Es6Map !== undefined && obj instanceof Es6Map) { entries = mapToEntries(obj); isMap = true; } else { var keys = es5$$2.keys(obj); var len = keys.length; entries = new Array(len * 2); for (var i = 0; i < len; ++i) { var key = keys[i]; entries[i] = obj[key]; entries[i + len] = key; } } this.constructor$(entries); this._isMap = isMap; this._init$(undefined, isMap ? -6 : -3); } util$$1.inherits(PropertiesPromiseArray, PromiseArray); PropertiesPromiseArray.prototype._init = function () {}; PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { var val; if (this._isMap) { val = entriesToMap(this._values); } else { val = {}; var keyOffset = this.length(); for (var i = 0, len = this.length(); i < len; ++i) { val[this._values[i + keyOffset]] = this._values[i]; } } this._resolve(val); return true; } return false; }; PropertiesPromiseArray.prototype.shouldCopyValues = function () { return false; }; PropertiesPromiseArray.prototype.getActualLength = function (len) { return len >> 1; }; function props(promises) { var ret; var castValue = tryConvertToPromise(promises); if (!isObject(castValue)) { return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } else if (castValue instanceof Promise) { ret = castValue._then( Promise.props, undefined, undefined, undefined, undefined); } else { ret = new PropertiesPromiseArray(castValue).promise(); } if (castValue instanceof Promise) { ret._propagateFrom(castValue, 2); } return ret; } Promise.prototype.props = function () { return props(this); }; Promise.props = function (promises) { return props(promises); }; }; var race = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { var util$$1 = util$5; var raceLater = function (promise) { return promise.then(function(array) { return race(array, promise); }); }; function race(promises, parent) { var maybePromise = tryConvertToPromise(promises); if (maybePromise instanceof Promise) { return raceLater(maybePromise); } else { promises = util$$1.asArray(promises); if (promises === null) return apiRejection("expecting an array or an iterable object but got " + util$$1.classString(promises)); } var ret = new Promise(INTERNAL); if (parent !== undefined) { ret._propagateFrom(parent, 3); } var fulfill = ret._fulfill; var reject = ret._reject; for (var i = 0, len = promises.length; i < len; ++i) { var val = promises[i]; if (val === undefined && !(i in promises)) { continue; } Promise.cast(val)._then(fulfill, reject, undefined, ret, null); } return ret; } Promise.race = function (promises) { return race(promises, undefined); }; Promise.prototype.race = function () { return race(this, undefined); }; }; var reduce = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util$$1 = util$5; var tryCatch = util$$1.tryCatch; function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); var domain = getDomain(); this._fn = domain === null ? fn : util$$1.domainBind(domain, fn); if (initialValue !== undefined) { initialValue = Promise.resolve(initialValue); initialValue._attachCancellationCallback(this); } this._initialValue = initialValue; this._currentCancellable = null; if(_each === INTERNAL) { this._eachValues = Array(this._length); } else if (_each === 0) { this._eachValues = null; } else { this._eachValues = undefined; } this._promise._captureStackTrace(); this._init$(undefined, -5); } util$$1.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._gotAccum = function(accum) { if (this._eachValues !== undefined && this._eachValues !== null && accum !== INTERNAL) { this._eachValues.push(accum); } }; ReductionPromiseArray.prototype._eachComplete = function(value) { if (this._eachValues !== null) { this._eachValues.push(value); } return this._eachValues; }; ReductionPromiseArray.prototype._init = function() {}; ReductionPromiseArray.prototype._resolveEmptyArray = function() { this._resolve(this._eachValues !== undefined ? this._eachValues : this._initialValue); }; ReductionPromiseArray.prototype.shouldCopyValues = function () { return false; }; ReductionPromiseArray.prototype._resolve = function(value) { this._promise._resolveCallback(value); this._values = null; }; ReductionPromiseArray.prototype._resultCancelled = function(sender) { if (sender === this._initialValue) return this._cancel(); if (this._isResolved()) return; this._resultCancelled$(); if (this._currentCancellable instanceof Promise) { this._currentCancellable.cancel(); } if (this._initialValue instanceof Promise) { this._initialValue.cancel(); } }; ReductionPromiseArray.prototype._iterate = function (values) { this._values = values; var value; var i; var length = values.length; if (this._initialValue !== undefined) { value = this._initialValue; i = 0; } else { value = Promise.resolve(values[0]); i = 1; } this._currentCancellable = value; if (!value.isRejected()) { for (; i < length; ++i) { var ctx = { accum: null, value: values[i], index: i, length: length, array: this }; value = value._then(gotAccum, undefined, undefined, ctx, undefined); } } if (this._eachValues !== undefined) { value = value ._then(this._eachComplete, undefined, undefined, this, undefined); } value._then(completed, completed, undefined, value, this); }; Promise.prototype.reduce = function (fn, initialValue) { return reduce(this, fn, initialValue, null); }; Promise.reduce = function (promises, fn, initialValue, _each) { return reduce(promises, fn, initialValue, _each); }; function completed(valueOrReason, array) { if (this.isFulfilled()) { array._resolve(valueOrReason); } else { array._reject(valueOrReason); } } function reduce(promises, fn, initialValue, _each) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util$$1.classString(fn)); } var array = new ReductionPromiseArray(promises, fn, initialValue, _each); return array.promise(); } function gotAccum(accum) { this.accum = accum; this.array._gotAccum(accum); var value = tryConvertToPromise(this.value, this.array._promise); if (value instanceof Promise) { this.array._currentCancellable = value; return value._then(gotValue, undefined, undefined, this, undefined); } else { return gotValue.call(this, value); } } function gotValue(value) { var array = this.array; var promise = array._promise; var fn = tryCatch(array._fn); promise._pushContext(); var ret; if (array._eachValues !== undefined) { ret = fn.call(promise._boundValue(), value, this.index, this.length); } else { ret = fn.call(promise._boundValue(), this.accum, value, this.index, this.length); } if (ret instanceof Promise) { array._currentCancellable = ret; } var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", promise ); return ret; } }; var settle = function(Promise, PromiseArray, debug) { var PromiseInspection = Promise.PromiseInspection; var util$$1 = util$5; function SettledPromiseArray(values) { this.constructor$(values); } util$$1.inherits(SettledPromiseArray, PromiseArray); SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { this._values[index] = inspection; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); ret._bitField = 33554432; ret._settledValueField = value; return this._promiseResolved(index, ret); }; SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); ret._bitField = 16777216; ret._settledValueField = reason; return this._promiseResolved(index, ret); }; Promise.settle = function (promises) { debug.deprecated(".settle()", ".reflect()"); return new SettledPromiseArray(promises).promise(); }; Promise.prototype.settle = function () { return Promise.settle(this); }; }; var some = function(Promise, PromiseArray, apiRejection) { var util$$1 = util$5; var RangeError = errors$3.RangeError; var AggregateError = errors$3.AggregateError; var isArray = util$$1.isArray; var CANCELLATION = {}; function SomePromiseArray(values) { this.constructor$(values); this._howMany = 0; this._unwrap = false; this._initialized = false; } util$$1.inherits(SomePromiseArray, PromiseArray); SomePromiseArray.prototype._init = function () { if (!this._initialized) { return; } if (this._howMany === 0) { this._resolve([]); return; } this._init$(undefined, -5); var isArrayResolved = isArray(this._values); if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) { this._reject(this._getRangeError(this.length())); } }; SomePromiseArray.prototype.init = function () { this._initialized = true; this._init(); }; SomePromiseArray.prototype.setUnwrap = function () { this._unwrap = true; }; SomePromiseArray.prototype.howMany = function () { return this._howMany; }; SomePromiseArray.prototype.setHowMany = function (count) { this._howMany = count; }; SomePromiseArray.prototype._promiseFulfilled = function (value) { this._addFulfilled(value); if (this._fulfilled() === this.howMany()) { this._values.length = this.howMany(); if (this.howMany() === 1 && this._unwrap) { this._resolve(this._values[0]); } else { this._resolve(this._values); } return true; } return false; }; SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); return this._checkOutcome(); }; SomePromiseArray.prototype._promiseCancelled = function () { if (this._values instanceof Promise || this._values == null) { return this._cancel(); } this._addRejected(CANCELLATION); return this._checkOutcome(); }; SomePromiseArray.prototype._checkOutcome = function() { if (this.howMany() > this._canPossiblyFulfill()) { var e = new AggregateError(); for (var i = this.length(); i < this._values.length; ++i) { if (this._values[i] !== CANCELLATION) { e.push(this._values[i]); } } if (e.length > 0) { this._reject(e); } else { this._cancel(); } return true; } return false; }; SomePromiseArray.prototype._fulfilled = function () { return this._totalResolved; }; SomePromiseArray.prototype._rejected = function () { return this._values.length - this.length(); }; SomePromiseArray.prototype._addRejected = function (reason) { this._values.push(reason); }; SomePromiseArray.prototype._addFulfilled = function (value) { this._values[this._totalResolved++] = value; }; SomePromiseArray.prototype._canPossiblyFulfill = function () { return this.length() - this._rejected(); }; SomePromiseArray.prototype._getRangeError = function (count) { var message = "Input array must contain at least " + this._howMany + " items but contains only " + count + " items"; return new RangeError(message); }; SomePromiseArray.prototype._resolveEmptyArray = function () { this._reject(this._getRangeError(0)); }; function some(promises, howMany) { if ((howMany | 0) !== howMany || howMany < 0) { return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(howMany); ret.init(); return promise; } Promise.some = function (promises, howMany) { return some(promises, howMany); }; Promise.prototype.some = function (howMany) { return some(this, howMany); }; Promise._SomePromiseArray = SomePromiseArray; }; var filter$1 = function(Promise, INTERNAL) { var PromiseMap = Promise.map; Promise.prototype.filter = function (fn, options) { return PromiseMap(this, fn, options, INTERNAL); }; Promise.filter = function (promises, fn, options) { return PromiseMap(promises, fn, options, INTERNAL); }; }; var each = function(Promise, INTERNAL) { var PromiseReduce = Promise.reduce; var PromiseAll = Promise.all; function promiseAllThis() { return PromiseAll(this); } function PromiseMapSeries(promises, fn) { return PromiseReduce(promises, fn, INTERNAL, INTERNAL); } Promise.prototype.each = function (fn) { return PromiseReduce(this, fn, INTERNAL, 0) ._then(promiseAllThis, undefined, undefined, this, undefined); }; Promise.prototype.mapSeries = function (fn) { return PromiseReduce(this, fn, INTERNAL, INTERNAL); }; Promise.each = function (promises, fn) { return PromiseReduce(promises, fn, INTERNAL, 0) ._then(promiseAllThis, undefined, undefined, promises, undefined); }; Promise.mapSeries = PromiseMapSeries; }; var any = function(Promise) { var SomePromiseArray = Promise._SomePromiseArray; function any(promises) { var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(1); ret.setUnwrap(); ret.init(); return promise; } Promise.any = function (promises) { return any(promises); }; Promise.prototype.any = function () { return any(this); }; }; var promise = createCommonjsModule(function (module) { "use strict"; module.exports = function() { var makeSelfResolutionError = function () { return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var reflectHandler = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; function Proxyable() {} var UNDEFINED_BINDING = {}; var util$$1 = util$5; var getDomain; if (util$$1.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util$$1.notEnumerableProp(Promise, "_getDomain", getDomain); var es5$$1 = es5; var Async = async$3; var async = new Async(); es5$$1.defineProperty(Promise, "_async", {value: async}); var errors = errors$3; var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; var CancellationError = Promise.CancellationError = errors.CancellationError; Promise.TimeoutError = errors.TimeoutError; Promise.OperationalError = errors.OperationalError; Promise.RejectionError = errors.OperationalError; Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {}; var tryConvertToPromise = thenables(Promise, INTERNAL); var PromiseArray = promise_array(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); var Context = context(Promise); /*jshint unused:false*/ var createContext = Context.create; var debug = debuggability(Promise, Context); var CapturedTrace = debug.CapturedTrace; var PassThroughHandlerContext = _finally(Promise, tryConvertToPromise, NEXT_FILTER); var catchFilter = catch_filter(NEXT_FILTER); var nodebackForPromise = nodeback; var errorObj = util$$1.errorObj; var tryCatch = util$$1.tryCatch; function check(self, executor) { if (self == null || self.constructor !== Promise) { throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (typeof executor !== "function") { throw new TypeError("expecting a function but got " + util$$1.classString(executor)); } } function Promise(executor) { if (executor !== INTERNAL) { check(this, executor); } this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; this._resolveFromExecutor(executor); this._promiseCreated(); this._fireEvent("promiseCreated", this); } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util$$1.isObject(item)) { catchInstances[j++] = item; } else { return apiRejection("Catch statement predicate: " + "expecting an object but got " + util$$1.classString(item)); } } catchInstances.length = j; fn = arguments[i]; return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); }; Promise.prototype.reflect = function () { return this._then(reflectHandler, reflectHandler, undefined, this, undefined); }; Promise.prototype.then = function (didFulfill, didReject) { if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util$$1.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util$$1.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, undefined, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject) { var promise = this._then(didFulfill, didReject, undefined, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util$$1.classString(fn)); } return this.all()._then(fn, undefined, undefined, APPLY, undefined); }; Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, fulfillmentValue: undefined, rejectionReason: undefined }; if (this.isFulfilled()) { ret.fulfillmentValue = this.value(); ret.isFulfilled = true; } else if (this.isRejected()) { ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; Promise.prototype.all = function () { if (arguments.length > 0) { this._warn(".all() was passed arguments but it does not take any"); } return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util$$1.originatesFromRejection, fn); }; Promise.getNewLibraryCopy = module.exports; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = Promise.fromCallback = function(fn) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); if (result === errorObj) { ret._rejectCallback(result.e, true); } if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util$$1.classString(fn)); } return async.setScheduler(fn); }; Promise.prototype._then = function ( didFulfill, didReject, _, receiver, internalData ) { var haveInternalData = internalData !== undefined; var promise = haveInternalData ? internalData : new Promise(INTERNAL); var target = this._target(); var bitField = target._bitField; if (!haveInternalData) { promise._propagateFrom(this, 3); promise._captureStackTrace(); if (receiver === undefined && ((this._bitField & 2097152) !== 0)) { if (!((bitField & 50397184) === 0)) { receiver = this._boundValue(); } else { receiver = target === this ? undefined : this._boundTo; } } this._fireEvent("promiseChained", this, promise); } var domain = getDomain(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { value = target._rejectionHandler0; handler = didFulfill; } else if (((bitField & 16777216) !== 0)) { value = target._fulfillmentHandler0; handler = didReject; target._unsetRejectionIsUnhandled(); } else { settler = target._settlePromiseLateCancellationObserver; value = new CancellationError("late cancellation observer"); target._attachExtraTrace(value); handler = didReject; } async.invoke(settler, target, { handler: domain === null ? handler : (typeof handler === "function" && util$$1.domainBind(domain, handler)), promise: promise, receiver: receiver, value: value }); } else { target._addCallbacks(didFulfill, didReject, promise, receiver, domain); } return promise; }; Promise.prototype._length = function () { return this._bitField & 65535; }; Promise.prototype._isFateSealed = function () { return (this._bitField & 117506048) !== 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 67108864) === 67108864; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -65536) | (len & 65535); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 33554432; this._fireEvent("promiseFulfilled", this); }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 16777216; this._fireEvent("promiseRejected", this); }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 67108864; this._fireEvent("promiseResolved", this); }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._isFinal = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._unsetCancelled = function() { this._bitField = this._bitField & (~65536); }; Promise.prototype._setCancelled = function() { this._bitField = this._bitField | 65536; this._fireEvent("promiseCancelled", this); }; Promise.prototype._setWillBeCancelled = function() { this._bitField = this._bitField | 8388608; }; Promise.prototype._setAsyncGuaranteed = function() { if (async.hasCustomScheduler()) return; this._bitField = this._bitField | 134217728; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 4 - 4 + 3]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return this[ index * 4 - 4 + 2]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return this[ index * 4 - 4 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return this[ index * 4 - 4 + 1]; }; Promise.prototype._boundValue = function() {}; Promise.prototype._migrateCallback0 = function (follower) { var bitField = follower._bitField; var fulfill = follower._fulfillmentHandler0; var reject = follower._rejectionHandler0; var promise = follower._promise0; var receiver = follower._receiverAt(0); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._migrateCallbackAt = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, promise, receiver, domain ) { var index = this._length(); if (index >= 65535 - 4) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { this._fulfillmentHandler0 = domain === null ? fulfill : util$$1.domainBind(domain, fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : util$$1.domainBind(domain, reject); } } else { var base = index * 4 - 4; this[base + 2] = promise; this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : util$$1.domainBind(domain, fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : util$$1.domainBind(domain, reject); } } this._setLength(index + 1); return index; }; Promise.prototype._proxy = function (proxyable, arg) { this._addCallbacks(undefined, undefined, arg, proxyable, null); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (((this._bitField & 117506048) !== 0)) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); if (shouldBind) this._propagateFrom(maybePromise, 2); var promise = maybePromise._target(); if (promise === this) { this._reject(makeSelfResolutionError()); return; } var bitField = promise._bitField; if (((bitField & 50397184) === 0)) { var len = this._length(); if (len > 0) promise._migrateCallback0(this); for (var i = 1; i < len; ++i) { promise._migrateCallbackAt(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { this._reject(promise._reason()); } else { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); this._reject(reason); } }; Promise.prototype._rejectCallback = function(reason, synchronous, ignoreNonErrorWarnings) { var trace = util$$1.ensureErrorObject(reason); var hasStack = trace === reason; if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { var message = "a promise was rejected with a non-error: " + util$$1.classString(reason); this._warn(message, true); } this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason); }; Promise.prototype._resolveFromExecutor = function (executor) { if (executor === INTERNAL) return; var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = this._execute(executor, function(value) { promise._resolveCallback(value); }, function (reason) { promise._rejectCallback(reason, synchronous); }); synchronous = false; this._popContext(); if (r !== undefined) { promise._rejectCallback(r, true); } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { var bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; promise._pushContext(); var x; if (receiver === APPLY) { if (!value || typeof value.length !== "number") { x = errorObj; x.e = new TypeError("cannot .spread() a non-array: " + util$$1.classString(value)); } else { x = tryCatch(handler).apply(this._boundValue(), value); } } else { x = tryCatch(handler).call(receiver, value); } var promiseCreated = promise._popContext(); bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; if (x === NEXT_FILTER) { promise._reject(value); } else if (x === errorObj) { promise._rejectCallback(x.e, false); } else { debug.checkForgottenReturns(x, promiseCreated, "", promise, this); promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { this._rejectionHandler0 = promise; }; Promise.prototype._settlePromise = function(promise, handler, receiver, value) { var isPromise = promise instanceof Promise; var bitField = this._bitField; var asyncGuaranteed = ((bitField & 134217728) !== 0); if (((bitField & 65536) !== 0)) { if (isPromise) promise._invokeInternalOnCancel(); if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) { receiver.cancelPromise = promise; if (tryCatch(handler).call(receiver, value) === errorObj) { promise._reject(errorObj.e); } } else if (handler === reflectHandler) { promise._fulfill(reflectHandler.call(receiver)); } else if (receiver instanceof Proxyable) { receiver._promiseCancelled(promise); } else if (isPromise || promise instanceof PromiseArray) { promise._cancel(); } else { receiver.cancel(); } } else if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { if (asyncGuaranteed) promise._setAsyncGuaranteed(); this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof Proxyable) { if (!receiver._isResolved()) { if (((bitField & 33554432) !== 0)) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (asyncGuaranteed) promise._setAsyncGuaranteed(); if (((bitField & 33554432) !== 0)) { promise._fulfill(value); } else { promise._reject(value); } } }; Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { var handler = ctx.handler; var promise = ctx.promise; var receiver = ctx.receiver; var value = ctx.value; if (typeof handler === "function") { if (!(promise instanceof Promise)) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (promise instanceof Promise) { promise._reject(value); } }; Promise.prototype._settlePromiseCtx = function(ctx) { this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); }; Promise.prototype._settlePromise0 = function(handler, value, bitField) { var promise = this._promise0; var receiver = this._receiverAt(0); this._promise0 = undefined; this._receiver0 = undefined; this._settlePromise(promise, handler, receiver, value); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { var base = index * 4 - 4; this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; }; Promise.prototype._fulfill = function (value) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._reject(err); } this._setFulfilled(); this._rejectionHandler0 = value; if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } } }; Promise.prototype._reject = function (reason) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; this._setRejected(); this._fulfillmentHandler0 = reason; if (this._isFinal()) { return async.fatalError(reason, util$$1.isNode); } if ((bitField & 65535) > 0) { async.settlePromises(this); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._fulfillPromises = function (len, value) { for (var i = 1; i < len; i++) { var handler = this._fulfillmentHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, value); } }; Promise.prototype._rejectPromises = function (len, reason) { for (var i = 1; i < len; i++) { var handler = this._rejectionHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, reason); } }; Promise.prototype._settlePromises = function () { var bitField = this._bitField; var len = (bitField & 65535); if (len > 0) { if (((bitField & 16842752) !== 0)) { var reason = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, reason, bitField); this._rejectPromises(len, reason); } else { var value = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, value, bitField); this._fulfillPromises(len, value); } this._setLength(0); } this._clearCancellationData(); }; Promise.prototype._settledValue = function() { var bitField = this._bitField; if (((bitField & 33554432) !== 0)) { return this._rejectionHandler0; } else if (((bitField & 16777216) !== 0)) { return this._fulfillmentHandler0; } }; function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} Promise.defer = Promise.pending = function() { debug.deprecated("Promise.defer", "new Promise"); var promise = new Promise(INTERNAL); return { promise: promise, resolve: deferResolve, reject: deferReject }; }; util$$1.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); method(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); bind(Promise, INTERNAL, tryConvertToPromise, debug); cancel(Promise, PromiseArray, apiRejection, debug); direct_resolve(Promise); synchronous_inspection(Promise); join$9( Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); Promise.Promise = Promise; Promise.version = "3.5.0"; map(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); call_get(Promise); using(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); timers$1(Promise, INTERNAL, debug); generators(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); nodeify(Promise); promisify(Promise, INTERNAL); props(Promise, PromiseArray, tryConvertToPromise, apiRejection); race(Promise, INTERNAL, tryConvertToPromise, apiRejection); reduce(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); settle(Promise, PromiseArray, debug); some(Promise, PromiseArray, apiRejection); filter$1(Promise, INTERNAL); each(Promise, INTERNAL); any(Promise); util$$1.toFastProperties(Promise); util$$1.toFastProperties(Promise.prototype); function fillTypes(value) { var p = new Promise(INTERNAL); p._fulfillmentHandler0 = value; p._rejectionHandler0 = value; p._promise0 = value; p._receiver0 = value; } // Complete slack tracking, opt out of field-type tracking and // stabilize map fillTypes({a: 1}); fillTypes({b: 2}); fillTypes({c: 3}); fillTypes(1); fillTypes(function(){}); fillTypes(undefined); fillTypes(false); fillTypes(new Promise(INTERNAL)); debug.setBounds(Async.firstLineError, util$$1.lastLineError); return Promise; }; }); var old; if (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = promise(); bluebird.noConflict = noConflict; var bluebird_1 = bluebird; // Based on iniparser by shockie <https://npmjs.org/package/iniparser> /* * get the file handler */ /* * define the possible values: * section: [section] * param: key=value * comment: ;this is a comment */ var regex = { section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/, param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/, comment: /^\s*[#;].*$/ }; /* * parses a .ini file * @param: {String} file, the location of the .ini file * @param: {Function} callback, the function that will be called when parsing is done * @return: none */ var parse_1 = function (file, callback) { if (!callback) { return; } fs.readFile(file, 'utf8', function (err, data) { if (err) { callback(err); } else { callback(null, parse(data)); } }); }; var parseSync$1 = function (file) { return parse(fs.readFileSync(file, 'utf8')); }; var parseString$1 = function (data) { var sectionBody = {}; var sectionName = null; var value = [[sectionName, sectionBody]]; var lines = data.split(/\r\n|\r|\n/); lines.forEach(function (line) { var match; if (regex.comment.test(line)) { return; } else if (regex.param.test(line)) { match = line.match(regex.param); sectionBody[match[1]] = match[2]; } else if (regex.section.test(line)) { match = line.match(regex.section); sectionName = match[1]; sectionBody = {}; value.push([sectionName, sectionBody]); } }); return value; }; var ini = { parse: parse_1, parseSync: parseSync$1, parseString: parseString$1 }; var hasOwnProperty = Object.prototype.hasOwnProperty; var pseudomap = PseudoMap; function PseudoMap (set) { if (!(this instanceof PseudoMap)) // whyyyyyyy throw new TypeError("Constructor PseudoMap requires 'new'") this.clear(); if (set) { if ((set instanceof PseudoMap) || (typeof Map === 'function' && set instanceof Map)) set.forEach(function (value, key) { this.set(key, value); }, this); else if (Array.isArray(set)) set.forEach(function (kv) { this.set(kv[0], kv[1]); }, this); else throw new TypeError('invalid argument') } } PseudoMap.prototype.forEach = function (fn, thisp) { thisp = thisp || this; Object.keys(this._data).forEach(function (k) { if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key); }, this); }; PseudoMap.prototype.has = function (k) { return !!find(this._data, k) }; PseudoMap.prototype.get = function (k) { var res = find(this._data, k); return res && res.value }; PseudoMap.prototype.set = function (k, v) { set(this._data, k, v); }; PseudoMap.prototype.delete = function (k) { var res = find(this._data, k); if (res) { delete this._data[res._index]; this._data.size--; } }; PseudoMap.prototype.clear = function () { var data = Object.create(null); data.size = 0; Object.defineProperty(this, '_data', { value: data, enumerable: false, configurable: true, writable: false }); }; Object.defineProperty(PseudoMap.prototype, 'size', { get: function () { return this._data.size }, set: function (n) {}, enumerable: true, configurable: true }); PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () { throw new Error('iterators are not implemented in this version') }; // Either identical, or both NaN function same (a, b) { return a === b || a !== a && b !== b } function Entry$1 (k, v, i) { this.key = k; this.value = v; this._index = i; } function find (data, k) { for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) { if (same(data[key].key, k)) return data[key] } } function set (data, k, v) { for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) { if (same(data[key].key, k)) { data[key].value = v; return } } data.size++; data[key] = new Entry$1(k, v, key); } var map$2 = createCommonjsModule(function (module) { if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true'; if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) { module.exports = Map; } else { module.exports = pseudomap; } }); var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it, // or a fakey-fake PseudoMap in older versions. function naiveLength () { return 1 } function LRUCache (options) { if (!(this instanceof LRUCache)) return new LRUCache(options) if (typeof options === 'number') options = { max: options }; if (!options) options = {}; this._max = options.max; // Kind of weird to have a default max of Infinity, but oh well. if (!this._max || !(typeof this._max === "number") || this._max <= 0 ) this._max = Infinity; this._lengthCalculator = options.length || naiveLength; if (typeof this._lengthCalculator !== "function") this._lengthCalculator = naiveLength; this._allowStale = options.stale || false; this._maxAge = options.maxAge || null; this._dispose = options.dispose; this.reset(); } // resize the cache when the max changes. Object.defineProperty(LRUCache.prototype, "max", { set : function (mL) { if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity; this._max = mL; if (this._length > this._max) trim(this); } , get : function () { return this._max } , enumerable : true }); // resize the cache when the lengthCalculator changes. Object.defineProperty(LRUCache.prototype, "lengthCalculator", { set : function (lC) { if (typeof lC !== "function") { this._lengthCalculator = naiveLength; this._length = this._lruList.size; this._cache.forEach(function (value, key) { value.length = 1; }); } else { this._lengthCalculator = lC; this._length = 0; this._cache.forEach(function (value, key) { value.length = this._lengthCalculator(value.value, key); this._length += value.length; }, this); } if (this._length > this._max) trim(this); } , get : function () { return this._lengthCalculator } , enumerable : true }); Object.defineProperty(LRUCache.prototype, "length", { get : function () { return this._length } , enumerable : true }); Object.defineProperty(LRUCache.prototype, "itemCount", { get : function () { return this._lruList.size } , enumerable : true }); function reverseKeys (map) { // keys live in lruList map in insertion order. // we want them in reverse insertion order. // flip the list of keys. var itemCount = map.size; var keys = new Array(itemCount); var i = itemCount; map.forEach(function (value, key) { keys[--i] = key; }); return keys } LRUCache.prototype.rforEach = function (fn, thisp) { thisp = thisp || this; this._lruList.forEach(function (hit) { forEachStep(this, fn, hit, thisp); }, this); }; function forEachStep (self, fn, hit, thisp) { if (isStale(self, hit)) { del(self, hit); if (!self._allowStale) { hit = undefined; } } if (hit) { fn.call(thisp, hit.value, hit.key, self); } } LRUCache.prototype.forEach = function (fn, thisp) { thisp = thisp || this; var keys = reverseKeys(this._lruList); for (var k = 0; k < keys.length; k++) { var hit = this._lruList.get(keys[k]); forEachStep(this, fn, hit, thisp); } }; LRUCache.prototype.keys = function () { return reverseKeys(this._lruList).map(function (k) { return this._lruList.get(k).key }, this) }; LRUCache.prototype.values = function () { return reverseKeys(this._lruList).map(function (k) { return this._lruList.get(k).value }, this) }; LRUCache.prototype.reset = function () { if (this._dispose && this._cache) { this._cache.forEach(function (entry, key) { this._dispose(key, entry.value); }, this); } this._cache = new map$2(); // hash of items by key this._lruList = new map$2(); // list of items in order of use recency this._mru = 0; // most recently used this._lru = 0; // least recently used this._length = 0; // number of items in the list }; LRUCache.prototype.dump = function () { var arr = []; var i = 0; var size = this._lruList.size; return reverseKeys(this._lruList).map(function (k) { var hit = this._lruList.get(k); if (!isStale(this, hit)) { return { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) } } }, this).filter(function (h) { return h }) }; LRUCache.prototype.dumpLru = function () { return this._lruList }; LRUCache.prototype.set = function (key, value, maxAge) { maxAge = maxAge || this._maxAge; var now = maxAge ? Date.now() : 0; var len = this._lengthCalculator(value, key); if (this._cache.has(key)) { if (len > this._max) { del(this, this._cache.get(key)); return false } var item = this._cache.get(key); // dispose of the old one before overwriting if (this._dispose) this._dispose(key, item.value); item.now = now; item.maxAge = maxAge; item.value = value; this._length += (len - item.length); item.length = len; this.get(key); if (this._length > this._max) trim(this); return true } var hit = new Entry(key, value, this._mru, len, now, maxAge); incMru(this); // oversized objects fall out of cache automatically. if (hit.length > this._max) { if (this._dispose) this._dispose(key, value); return false } this._length += hit.length; this._cache.set(key, hit); this._lruList.set(hit.lu, hit); if (this._length > this._max) trim(this); return true }; LRUCache.prototype.has = function (key) { if (!this._cache.has(key)) return false var hit = this._cache.get(key); if (isStale(this, hit)) { return false } return true }; LRUCache.prototype.get = function (key) { return get(this, key, true) }; LRUCache.prototype.peek = function (key) { return get(this, key, false) }; LRUCache.prototype.pop = function () { var hit = this._lruList.get(this._lru); del(this, hit); return hit || null }; LRUCache.prototype.del = function (key) { del(this, this._cache.get(key)); }; LRUCache.prototype.load = function (arr) { //reset the cache this.reset(); var now = Date.now(); // A previous serialized cache has the most recent items first for (var l = arr.length - 1; l >= 0; l--) { var hit = arr[l]; var expiresAt = hit.e || 0; if (expiresAt === 0) { // the item was created without expiration in a non aged cache this.set(hit.k, hit.v); } else { var maxAge = expiresAt - now; // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge); } } } }; function get (self, key, doUse) { var hit = self._cache.get(key); if (hit) { if (isStale(self, hit)) { del(self, hit); if (!self._allowStale) hit = undefined; } else { if (doUse) use(self, hit); } if (hit) hit = hit.value; } return hit } function isStale(self, hit) { if (!hit || (!hit.maxAge && !self._maxAge)) return false var stale = false; var diff = Date.now() - hit.now; if (hit.maxAge) { stale = diff > hit.maxAge; } else { stale = self._maxAge && (diff > self._maxAge); } return stale; } function use (self, hit) { shiftLU(self, hit); hit.lu = self._mru; incMru(self); self._lruList.set(hit.lu, hit); } function trim (self) { if (self._length > self._max) { var keys = reverseKeys(self._lruList); for (var k = keys.length - 1; self._length > self._max; k--) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. self._lru = keys[k - 1]; del(self, self._lruList.get(keys[k])); } } } function shiftLU (self, hit) { self._lruList.delete(hit.lu); if (hit.lu === self._lru) self._lru = reverseKeys(self._lruList).pop(); } function del (self, hit) { if (hit) { if (self._dispose) self._dispose(hit.key, hit.value); self._length -= hit.length; self._cache.delete(hit.key); shiftLU(self, hit); } } // classy, since V8 prefers predictable objects. function Entry (key, value, lu, length, now, maxAge) { this.key = key; this.value = value; this.lu = lu; this.length = length; this.now = now; if (maxAge) this.maxAge = maxAge; } // Incrementers and decrementers that loop at MAX_SAFE_INTEGER // only relevant for the lu, lru, and mru counters, since they // get touched a lot and can get very large. Also, since they // only go upwards, and the sets will tend to be much smaller than // the max, we can very well assume that a very small number comes // after a very large number, rather than before it. var maxSafeInt = Number.MAX_SAFE_INTEGER || 9007199254740991; function intInc (number) { return (number === maxSafeInt) ? 0 : number + 1 } function incMru (self) { do { self._mru = intInc(self._mru); } while (self._lruList.has(self._mru)) } var sigmund_1 = sigmund; function sigmund (subject, maxSessions) { maxSessions = maxSessions || 10; var notes = []; var analysis = ''; var RE = RegExp; function psychoAnalyze (subject, session) { if (session > maxSessions) return; if (typeof subject === 'function' || typeof subject === 'undefined') { return; } if (typeof subject !== 'object' || !subject || (subject instanceof RE)) { analysis += subject; return; } if (notes.indexOf(subject) !== -1 || session === maxSessions) return; notes.push(subject); analysis += '{'; Object.keys(subject).forEach(function (issue, _, __) { // pseudo-private values. skip those. if (issue.charAt(0) === '_') return; var to = typeof subject[issue]; if (to === 'function' || to === 'undefined') return; analysis += issue; psychoAnalyze(subject[issue], session + 1); }); } psychoAnalyze(subject, 0); return analysis; } // vim: set softtabstop=4 shiftwidth=4: var fnmatch$1 = createCommonjsModule(function (module, exports) { // Based on minimatch.js by isaacs <https://npmjs.org/package/minimatch> var platform = typeof process === "object" ? process.platform : "win32"; if (module) module.exports = minimatch; else exports.minimatch = minimatch; minimatch.Minimatch = Minimatch; var cache = minimatch.cache = new lruCache({max: 100}) , GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}; var qmark = "[^/]" // * => any number of characters , 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. , twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot, // followed by anything, any number of times. , twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp. , 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.monkeyPatch = monkeyPatch; function monkeyPatch () { var desc = Object.getOwnPropertyDescriptor(String.prototype, "match"); var orig = desc.value; desc.value = function (p) { if (p instanceof Minimatch) return p.match(this) return orig.call(this, p) }; Object.defineProperty(String.prototype, desc); } 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, cache) } if (typeof pattern !== "string") { throw new TypeError("glob pattern string required") } if (!options) options = {}; // windows: need to use /, not \ // On other platforms, \ is a valid (albeit bad) filename char. if (platform === "win32") { pattern = pattern.split("\\").join("/"); } // lru storage. // these things aren't particularly big, but walking down the string // and turning it into a regexp can get pretty costly. var cacheKey = pattern + "\n" + sigmund_1(options); var cached = minimatch.cache.get(cacheKey); if (cached) return cached minimatch.cache.set(cacheKey, this); 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.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) console.error(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) }); if (options.debug) console.error(this.pattern, set); // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this); if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly. set = set.filter(function (s) { return -1 === s.indexOf(false) }); if (options.debug) console.error(this.pattern, set); this.set = set; } Minimatch.prototype.parseNegate = parseNegate; function parseNegate () { var pattern = this.pattern , negate = false , options = this.options , 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 new Minimatch(pattern, options).braceExpand() }; Minimatch.prototype.braceExpand = braceExpand; function braceExpand (pattern, options) { options = options || this.options; pattern = typeof pattern === "undefined" ? this.pattern : pattern; if (typeof pattern === "undefined") { throw new Error("undefined pattern") } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } var escaping = false; // examples and comments refer to this crazy pattern: // a{b,c{d,e},{f,g}h}x{y,z} // expected: // abxy // abxz // acdxy // acdxz // acexy // acexz // afhxy // afhxz // aghxy // aghxz // everything before the first \{ is just a prefix. // So, we pluck that off, and work with the rest, // and then prepend it to everything we find. if (pattern.charAt(0) !== "{") { // console.error(pattern) var prefix = null; for (var i = 0, l = pattern.length; i < l; i ++) { var c = pattern.charAt(i); // console.error(i, c) if (c === "\\") { escaping = !escaping; } else if (c === "{" && !escaping) { prefix = pattern.substr(0, i); break } } // actually no sets, all { were escaped. if (prefix === null) { // console.error("no sets") return [pattern] } var tail = braceExpand(pattern.substr(i), options); return tail.map(function (t) { return prefix + t }) } // now we have something like: // {b,c{d,e},{f,g}h}x{y,z} // walk through the set, expanding each part, until // the set ends. then, we'll expand the suffix. // If the set only has a single member, then'll put the {} back // first, handle numeric sets, since they're easier var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/); if (numset) { // console.error("numset", numset[1], numset[2]) var suf = braceExpand(pattern.substr(numset[0].length), options) , start = +numset[1] , end = +numset[2] , inc = start > end ? -1 : 1 , set = []; for (var i = start; i != (end + inc); i += inc) { // append all the suffixes for (var ii = 0, ll = suf.length; ii < ll; ii ++) { set.push(i + suf[ii]); } } return set } // ok, walk through the set // We hope, somewhat optimistically, that there // will be a } at the end. // If the closing brace isn't found, then the pattern is // interpreted as braceExpand("\\" + pattern) so that // the leading \{ will be interpreted literally. var i = 1 // skip the \{ , depth = 1 , set = [] , member = "" , sawEnd = false , escaping = false; function addMember () { set.push(member); member = ""; } // console.error("Entering for") FOR: for (i = 1, l = pattern.length; i < l; i ++) { var c = pattern.charAt(i); // console.error("", i, c) if (escaping) { escaping = false; member += "\\" + c; } else { switch (c) { case "\\": escaping = true; continue case "{": depth ++; member += "{"; continue case "}": depth --; // if this closes the actual set, then we're done if (depth === 0) { addMember(); // pluck off the close-brace i ++; break FOR } else { member += c; continue } case ",": if (depth === 1) { addMember(); } else { member += c; } continue default: member += c; continue } // switch } // else } // for // now we've either finished the set, and the suffix is // pattern.substr(i), or we have *not* closed the set, // and need to escape the leading brace if (depth !== 0) { // console.error("didn't close", pattern) return braceExpand("\\" + pattern, options) } // x{y,z} -> ["xy", "xz"] // console.error("set", set) // console.error("suffix", pattern.substr(i)) var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] -> // [["b"], ["cd", "ce"], ["fh", "gh"]] var addBraces = set.length === 1; // console.error("set pre-expanded", set) set = set.map(function (p) { return braceExpand(p, options) }); // console.error("set expanded", set) // [["b"], ["cd", "ce"], ["fh", "gh"]] -> // ["b", "cd", "ce", "fh", "gh"] set = set.reduce(function (l, r) { return l.concat(r) }); if (addBraces) { set = set.map(function (s) { return "{" + s + "}" }); } // now attach the suffixes. var ret = []; for (var i = 0, l = set.length; i < l; i ++) { for (var ii = 0, ll = suf.length; ii < ll; ii ++) { ret.push(set[i] + suf[ii]); } } return ret } // 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; var SUBPARSE = {}; function parse (pattern, isSub) { var options = this.options; // shortcuts if (!options.noglobstar && pattern === "**") return GLOBSTAR if (pattern === "") return "" var re = "" , hasMagic = !!options.nocase , escaping = false // ? => one single character , patternListStack = [] , plType , stateChar , inClass = false , reClassStart = -1 , classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. , patternStart = pattern.charAt(0) === "." ? "" // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)"; 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 } stateChar = false; } } for ( var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i ++ ) { if (options.debug) { console.error("%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: 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 "!": if (options.debug) { console.error("%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) { 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. 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 } plType = stateChar; patternListStack.push({ type: plType , start: i - 1 , reStart: re.length }); // negation is (?:(?!js)[^/]*) re += stateChar === "!" ? "(?:(?!" : "(?:"; stateChar = false; continue case ")": if (inClass || !patternListStack.length) { re += "\\)"; continue } hasMagic = true; re += ")"; plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*) // The others are (?:<pattern>)<type> switch (plType) { case "!": re += "[^/]*?)"; break case "?": case "+": case "*": re += plType; case "@": break // the default anyway } continue case "|": if (inClass || !patternListStack.length || escaping) { re += "\\|"; escaping = false; continue } 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 } // 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 var 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. var pl; while (pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2})*)(\\?)\|/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 + "|" }); // console.error("tail=%j\n %s", tail, tail) 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; } // 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" : "" , regExp = new RegExp("^" + re + "$", flags); 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) return this.regexp = false var options = this.options; var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot , 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 { return this.regexp = new RegExp(re, flags) } catch (ex) { return this.regexp = false } } minimatch.match = function (list, pattern, options) { var mm = new Minimatch(pattern, options); list = list.filter(function (f) { return mm.match(f) }); if (options.nonull && !list.length) { list.push(pattern); } return list }; Minimatch.prototype.match = match; function match (f, partial) { // console.error("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 \ // On other platforms, \ is a valid (albeit bad) filename char. if (platform === "win32") { f = f.split("\\").join("/"); } // treat the test path as a set of pathparts. f = f.split(slashSplit); if (options.debug) { console.error(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; // console.error(this.pattern, "set", set) for (var i = 0, l = set.length; i < l; i ++) { var pattern = set[i]; var hit = this.matchOne(f, 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; if (options.debug) { console.error("matchOne", { "this": this , file: file , pattern: pattern }); } if (options.matchBase && pattern.length === 1) { file = path.basename(file.join("/")).split("/"); } if (options.debug) { console.error("matchOne", file.length, pattern.length); } for ( var fi = 0 , pi = 0 , fl = file.length , pl = pattern.length ; (fi < fl) && (pi < pl) ; fi ++, pi ++ ) { if (options.debug) { console.error("matchOne loop"); } var p = pattern[pi] , f = file[fi]; if (options.debug) { console.error(pattern, p, f); } // should be impossible. // some invalid regexp stuff in the set. if (p === false) return false if (p === GLOBSTAR) { if (options.debug) console.error('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 , pr = pi + 1; if (pr === pl) { if (options.debug) console.error('** 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: while (fr < fl) { var swallowee = file[fr]; if (options.debug) { console.error('\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)) { if (options.debug) console.error('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) === ".")) { if (options.debug) console.error("dot detected!", file, fr, pattern, pr); break WHILE } // ** swallows a segment, and continue. if (options.debug) console.error('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 // console.error("\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; } if (options.debug) { console.error("string match", p, f, hit); } } else { hit = f.match(p); if (options.debug) { console.error("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 name$1 = "editorconfig"; var version$2 = "0.14.2"; var description$1 = "EditorConfig File Locator and Interpreter for Node.js"; var keywords = ["editorconfig","core"]; var main$1 = "editorconfig.js"; var bin$1 = {"editorconfig":"bin/editorconfig"}; var contributors = ["Hong Xu (topbug.net)","Jed Mao (https://github.com/jedmao/)","Trey Hunner (http://treyhunner.com)"]; var directories = {"bin":"./bin","lib":"./lib"}; var scripts$1 = {"pretest":"cmake .","test":"npm run lint && ctest .","test-verbose":"npm run lint && ctest -VV --output-on-failure .","lint":"eclint check --indent_size ignore editorconfig.js README.md \"bin/**\" \"lib/**\""}; var repository$1 = {"type":"git","url":"git://github.com/editorconfig/editorconfig-core-js.git"}; var bugs$1 = "https://github.com/editorconfig/editorconfig-core-js/issues"; var author$1 = "EditorConfig Team"; var license$1 = "MIT"; var dependencies$1 = {"bluebird":"^3.0.5","commander":"^2.9.0","lru-cache":"^3.2.0","semver":"^5.1.0","sigmund":"^1.0.1"}; var devDependencies$1 = {"eclint":"^1.1.5","mocha":"^2.3.4","should":"^7.1.1"}; var _package$2 = { name: name$1, version: version$2, description: description$1, keywords: keywords, main: main$1, bin: bin$1, contributors: contributors, directories: directories, scripts: scripts$1, repository: repository$1, bugs: bugs$1, author: author$1, license: license$1, dependencies: dependencies$1, devDependencies: devDependencies$1 }; var _package$3 = Object.freeze({ name: name$1, version: version$2, description: description$1, keywords: keywords, main: main$1, bin: bin$1, contributors: contributors, directories: directories, scripts: scripts$1, repository: repository$1, bugs: bugs$1, author: author$1, license: license$1, dependencies: dependencies$1, devDependencies: devDependencies$1, default: _package$2 }); var pkg = ( _package$3 && _package$2 ) || _package$3; var whenReadFile = bluebird_1.promisify(fs.readFile); var knownProps = [ 'end_of_line', 'indent_style', 'indent_size', 'insert_final_newline', 'trim_trailing_whitespace', 'charset' ].reduce(function (set, prop) { set[prop] = true; return set; }, {}); function fnmatch(filepath, glob) { var matchOptions = {matchBase: true, dot: true, noext: true}; glob = glob.replace(/\*\*/g, '{*,**/**/**}'); return fnmatch$1(filepath, glob, matchOptions); } function getConfigFileNames(filepath, options) { var paths = []; do { filepath = path.dirname(filepath); paths.push(path.join(filepath, options.config)); } while (filepath !== options.root); return paths; } function getFilepathRoot(filepath) { if (path.parse !== undefined) { // Node.js >= 0.11.15 return path.parse(filepath).root; } if (os.platform() === 'win32') { return path.resolve(filepath).match(/^(\\\\[^\\]+\\)?[^\\]+\\/)[0]; } return '/'; } function processMatches(matches, version) { // Set indent_size to "tab" if indent_size is unspecified and // indent_style is set to "tab". if ("indent_style" in matches && matches.indent_style === "tab" && !("indent_size" in matches) && semver.gte(version, "0.10.0")) { matches.indent_size = "tab"; } // Set tab_width to indent_size if indent_size is specified and // tab_width is unspecified if ("indent_size" in matches && !("tab_width" in matches) && matches.indent_size !== "tab") matches.tab_width = matches.indent_size; // Set indent_size to tab_width if indent_size is "tab" if("indent_size" in matches && "tab_width" in matches && matches.indent_size === "tab") matches.indent_size = matches.tab_width; return matches; } function processOptions(options, filepath) { options = options || {}; return { config: options.config || '.editorconfig', version: options.version || pkg.version, root: path.resolve(options.root || getFilepathRoot(filepath)) }; } function buildFullGlob(pathPrefix, glob) { switch (glob.indexOf('/')) { case -1: glob = "**/" + glob; break; case 0: glob = glob.substring(1); break; } return path.join(pathPrefix, glob); } function extendProps(props, options) { for (var key in options) { var value = options[key]; key = key.toLowerCase(); if (knownProps[key]) { value = value.toLowerCase(); } try { value = JSON.parse(value); } catch(e) {} if (typeof value === 'undefined' || value === null) { // null and undefined are values specific to JSON (no special meaning // in editorconfig) & should just be returned as regular strings. value = String(value); } props[key] = value; } return props; } function parseFromFiles(filepath, files, options) { return getConfigsForFiles(files).then(function (configs) { return configs.reverse(); }).reduce(function (matches, file) { var pathPrefix = path.dirname(file.name); file.contents.forEach(function (section) { var glob = section[0], options = section[1]; if (!glob) return; var fullGlob = buildFullGlob(pathPrefix, glob); if (!fnmatch(filepath, fullGlob)) return; matches = extendProps(matches, options); }); return matches; }, {}).then(function (matches) { return processMatches(matches, options.version); }); } function parseFromFilesSync(filepath, files, options) { var configs = getConfigsForFilesSync(files); configs.reverse(); var matches = {}; configs.forEach(function(config) { var pathPrefix = path.dirname(config.name); config.contents.forEach(function(section) { var glob = section[0], options = section[1]; if (!glob) return; var fullGlob = buildFullGlob(pathPrefix, glob); if (!fnmatch(filepath, fullGlob)) return; matches = extendProps(matches, options); }); }); return processMatches(matches, options.version); } function StopReduce(array) { this.array = array; } StopReduce.prototype = Object.create(Error.prototype); function getConfigsForFiles(files) { return bluebird_1.reduce(files, function (configs, file) { var contents = ini.parseString(file.contents); configs.push({ name: file.name, contents: contents }); if ((contents[0][1].root || '').toLowerCase() === 'true') { return bluebird_1.reject(new StopReduce(configs)); } return configs; }, []).catch(StopReduce, function (stop) { return stop.array; }); } function getConfigsForFilesSync(files) { var configs = []; for (var i in files) { var file = files[i]; var contents = ini.parseString(file.contents); configs.push({ name: file.name, contents: contents }); if ((contents[0][1].root || '').toLowerCase() === 'true') { break; } } return configs; } function readConfigFiles(filepaths) { return bluebird_1.map(filepaths, function (path$$2) { return whenReadFile(path$$2, 'utf-8').catch(function () { return ''; }).then(function (contents) { return {name: path$$2, contents: contents}; }); }); } function readConfigFilesSync(filepaths) { var files = []; var file; filepaths.forEach(function(filepath) { try { file = fs.readFileSync(filepath, 'utf8'); } catch (e) { file = ''; } files.push({name: filepath, contents: file}); }); return files; } var parseFromFiles_1 = function (filepath, files, options) { return new bluebird_1 (function (resolve, reject) { filepath = path.resolve(filepath); options = processOptions(options, filepath); resolve(parseFromFiles(filepath, files, options)); }); }; var parseFromFilesSync_1 = function (filepath, files, options) { filepath = path.resolve(filepath); options = processOptions(options, filepath); return parseFromFilesSync(filepath, files, options); }; var parse$6 = function (filepath, options) { return new bluebird_1 (function (resolve, reject) { filepath = path.resolve(filepath); options = processOptions(options, filepath); var filepaths = getConfigFileNames(filepath, options); var files = readConfigFiles(filepaths); resolve(parseFromFiles(filepath, files, options)); }); }; var parseSync = function (filepath, options) { filepath = path.resolve(filepath); options = processOptions(options, filepath); var filepaths = getConfigFileNames(filepath, options); var files = readConfigFilesSync(filepaths); return parseFromFilesSync(filepath, files, options); }; var parseString = ini.parseString; var editorconfig = { parseFromFiles: parseFromFiles_1, parseFromFilesSync: parseFromFilesSync_1, parse: parse$6, parseSync: parseSync, parseString: parseString }; var editorconfigToPrettier = editorConfigToPrettier; function editorConfigToPrettier(editorConfig) { if (!editorConfig || Object.keys(editorConfig).length === 0) { return null; } const result = {}; if (editorConfig.indent_style) { result.useTabs = editorConfig.indent_style === "tab"; } if (editorConfig.indent_size === "tab") { result.useTabs = true; } if (result.useTabs && editorConfig.tab_width) { result.tabWidth = editorConfig.tab_width; } else if ( editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab" ) { result.tabWidth = editorConfig.indent_size; } else if (editorConfig.tab_width !== undefined) { result.tabWidth = editorConfig.tab_width; } if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") { result.printWidth = editorConfig.max_line_length; } if (editorConfig.quote_type === "single") { result.singleQuote = true; } else if (editorConfig.quote_type === "double") { result.singleQuote = false; } return result; } function markerExists (files, markers) { return markers.some(function(marker) { return files.some(function(file) { return file === marker; }); }); } function traverseFolder (directory, levels, markers) { var files = fs.readdirSync(directory); if (levels === 0) { return null; } else if (markerExists(files, markers)) { return directory; } else { return traverseFolder(path.resolve(directory, '..'), levels - 1, markers); } } var findProjectRoot = function findRoot(dir, opts) { if (!dir) throw new Error("Directory not defined"); opts = opts || {}; var levels = opts.maxDepth || findRoot.MAX_DEPTH; var markers = opts.markers || findRoot.MARKERS; return traverseFolder(dir, levels, markers); }; var MAX_DEPTH = 9; var MARKERS = [ '.git', '.hg' ]; findProjectRoot.MAX_DEPTH = MAX_DEPTH; findProjectRoot.MARKERS = MARKERS; var resolveConfigEditorconfig = createCommonjsModule(function (module) { "use strict"; const maybeParse = (filePath, config, parse) => { const root = findProjectRoot(path.dirname(path.resolve(filePath))); return filePath && parse(filePath, { root }); }; const editorconfigAsyncNoCache = (filePath, config) => { return Promise.resolve(maybeParse(filePath, config, editorconfig.parse)).then( editorconfigToPrettier ); }; const editorconfigAsyncWithCache = mem(editorconfigAsyncNoCache); const editorconfigSyncNoCache = (filePath, config) => { return editorconfigToPrettier( maybeParse(filePath, config, editorconfig.parseSync) ); }; const editorconfigSyncWithCache = mem(editorconfigSyncNoCache); function getLoadFunction(opts) { if (!opts.editorconfig) { return () => null; } if (opts.sync) { return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache; } return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache; } function clearCache() { mem.clear(editorconfigSyncWithCache); mem.clear(editorconfigAsyncWithCache); } module.exports = { getLoadFunction, clearCache }; }); var thirdParty$1 = ( thirdParty && thirdParty__default ) || thirdParty; var resolveConfig_1 = createCommonjsModule(function (module) { "use strict"; const getExplorerMemoized = mem(opts => thirdParty$1.cosmiconfig("prettier", { sync: opts.sync, cache: opts.cache, rcExtensions: true, transform: result => { if (result && result.config) { delete result.config.$schema; } return result; } }) ); /** @param {{ cache: boolean, sync: boolean }} opts */ function getLoadFunction(opts) { // Normalize opts before passing to a memoized function opts = Object.assign({ sync: false, cache: false }, opts); return getExplorerMemoized(opts).load; } function _resolveConfig(filePath, opts, sync) { opts = Object.assign({ useCache: true }, opts); const loadOpts = { cache: !!opts.useCache, sync: !!sync, editorconfig: !!opts.editorconfig }; const load = getLoadFunction(loadOpts); const loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts); const arr = [load, loadEditorConfig].map(l => l(filePath, opts.config)); const unwrapAndMerge = arr => { const result = arr[0]; const editorConfigured = arr[1]; const merged = Object.assign( {}, editorConfigured, mergeOverrides(Object.assign({}, result), filePath) ); if (!result && !editorConfigured) { return null; } return merged; }; if (loadOpts.sync) { return unwrapAndMerge(arr); } return Promise.all(arr).then(unwrapAndMerge); } const resolveConfig = (filePath, opts) => _resolveConfig(filePath, opts, false); resolveConfig.sync = (filePath, opts) => _resolveConfig(filePath, opts, true); function clearCache() { mem.clear(getExplorerMemoized); resolveConfigEditorconfig.clearCache(); } function resolveConfigFile(filePath) { const load = getLoadFunction({ sync: false }); return load(filePath).then(result => { return result ? result.filepath : null; }); } resolveConfigFile.sync = filePath => { const load = getLoadFunction({ sync: true }); const result = load(filePath); return result ? result.filepath : null; }; function mergeOverrides(configResult, filePath) { const options = Object.assign({}, configResult.config); if (filePath && options.overrides) { const relativeFilePath = path.relative( path.dirname(configResult.filepath), filePath ); for (const override of options.overrides) { if ( pathMatchesGlobs( relativeFilePath, override.files, override.excludeFiles ) ) { Object.assign(options, override.options); } } } delete options.overrides; return options; } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js function pathMatchesGlobs(filePath, patterns, excludedPatterns) { const patternList = [].concat(patterns); const excludedPatternList = [].concat(excludedPatterns || []); const opts = { matchBase: true }; return ( patternList.some(pattern => minimatch_1(filePath, pattern, opts)) && !excludedPatternList.some(excludedPattern => minimatch_1(filePath, excludedPattern, opts) ) ); } module.exports = { resolveConfig, resolveConfigFile, clearCache }; }); const version = require$$0$11.version; const getSupportInfo = support.getSupportInfo; const normalizeOptions = options$12.normalize; const printDocToString = doc.printer.printDocToString; const printDocToDebug = doc.debug.printDocToDebug; function guessLineEnding(text) { const index = text.indexOf("\n"); if (index >= 0 && text.charAt(index - 1) === "\r") { return "\r\n"; } return "\n"; } function attachComments(text, ast, opts) { const astComments = ast.comments; if (astComments) { delete ast.comments; comments.attach(astComments, ast, text, opts); } ast.tokens = []; opts.originalText = text.trimRight(); return astComments; } function hasPragma(text) { const pragmas = Object.keys(build.parse(build.extract(text))); return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1; } function ensureAllCommentsPrinted(astComments) { if (!astComments) { return; } for (let i = 0; i < astComments.length; ++i) { if (astComments[i].value.trim() === "prettier-ignore") { // If there's a prettier-ignore, we're not printing that sub-tree so we // don't know if the comments was printed or not. return; } } astComments.forEach(comment => { if (!comment.printed) { throw new Error( 'Comment "' + comment.value.trim() + '" was not printed. Please report this error!' ); } delete comment.printed; }); } function formatWithCursor(text, opts, addAlignmentSize) { if (opts.requirePragma && !hasPragma(text)) { return { formatted: text }; } const UTF8BOM = 0xfeff; const hasUnicodeBOM = text.charCodeAt(0) === UTF8BOM; if (hasUnicodeBOM) { text = text.substring(1); } if ( opts.insertPragma && !hasPragma(text) && opts.rangeStart === 0 && opts.rangeEnd === Infinity ) { const parsedDocblock = build.parseWithComments(build.extract(text)); const pragmas = Object.assign({ format: "" }, parsedDocblock.pragmas); const newDocblock = build.print({ pragmas, comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines }); const strippedText = build.strip(text); const separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n"; text = newDocblock + separatingNewlines + strippedText; } addAlignmentSize = addAlignmentSize || 0; const result = parser$3.parse(text, opts); const ast = result.ast; text = result.text; const formattedRangeOnly = formatRange(text, opts, ast); if (formattedRangeOnly) { return { formatted: formattedRangeOnly }; } let cursorOffset; if (opts.cursorOffset >= 0) { const cursorNodeAndParents = findNodeAtOffset(ast, opts.cursorOffset, opts); const cursorNode = cursorNodeAndParents.node; if (cursorNode) { cursorOffset = opts.cursorOffset - opts.locStart(cursorNode); opts.cursorNode = cursorNode; } } const astComments = attachComments(text, ast, opts); const doc$$1 = astToDoc(ast, opts, addAlignmentSize); opts.newLine = guessLineEnding(text); const toStringResult = printDocToString(doc$$1, opts); let str = toStringResult.formatted; if (hasUnicodeBOM) { str = String.fromCharCode(UTF8BOM) + str; } const cursorOffsetResult = toStringResult.cursor; ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline if (addAlignmentSize > 0) { return { formatted: str.trim() + opts.newLine }; } if (cursorOffset !== undefined) { return { formatted: str, cursorOffset: cursorOffsetResult + cursorOffset }; } return { formatted: str }; } function format(text, opts, addAlignmentSize) { return formatWithCursor(text, opts, addAlignmentSize).formatted; } function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { let resultStartNode = startNodeAndParents.node; let resultEndNode = endNodeAndParents.node; if (resultStartNode === resultEndNode) { return { startNode: resultStartNode, endNode: resultEndNode }; } for (const endParent of endNodeAndParents.parentNodes) { if ( endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node) ) { resultEndNode = endParent; } else { break; } } for (const startParent of startNodeAndParents.parentNodes) { if ( startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node) ) { resultStartNode = startParent; } else { break; } } return { startNode: resultStartNode, endNode: resultEndNode }; } function findNodeAtOffset(node, offset, options, predicate, parentNodes) { predicate = predicate || (() => true); parentNodes = parentNodes || []; const start = options.locStart(node, options.locStart); const end = options.locEnd(node, options.locEnd); if (start <= offset && offset <= end) { for (const childNode of comments.getSortedChildNodes( node, undefined /* text */, options )) { const childResult = findNodeAtOffset( childNode, offset, options, predicate, [node].concat(parentNodes) ); if (childResult) { return childResult; } } if (predicate(node)) { return { node: node, parentNodes: parentNodes }; } } } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 function isSourceElement(opts, node) { if (node == null) { return false; } // JS and JS like to avoid repetitions const jsSourceElements = [ "FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015 "ImportDeclaration", // Module "ExportDefaultDeclaration", // Module "ExportNamedDeclaration", // Module "ExportAllDeclaration", // Module "TypeAlias", // Flow "InterfaceDeclaration", // Flow, TypeScript "TypeAliasDeclaration", // TypeScript "ExportAssignment", // TypeScript "ExportDeclaration" // TypeScript ]; const jsonSourceElements = [ "ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral" ]; const graphqlSourceElements = [ "OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition" ]; switch (opts.parser) { case "flow": case "babylon": case "typescript": return jsSourceElements.indexOf(node.type) > -1; case "json": return jsonSourceElements.indexOf(node.type) > -1; case "graphql": return graphqlSourceElements.indexOf(node.kind) > -1; } return false; } function calculateRange(text, opts, ast) { // Contract the range so that it has non-whitespace characters at its endpoints. // This ensures we can format a range that doesn't end on a node. const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd); const startNonWhitespace = Math.max( opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart ); let endNonWhitespace; for ( endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace ) { if (text[endNonWhitespace - 1].match(/\S/)) { break; } } const startNodeAndParents = findNodeAtOffset( ast, startNonWhitespace, opts, node => isSourceElement(opts, node) ); const endNodeAndParents = findNodeAtOffset( ast, endNonWhitespace, opts, node => isSourceElement(opts, node) ); if (!startNodeAndParents || !endNodeAndParents) { return { rangeStart: 0, rangeEnd: 0 }; } const siblingAncestors = findSiblingAncestors( startNodeAndParents, endNodeAndParents, opts ); const startNode = siblingAncestors.startNode; const endNode = siblingAncestors.endNode; const rangeStart = Math.min( opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart) ); const rangeEnd = Math.max( opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd) ); return { rangeStart: rangeStart, rangeEnd: rangeEnd }; } function formatRange(text, opts, ast) { if (opts.rangeStart <= 0 && text.length <= opts.rangeEnd) { return; } const range = calculateRange(text, opts, ast); const rangeStart = range.rangeStart; const rangeEnd = range.rangeEnd; const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. // This is so we can detect indentation correctly and restore it. // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 const rangeStart2 = Math.min( rangeStart, text.lastIndexOf("\n", rangeStart) + 1 ); const indentString = text.slice(rangeStart2, rangeStart); const alignmentSize = util$1.getAlignmentSize( indentString, opts.tabWidth ); const rangeFormatted = format( rangeString, Object.assign({}, opts, { rangeStart: 0, rangeEnd: Infinity, printWidth: opts.printWidth - alignmentSize }), alignmentSize ); // Since the range contracts to avoid trailing whitespace, // we need to remove the newline that was inserted by the `format` call. const rangeTrimmed = rangeFormatted.trimRight(); return text.slice(0, rangeStart) + rangeTrimmed + text.slice(rangeEnd); } var prettier$2 = { formatWithCursor: function(text, opts) { return formatWithCursor(text, normalizeOptions(opts)); }, format: function(text, opts) { return format(text, normalizeOptions(opts)); }, check: function(text, opts) { try { const formatted = format(text, normalizeOptions(opts)); return formatted === text; } catch (e) { return false; } }, doc, resolveConfig: resolveConfig_1.resolveConfig, clearConfigCache: resolveConfig_1.clearCache, getSupportInfo, version, util: utilShared, /* istanbul ignore next */ __debug: { parse: function(text, opts) { opts = normalizeOptions(opts); return parser$3.parse(text, opts); }, formatAST: function(ast, opts) { opts = normalizeOptions(opts); const doc$$1 = astToDoc(ast, opts); const str = printDocToString(doc$$1, opts); return str; }, // Doesn't handle shebang for now formatDoc: function(doc$$1, opts) { opts = normalizeOptions(opts); const debug = printDocToDebug(doc$$1); const str = format(debug, opts); return str; }, printToDoc: function(text, opts) { opts = normalizeOptions(opts); const result = parser$3.parse(text, opts); const ast = result.ast; text = result.text; attachComments(text, ast, opts); const doc$$1 = astToDoc(ast, opts); return doc$$1; }, printDocToString: function(doc$$1, opts) { opts = normalizeOptions(opts); const str = printDocToString(doc$$1, opts); return str; } } }; var at; var ch; var escapee = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }; var text; var error = function (m) { // Call error when something is wrong. throw { name: 'SyntaxError', message: m, at: at, text: text }; }; var next = function (c) { // If a c parameter is provided, verify that it matches the current character. if (c && c !== ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } // Get the next character. When there are no more characters, // return the empty string. ch = text.charAt(at); at += 1; return ch; }; var number = function () { // Parse a number value. var number, string = ''; if (ch === '-') { string = '-'; next('-'); } while (ch >= '0' && ch <= '9') { string += ch; next(); } if (ch === '.') { string += '.'; while (next() && ch >= '0' && ch <= '9') { string += ch; } } if (ch === 'e' || ch === 'E') { string += ch; next(); if (ch === '-' || ch === '+') { string += ch; next(); } while (ch >= '0' && ch <= '9') { string += ch; next(); } } number = +string; if (!isFinite(number)) { error("Bad number"); } else { return number; } }; var string = function () { // Parse a string value. var hex, i, string = '', uffff; // When parsing for string values, we must look for " and \ characters. if (ch === '"') { while (next()) { if (ch === '"') { next(); return string; } else if (ch === '\\') { next(); if (ch === 'u') { uffff = 0; for (i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === 'string') { string += escapee[ch]; } else { break; } } else { string += ch; } } } error("Bad string"); }; var white = function () { // Skip whitespace. while (ch && ch <= ' ') { next(); } }; var word = function () { // true, false, or null. switch (ch) { case 't': next('t'); next('r'); next('u'); next('e'); return true; case 'f': next('f'); next('a'); next('l'); next('s'); next('e'); return false; case 'n': next('n'); next('u'); next('l'); next('l'); return null; } error("Unexpected '" + ch + "'"); }; var value; var array = function () { // Parse an array value. var array = []; if (ch === '[') { next('['); white(); if (ch === ']') { next(']'); return array; // empty array } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); return array; } next(','); white(); } } error("Bad array"); }; var object = function () { // Parse an object value. var key, object = {}; if (ch === '{') { next('{'); white(); if (ch === '}') { next('}'); return object; // empty object } while (ch) { key = string(); white(); next(':'); if (Object.hasOwnProperty.call(object, key)) { error('Duplicate key "' + key + '"'); } object[key] = value(); white(); if (ch === '}') { next('}'); return object; } next(','); white(); } } error("Bad object"); }; value = function () { // Parse a JSON value. It could be an object, an array, a string, a number, // or a word. white(); switch (ch) { case '{': return object(); case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); } }; // Return the json_parse function. It will have access to all of the above // functions and variables. var parse$8 = function (source, reviver) { var result; text = source; at = 0; ch = ' '; result = value(); white(); if (ch) { error("Syntax error"); } // If there is a reviver function, we recursively walk the new structure, // passing each name/value pair to the reviver function for possible // transformation, starting with a temporary root object that holds the result // in an empty key. If there is not a reviver function, we simply return the // result. return typeof reviver === 'function' ? (function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); }({'': result}, '')) : result; }; var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; var gap; var indent$8; var meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; var rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); case 'object': if (!value) return 'null'; gap += indent$8; partial = []; // Array.isArray if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and // wrap them in brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be // stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } var stringify$1 = function (value, replacer, space) { var i; gap = ''; indent$8 = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent$8 += ' '; } } // If the space parameter is a string, it will be used as the indent string. else if (typeof space === 'string') { indent$8 = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; var parse$7 = parse$8; var stringify = stringify$1; var jsonify = { parse: parse$7, stringify: stringify }; var json = typeof JSON !== 'undefined' ? JSON : jsonify; var jsonStableStringify = function (obj, opts) { if (!opts) opts = {}; if (typeof opts === 'function') opts = { cmp: opts }; var space = opts.space || ''; if (typeof space === 'number') space = Array(space+1).join(' '); var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; var replacer = opts.replacer || function(key, value) { return value; }; var cmp = opts.cmp && (function (f) { return function (node) { return function (a, b) { var aobj = { key: a, value: node[a] }; var bobj = { key: b, value: node[b] }; return f(aobj, bobj); }; }; })(opts.cmp); var seen = []; return (function stringify (parent, key, node, level) { var indent = space ? ('\n' + new Array(level + 1).join(space)) : ''; var colonSeparator = space ? ': ' : ':'; if (node && node.toJSON && typeof node.toJSON === 'function') { node = node.toJSON(); } node = replacer.call(parent, key, node); if (node === undefined) { return; } if (typeof node !== 'object' || node === null) { return json.stringify(node); } if (isArray$1(node)) { var out = []; for (var i = 0; i < node.length; i++) { var item = stringify(node, i, node[i], level+1) || json.stringify(null); out.push(indent + space + item); } return '[' + out.join(',') + indent + ']'; } else { if (seen.indexOf(node) !== -1) { if (cycles) return json.stringify('__cycle__'); throw new TypeError('Converting circular structure to JSON'); } else seen.push(node); var keys = objectKeys(node).sort(cmp && cmp(node)); var out = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = stringify(node, key, node[key], level+1); if(!value) continue; var keyValue = json.stringify(key) + colonSeparator + value; out.push(indent + space + keyValue); } seen.splice(seen.indexOf(node), 1); return '{' + out.join(',') + indent + '}'; } })({ '': obj }, '', obj, 0); }; var isArray$1 = Array.isArray || function (x) { return {}.toString.call(x) === '[object Array]'; }; var objectKeys = Object.keys || function (obj) { var has = Object.prototype.hasOwnProperty || function () { return true }; var keys = []; for (var key in obj) { if (has.call(obj, key)) keys.push(key); } return keys; }; function preserveCamelCase(str) { let isLastCharLower = false; let isLastCharUpper = false; let isLastLastCharUpper = false; for (let i = 0; i < str.length; i++) { const c = str[i]; if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) { str = str.substr(0, i) + '-' + str.substr(i); isLastCharLower = false; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = true; i++; } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(c) && c.toLowerCase() === c) { str = str.substr(0, i - 1) + '-' + str.substr(i - 1); isLastLastCharUpper = isLastCharUpper; isLastCharUpper = false; isLastCharLower = true; } else { isLastCharLower = c.toLowerCase() === c; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = c.toUpperCase() === c; } } return str; } var camelcase = function (str) { if (arguments.length > 1) { str = Array.from(arguments) .map(x => x.trim()) .filter(x => x.length) .join('-'); } else { str = str.trim(); } if (str.length === 0) { return ''; } if (str.length === 1) { return str.toLowerCase(); } if (/^[a-z0-9]+$/.test(str)) { return str; } const hasUpperCase = str !== str.toLowerCase(); if (hasUpperCase) { str = preserveCamelCase(str); } return str .replace(/^[_.\- ]+/, '') .toLowerCase() .replace(/[_.\- ]+(\w|$)/g, (m, p1) => p1.toUpperCase()); }; /*! * dashify <https://github.com/jonschlinkert/dashify> * * Copyright (c) 2015 Jon Schlinkert. * Licensed under the MIT license. */ var dashify = function dashify(str) { if (typeof str !== 'string') { throw new TypeError('expected a string'); } str = str.replace(/([a-z])([A-Z])/g, '$1-$2'); str = str.replace(/[ \t\W]/g, '-'); str = str.replace(/^-+|-+$/g, ''); return str.toLowerCase(); }; var PENDING = 'pending'; var SETTLED = 'settled'; var FULFILLED = 'fulfilled'; var REJECTED = 'rejected'; var NOOP = function () {}; var isNode$1 = typeof commonjsGlobal !== 'undefined' && typeof commonjsGlobal.process !== 'undefined' && typeof commonjsGlobal.process.emit === 'function'; var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate; var asyncQueue = []; var asyncTimer; function asyncFlush() { // run promise callbacks for (var i = 0; i < asyncQueue.length; i++) { asyncQueue[i][0](asyncQueue[i][1]); } // reset async asyncQueue asyncQueue = []; asyncTimer = false; } function asyncCall(callback, arg) { asyncQueue.push([callback, arg]); if (!asyncTimer) { asyncTimer = true; asyncSetTimer(asyncFlush, 0); } } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve$3(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch (e) { rejectPromise(e); } } function invokeCallback(subscriber) { var owner = subscriber.owner; var settled = owner._state; var value = owner._data; var callback = subscriber[settled]; var promise = subscriber.then; if (typeof callback === 'function') { settled = FULFILLED; try { value = callback(value); } catch (e) { reject(promise, e); } } if (!handleThenable(promise, value)) { if (settled === FULFILLED) { resolve$3(promise, value); } if (settled === REJECTED) { reject(promise, value); } } } function handleThenable(promise, value) { var resolved; try { if (promise === value) { throw new TypeError('A promises callback cannot return that same promise.'); } if (value && (typeof value === 'function' || typeof value === 'object')) { // then should be retrieved only once var then = value.then; if (typeof then === 'function') { then.call(value, function (val) { if (!resolved) { resolved = true; if (value === val) { fulfill(promise, val); } else { resolve$3(promise, val); } } }, function (reason) { if (!resolved) { resolved = true; reject(promise, reason); } }); return true; } } } catch (e) { if (!resolved) { reject(promise, e); } return true; } return false; } function resolve$3(promise, value) { if (promise === value || !handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state === PENDING) { promise._state = SETTLED; promise._data = value; asyncCall(publishFulfillment, promise); } } function reject(promise, reason) { if (promise._state === PENDING) { promise._state = SETTLED; promise._data = reason; asyncCall(publishRejection, promise); } } function publish(promise) { promise._then = promise._then.forEach(invokeCallback); } function publishFulfillment(promise) { promise._state = FULFILLED; publish(promise); } function publishRejection(promise) { promise._state = REJECTED; publish(promise); if (!promise._handled && isNode$1) { commonjsGlobal.process.emit('unhandledRejection', promise._data, promise); } } function notifyRejectionHandled(promise) { commonjsGlobal.process.emit('rejectionHandled', promise); } /** * @class */ function Promise$2(resolver) { if (typeof resolver !== 'function') { throw new TypeError('Promise resolver ' + resolver + ' is not a function'); } if (this instanceof Promise$2 === false) { throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); } this._then = []; invokeResolver(resolver, this); } Promise$2.prototype = { constructor: Promise$2, _state: PENDING, _then: null, _data: undefined, _handled: false, then: function (onFulfillment, onRejection) { var subscriber = { owner: this, then: new this.constructor(NOOP), fulfilled: onFulfillment, rejected: onRejection }; if ((onRejection || onFulfillment) && !this._handled) { this._handled = true; if (this._state === REJECTED && isNode$1) { asyncCall(notifyRejectionHandled, this); } } if (this._state === FULFILLED || this._state === REJECTED) { // already resolved, call callback async asyncCall(invokeCallback, subscriber); } else { // subscribe this._then.push(subscriber); } return subscriber.then; }, catch: function (onRejection) { return this.then(null, onRejection); } }; Promise$2.all = function (promises) { if (!Array.isArray(promises)) { throw new TypeError('You must pass an array to Promise.all().'); } return new Promise$2(function (resolve, reject) { var results = []; var remaining = 0; function resolver(index) { remaining++; return function (value) { results[index] = value; if (!--remaining) { resolve(results); } }; } for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolver(i), reject); } else { results[i] = promise; } } if (!remaining) { resolve(results); } }); }; Promise$2.race = function (promises) { if (!Array.isArray(promises)) { throw new TypeError('You must pass an array to Promise.race().'); } return new Promise$2(function (resolve, reject) { for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); }; Promise$2.resolve = function (value) { if (value && typeof value === 'object' && value.constructor === Promise$2) { return value; } return new Promise$2(function (resolve) { resolve(value); }); }; Promise$2.reject = function (reason) { return new Promise$2(function (resolve, reject) { reject(reason); }); }; var pinkie = Promise$2; var pinkiePromise = typeof Promise === 'function' ? Promise : pinkie; var arrayUniq = createCommonjsModule(function (module) { 'use strict'; // there's 3 implementations written in increasing order of efficiency // 1 - no Set type is defined function uniqNoSet(arr) { var ret = []; for (var i = 0; i < arr.length; i++) { if (ret.indexOf(arr[i]) === -1) { ret.push(arr[i]); } } return ret; } // 2 - a simple Set type is defined function uniqSet(arr) { var seen = new Set(); return arr.filter(function (el) { if (!seen.has(el)) { seen.add(el); return true; } return false; }); } // 3 - a standard Set type is defined and it has a forEach method function uniqSetWithForEach(arr) { var ret = []; (new Set(arr)).forEach(function (el) { ret.push(el); }); return ret; } // V8 currently has a broken implementation // https://github.com/joyent/node/issues/8449 function doesForEachActuallyWork() { var ret = false; (new Set([true])).forEach(function (el) { ret = el; }); return ret === true; } if ('Set' in commonjsGlobal) { if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) { module.exports = uniqSetWithForEach; } else { module.exports = uniqSet; } } else { module.exports = uniqNoSet; } }); var arrayUnion = function () { return arrayUniq([].concat.apply([], arguments)); }; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty$1 = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty$1.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; // 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(); } // 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$1 = function realpathSync(p, cache) { // make p is absolute p = path.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.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.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.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = path.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.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; var realpath$1 = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = path.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.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.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.stat(base, function(err) { if (err) return cb(err); fs.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.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = path.resolve(resolvedLink, p.slice(pos)); start(); } }; var old$1 = { realpathSync: realpathSync$1, realpath: realpath$1 }; var fs_realpath = realpath; realpath.realpath = realpath; realpath.sync = realpathSync; realpath.realpathSync = realpathSync; realpath.monkeypatch = monkeypatch; realpath.unmonkeypatch = unmonkeypatch; var origRealpath = fs.realpath; var origRealpathSync = fs.realpathSync; var version$3 = process.version; var ok = /^v[0-5]\./.test(version$3); function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath (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$1.realpath(p, cache, cb); } else { cb(er, result); } }); } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old$1.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs.realpath = realpath; fs.realpathSync = realpathSync; } function unmonkeypatch () { fs.realpath = origRealpath; fs.realpathSync = origRealpathSync; } var inherits_browser = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, 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) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var inherits$2 = createCommonjsModule(function (module) { try { var util$$2 = util; if (typeof util$$2.inherits !== 'function') throw ''; module.exports = util$$2.inherits; } catch (e) { module.exports = inherits_browser; } }); function posix(path$$1) { return path$$1.charAt(0) === '/'; } function win32(path$$1) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path$$1); 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$2; var alphasorti_1 = alphasorti$2; var setopts_1 = setopts$2; var ownProp_1 = ownProp$2; var makeAbs_1 = makeAbs; var finish_1 = finish; var mark_1 = mark; var isIgnored_1 = isIgnored$2; var childrenIgnored_1 = childrenIgnored$2; function ownProp$2 (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var Minimatch$3 = minimatch_1.Minimatch; function alphasorti$2 (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()) } function alphasort$2 (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$3(gpattern, { dot: true }); } return { matcher: new Minimatch$3(pattern, { dot: true }), gmatcher: gmatcher } } function setopts$2 (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$2(options, "cwd")) self.cwd = cwd; else { self.cwd = path.resolve(options.cwd); self.changedCwd = self.cwd !== cwd; } self.root = options.root || path.resolve(self.cwd, "/"); self.root = path.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$3(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$2 : alphasort$2); // 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$2(self, m) }); self.found = all; } function mark (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.join(self.root, f); } else if (pathIsAbsolute(f) || f === '') { abs = f; } else if (self.changedCwd) { abs = path.resolve(self.cwd, f); } else { abs = path.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$2 (self, path$$2) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path$$2) || !!(item.gmatcher && item.gmatcher.match(path$$2)) }) } function childrenIgnored$2 (self, path$$2) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path$$2)) }) } var common = { 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$4 = globSync; globSync.GlobSync = GlobSync$1; var setopts$1 = common.setopts; var ownProp$1 = common.ownProp; var childrenIgnored$1 = common.childrenIgnored; var isIgnored$1 = common.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$1(pattern, options).found } function GlobSync$1 (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$1)) return new GlobSync$1(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$1.prototype._finish = function () { assert(this instanceof GlobSync$1); 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.finish(this); }; GlobSync$1.prototype._process = function (pattern, index, inGlobStar) { assert(this instanceof GlobSync$1); // 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$1.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.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$1.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$1.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; var stat; try { lstat = fs.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$1.prototype._readdir = function (abs, inGlobStar) { var entries; 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.readdirSync(abs)) } catch (er) { this._readdirError(abs, er); return null } }; GlobSync$1.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$1.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$1.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$1.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.join(this.root, prefix); } else { prefix = path.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$1.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 exists; var stat = this.statCache[abs]; if (!stat) { var lstat; try { lstat = fs.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.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$1.prototype._mark = function (p) { return common.mark(this, p) }; GlobSync$1.prototype._makeAbs = function (f) { return common.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(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 (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.EventEmitter; var setopts = common.setopts; var ownProp = common.ownProp; var childrenIgnored = common.childrenIgnored; var isIgnored = common.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$4(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = sync$4; var GlobSync = glob.GlobSync = sync$4.GlobSync; // old api surface glob.glob = glob; function extend (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({}, 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$2(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(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options); this._didRealPath = false; // process each pattern in the minimatch set var n = this.minimatch.set.length; // The matches are stored as {<filename>: 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(this instanceof Glob); if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.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.mark(this, p) }; Glob.prototype._makeAbs = function (f) { return common.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(this instanceof Glob); assert(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(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.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]; var newPattern; 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(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.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(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this; fs.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.join(this.root, prefix); } else { prefix = path.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(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 exists; 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.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.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) }; var pify_1 = createCommonjsModule(function (module) { 'use strict'; var processFn = function (fn, P, opts) { return function () { var that = this; var args = new Array(arguments.length); for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } return new P(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else if (opts.multiArgs) { var results = new Array(arguments.length - 1); for (var i = 1; i < arguments.length; i++) { results[i - 1] = arguments[i]; } resolve(results); } else { resolve(result); } }); fn.apply(that, args); }); }; }; var pify = module.exports = function (obj, P, opts) { if (typeof P !== 'function') { opts = P; P = Promise; } opts = opts || {}; opts.exclude = opts.exclude || [/.+Sync$/]; var filter = function (key) { var match = function (pattern) { return typeof pattern === 'string' ? key === pattern : pattern.test(key); }; return opts.include ? opts.include.some(match) : !opts.exclude.some(match); }; var ret = typeof obj === 'function' ? function () { if (opts.excludeMain) { return obj.apply(this, arguments); } return processFn(obj, P, opts).apply(this, arguments); } : {}; return Object.keys(obj).reduce(function (ret, key) { var x = obj[key]; ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x; return ret; }, ret); }; pify.all = pify; }); var globP = pify_1(glob_1, pinkiePromise).bind(glob_1); function isNegative(pattern) { return pattern[0] === '!'; } function isString(value) { return typeof value === 'string'; } function assertPatternsInput(patterns) { if (!patterns.every(isString)) { throw new TypeError('patterns must be a string or an array of strings'); } } function generateGlobTasks(patterns, opts) { patterns = [].concat(patterns); assertPatternsInput(patterns); var globTasks = []; opts = objectAssign({ cache: Object.create(null), statCache: Object.create(null), realpathCache: Object.create(null), symlinks: Object.create(null), ignore: [] }, opts); patterns.forEach(function (pattern, i) { if (isNegative(pattern)) { return; } var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) { return pattern.slice(1); }); globTasks.push({ pattern: pattern, opts: objectAssign({}, opts, { ignore: opts.ignore.concat(ignore) }) }); }); return globTasks; } var globby = function (patterns, opts) { var globTasks; try { globTasks = generateGlobTasks(patterns, opts); } catch (err) { return pinkiePromise.reject(err); } return pinkiePromise.all(globTasks.map(function (task) { return globP(task.pattern, task.opts); })).then(function (paths) { return arrayUnion.apply(null, paths); }); }; var sync$3 = function (patterns, opts) { var globTasks = generateGlobTasks(patterns, opts); return globTasks.reduce(function (matches, task) { return arrayUnion(matches, glob_1.sync(task.pattern, task.opts)); }, []); }; var generateGlobTasks_1 = generateGlobTasks; var hasMagic = function (patterns, opts) { return [].concat(patterns).some(function (pattern) { return glob_1.hasMagic(pattern, opts); }); }; globby.sync = sync$3; globby.generateGlobTasks = generateGlobTasks_1; globby.hasMagic = hasMagic; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ignore = function () { return new IgnoreBase(); }; // A simple implementation of make-array function make_array(subject) { return Array.isArray(subject) ? subject : [subject]; } var REGEX_BLANK_LINE = /^\s+$/; var REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\\!/; var REGEX_LEADING_EXCAPED_HASH = /^\\#/; var SLASH = '/'; var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore') /* istanbul ignore next */ : 'node-ignore'; var IgnoreBase = function () { function IgnoreBase() { _classCallCheck(this, IgnoreBase); this._rules = []; this[KEY_IGNORE] = true; this._initCache(); } _createClass(IgnoreBase, [{ key: '_initCache', value: function _initCache() { this._cache = {}; } // @param {Array.<string>|string|Ignore} pattern }, { key: 'add', value: function add(pattern) { this._added = false; if (typeof pattern === 'string') { pattern = pattern.split(/\r?\n/g); } make_array(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 }, { key: 'addPattern', value: function addPattern(pattern) { return this.add(pattern); } }, { key: '_addPattern', value: function _addPattern(pattern) { // #32 if (pattern && pattern[KEY_IGNORE]) { this._rules = this._rules.concat(pattern._rules); this._added = true; return; } if (this._checkPattern(pattern)) { var rule = this._createRule(pattern); this._added = true; this._rules.push(rule); } } }, { key: '_checkPattern', value: function _checkPattern(pattern) { // > A blank line matches no files, so it can serve as a separator for readability. return pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment. && pattern.indexOf('#') !== 0; } }, { key: 'filter', value: function filter(paths) { var _this = this; return make_array(paths).filter(function (path$$1) { return _this._filter(path$$1); }); } }, { key: 'createFilter', value: function createFilter() { var _this2 = this; return function (path$$1) { return _this2._filter(path$$1); }; } }, { key: 'ignores', value: function ignores(path$$1) { return !this._filter(path$$1); } }, { key: '_createRule', value: function _createRule(pattern) { var origin = pattern; var 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_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that begin with a hash. .replace(REGEX_LEADING_EXCAPED_HASH, '#'); var regex = make_regex(pattern, negative); return { origin: origin, pattern: pattern, negative: negative, regex: regex }; } // @returns `Boolean` true if the `path` is NOT ignored }, { key: '_filter', value: function _filter(path$$1, slices) { if (!path$$1) { return false; } if (path$$1 in this._cache) { return this._cache[path$$1]; } if (!slices) { // path/to/a.js // ['path', 'to', 'a.js'] slices = path$$1.split(SLASH); } slices.pop(); return this._cache[path$$1] = slices.length // > It is not possible to re-include a file if a parent directory of that file is excluded. // If the path contains a parent directory, check the parent first ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path$$1) // Or only test the path : this._test(path$$1); } // @returns {Boolean} true if a file is NOT ignored }, { key: '_test', value: function _test(path$$1) { // Explicitly define variable type by setting matched to `0` var matched = 0; this._rules.forEach(function (rule) { // if matched = true, then we only test negative rules // if matched = false, then we test non-negative rules if (!(matched ^ rule.negative)) { matched = rule.negative ^ rule.regex.test(path$$1); } }); return !matched; } }]); return IgnoreBase; }(); // > 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 '`..`' var DEFAULT_REPLACER_PREFIX = [ // > Trailing spaces are ignored unless they are quoted with backslash ("\") [ // (a\ ) -> (a ) // (a ) -> (a) // (a \ ) -> (a ) /\\?\s+$/, function (match) { return match.indexOf('\\') === 0 ? ' ' : ''; }], // replace (\ ) with ' ' [/\\\s/g, function () { return ' '; }], // 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, function (match) { return '\\' + match; }], // 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 /^\//, function () { return '^'; }], // replace special metacharacter slash after the leading slash [/\//g, function () { return '\\/'; }], [ // > 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' function () { return '^(?:.*\\/)?'; }]]; var DEFAULT_REPLACER_SUFFIX = [ // 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 () { return !/\/(?!$)/.test(this) // > 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 ? '(?:^|\\/)' // > 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 `'/**'` function (match, index, str) { return 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' function (match, p1) { return p1 + '[^\\/]*'; }], // trailing wildcard [/(\^|\\\/)?\\\*$/, function (match, p1) { return (p1 // '\^': // '/*' does not match '' // '/*' does not match everything // '\\\/': // 'abc/*' does not match 'abc/' ? p1 + '[^/]+' // 'a*' matches 'a' // 'a*' matches 'aa' : '[^/]*') + '(?=$|\\/$)'; }], [ // unescape /\\\\\\/g, function () { return '\\'; }]]; var POSITIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [ // 'f' // matches // - /f(end) // - /f/ // - (start)f(end) // - (start)f/ // doesn't match // - oof // - foo // pseudo: // -> (^|/)f(/|$) // ending [ // 'js' will not match 'js.' // 'ab' will not match 'abc' /(?:[^*\/])$/, // 'js*' will not match 'a.js' // 'js/' will not match 'a.js' // 'js' will match 'a.js' and 'a.js/' function (match) { return match + '(?=$|\\/)'; }]], DEFAULT_REPLACER_SUFFIX); var NEGATIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [ // #24 // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore) // A negative pattern without a trailing wildcard should not // re-include the things inside that directory. // eg: // ['node_modules/*', '!node_modules'] // should ignore `node_modules/a.js` [/(?:[^*\/])$/, function (match) { return match + '(?=$|\\/$)'; }]], DEFAULT_REPLACER_SUFFIX); // A simple cache, because an ignore rule only has only one certain meaning var cache = {}; // @param {pattern} function make_regex(pattern, negative) { var r = cache[pattern]; if (r) { return r; } var replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS; var source = replacers.reduce(function (prev, current) { return prev.replace(current[0], current[1].bind(pattern)); }, pattern); return cache[pattern] = new RegExp(source, 'i'); } // 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')) { var filter$3 = IgnoreBase.prototype._filter; var make_posix = function make_posix(str) { return (/^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/') ); }; IgnoreBase.prototype._filter = function (path$$1, slices) { path$$1 = make_posix(path$$1); return filter$3.call(this, path$$1, slices); }; } var ansiStyles$3 = createCommonjsModule(function (module) { 'use strict'; 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 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; Object.keys(styles).forEach(groupName => { const group = styles[groupName]; Object.keys(group).forEach(styleName => { const style = group[styleName]; styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; }); Object.defineProperty(styles, groupName, { value: group, enumerable: false }); }); const rgb2rgb = (r, g, b) => [r, g, b]; styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = {}; styles.color.ansi256 = {}; styles.color.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 0) }; styles.bgColor.ansi = {}; styles.bgColor.ansi256 = {}; styles.bgColor.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 10) }; for (const key of Object.keys(colorConvert)) { if (typeof colorConvert[key] !== 'object') { continue; } const suite = colorConvert[key]; 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; } Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }); var supportsColor$3 = createCommonjsModule(function (module) { 'use strict'; const env = process.env; const support = level => { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; }; let supportLevel = (() => { if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { return 1; } if (process.stdout && !process.stdout.isTTY) { return 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. const osRelease = os.release().split('.'); if ( Number(process.version.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return 2; } return 1; } if ('CI' in env) { if ('TRAVIS' in env || env.CI === 'Travis' || 'CIRCLECI' in env) { return 1; } return 0; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } 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 'Hyper': return 3; case 'Apple_Terminal': return 2; // No default } } if (/^(screen|xterm)-256(?:color)?/.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } if (env.TERM === 'dumb') { return 0; } return 0; })(); if ('FORCE_COLOR' in env) { supportLevel = parseInt(env.FORCE_COLOR, 10) === 0 ? 0 : (supportLevel || 1); } module.exports = process && support(supportLevel); }); var templates$2 = createCommonjsModule(function (module) { 'use strict'; const TEMPLATE_REGEX = /(?:\\(u[a-f0-9]{4}|x[a-f0-9]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u[0-9a-f]{4}|x[0-9a-f]{2}|.)|([^\\])/gi; const ESCAPES = { 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[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; } module.exports = (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(''); }; }); 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 = supportsColor$3 ? supportsColor$3.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$3.blue.open = '\u001B[94m'; } for (const key of Object.keys(ansiStyles$3)) { ansiStyles$3[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles$3[key].close), 'g'); styles[key] = { get() { const codes = ansiStyles$3[key]; return build$1.call(this, this._styles ? this._styles.concat(codes) : [codes], key); } }; } ansiStyles$3.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles$3.color.close), 'g'); for (const model of Object.keys(ansiStyles$3.color.ansi)) { if (skipModels.has(model)) { continue; } styles[model] = { get() { const level = this.level; return function () { const open = ansiStyles$3.color[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles$3.color.close, closeRe: ansiStyles$3.color.closeRe }; return build$1.call(this, this._styles ? this._styles.concat(codes) : [codes], model); }; } }; } ansiStyles$3.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles$3.bgColor.close), 'g'); for (const model of Object.keys(ansiStyles$3.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$3.bgColor[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles$3.bgColor.close, closeRe: ansiStyles$3.bgColor.closeRe }; return build$1.call(this, this._styles ? this._styles.concat(codes) : [codes], model); }; } }; } const proto = Object.defineProperties(() => {}, styles); function build$1(_styles, key) { const builder = function () { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; 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 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$3.dim.open; if (isSimpleWindowsTerm && this.hasGrey) { ansiStyles$3.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$3.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$2(chalk, parts.join('')); } Object.defineProperties(Chalk.prototype, styles); var chalk$2 = Chalk(); // eslint-disable-line new-cap var supportsColor_1 = supportsColor$3; chalk$2.supportsColor = supportsColor_1; 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(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; keys.slice(0,-1).forEach(function (key) { if (o[key] === undefined) o[key] = {}; o = o[key]; }); var key = keys[keys.length - 1]; 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(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 (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); } const PLACEHOLDER = null; /** * unspecified boolean flag without default value is parsed as `undefined` instead of `false` */ var minimist_1 = function(args, options) { const boolean = options.boolean || []; const defaults = options.default || {}; const booleanWithoutDefault = boolean.filter(key => !(key in defaults)); const newDefaults = Object.assign( {}, defaults, booleanWithoutDefault.reduce( (reduced, key) => Object.assign(reduced, { [key]: PLACEHOLDER }), {} ) ); const parsed = minimist( args, Object.assign({}, options, { default: newDefaults }) ); return Object.keys(parsed).reduce((reduced, key) => { if (parsed[key] !== PLACEHOLDER) { reduced[key] = parsed[key]; } return reduced; }, {}); }; function cleanAST$1(ast, options) { return JSON.stringify(massageAST(ast, options), null, 2); } function massageAST(ast, options, parent) { if (Array.isArray(ast)) { return ast.map(e => massageAST(e, options, parent)).filter(e => e); } if (!ast || typeof ast !== "object") { return ast; } const newObj = {}; for (const key in ast) { if (typeof ast[key] !== "function") { newObj[key] = massageAST(ast[key], options, ast); } } [ "loc", "range", "raw", "comments", "leadingComments", "trailingComments", "extra", "start", "end", "tokens", "flags", "raws", "sourceIndex", "id", "source", "before", "after", "trailingComma", "parent", "prev", "position" ].forEach(name => { delete newObj[name]; }); if (options.printer.massageAstNode) { const result = options.printer.massageAstNode(ast, newObj, parent); if (result === null) { return undefined; } if (result) { return result; } } return newObj; } var cleanAst = { cleanAST: cleanAST$1, massageAST }; var base = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports['default'] = /*istanbul ignore end*/Diff; function Diff() {} Diff.prototype = { /*istanbul ignore start*/ /*istanbul ignore end*/diff: function diff(oldString, newString) { /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } this.options = options; var self = this; function done(value) { if (callback) { setTimeout(function () { callback(undefined, value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString); newString = this.castInput(newString); oldString = this.removeEmpty(this.tokenize(oldString)); newString = this.removeEmpty(this.tokenize(newString)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0, i.e. the content starts with the same values var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { // Identity per the equality and tokenizer return done([{ value: this.join(newString), count: newString.length }]); } // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { var basePath = /*istanbul ignore start*/void 0; var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { basePath = clonePath(removePath); self.pushComponent(basePath.components, undefined, true); } else { basePath = addPath; // No need to clone, we've pulled it from the list basePath.newPos++; self.pushComponent(basePath.components, true, undefined); } _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); } else { // Otherwise track this path as a potential candidate and continue. bestPath[diagonalPath] = basePath; } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced. if (callback) { (function exec() { setTimeout(function () { // This should not happen, but we want to be safe. /* istanbul ignore next */ if (editLength > maxEditLength) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength) { var ret = execEditLength(); if (ret) { return ret; } } } }, /*istanbul ignore start*/ /*istanbul ignore end*/pushComponent: function pushComponent(components, added, removed) { var last = components[components.length - 1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length - 1] = { count: last.count + 1, added: added, removed: removed }; } else { components.push({ count: 1, added: added, removed: removed }); } }, /*istanbul ignore start*/ /*istanbul ignore end*/extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { newPos++; oldPos++; commonCount++; } if (commonCount) { basePath.components.push({ count: commonCount }); } basePath.newPos = newPos; return oldPos; }, /*istanbul ignore start*/ /*istanbul ignore end*/equals: function equals(left, right) { return left === right; }, /*istanbul ignore start*/ /*istanbul ignore end*/removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, /*istanbul ignore start*/ /*istanbul ignore end*/castInput: function castInput(value) { return value; }, /*istanbul ignore start*/ /*istanbul ignore end*/tokenize: function tokenize(value) { return value.split(''); }, /*istanbul ignore start*/ /*istanbul ignore end*/join: function join(chars) { return chars.join(''); } }; function buildValues(diff, components, newString, oldString, useLongestToken) { var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; // Reverse add and remove so removes are output first to match common convention // The diffing algorithm is tied to add then remove output and this is the simplest // route to get the desired output with minimal overhead. if (componentPos && components[componentPos - 1].added) { var tmp = components[componentPos - 1]; components[componentPos - 1] = components[componentPos]; components[componentPos] = tmp; } } } // Special case handle for when one terminal is ignored. For this case we merge the // terminal into the prior string and drop the change. var lastComponent = components[componentLen - 1]; if (componentLen > 1 && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { components[componentLen - 2].value += lastComponent.value; components.pop(); } return components; } function clonePath(path$$1) { return { newPos: path$$1.newPos, components: path$$1.components.slice(0) }; } }); unwrapExports(base); var character = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.characterDiff = undefined; exports. /*istanbul ignore end*/diffChars = diffChars; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/var characterDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/characterDiff = new /*istanbul ignore start*/_base2['default'](); function diffChars(oldStr, newStr, callback) { return characterDiff.diff(oldStr, newStr, callback); } }); unwrapExports(character); var params = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports. /*istanbul ignore end*/generateOptions = generateOptions; function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } }); unwrapExports(params); var word$1 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.wordDiff = undefined; exports. /*istanbul ignore end*/diffWords = diffWords; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = diffWordsWithSpace; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); /*istanbul ignore end*/ /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/ // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ &#711; Caron // - U+02D8 ˘ &#728; Breve // - U+02D9 ˙ &#729; Dot Above // - U+02DA ˚ &#730; Ring Above // - U+02DB ˛ &#731; Ogonek // - U+02DC ˜ &#732; Small Tilde // - U+02DD ˝ &#733; Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; var reWhitespace = /\S/; var wordDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/wordDiff = new /*istanbul ignore start*/_base2['default'](); wordDiff.equals = function (left, right) { return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); }; wordDiff.tokenize = function (value) { var tokens = value.split(/(\s+|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. for (var i = 0; i < tokens.length - 1; i++) { // If we have an empty string in the next field and we have only word chars before and after, merge if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { tokens[i] += tokens[i + 2]; tokens.splice(i + 1, 2); i--; } } return tokens; }; function diffWords(oldStr, newStr, callback) { var options = /*istanbul ignore start*/(0, params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true }); return wordDiff.diff(oldStr, newStr, options); } function diffWordsWithSpace(oldStr, newStr, callback) { return wordDiff.diff(oldStr, newStr, callback); } }); unwrapExports(word$1); var line$7 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.lineDiff = undefined; exports. /*istanbul ignore end*/diffLines = diffLines; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = diffTrimmedLines; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); /*istanbul ignore end*/ /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/var lineDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/lineDiff = new /*istanbul ignore start*/_base2['default'](); lineDiff.tokenize = function (value) { var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !this.options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { if (this.options.ignoreWhitespace) { line = line.trim(); } retLines.push(line); } } return retLines; }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } function diffTrimmedLines(oldStr, newStr, callback) { var options = /*istanbul ignore start*/(0, params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } }); unwrapExports(line$7); var sentence = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.sentenceDiff = undefined; exports. /*istanbul ignore end*/diffSentences = diffSentences; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/var sentenceDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/sentenceDiff = new /*istanbul ignore start*/_base2['default'](); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } }); unwrapExports(sentence); var css = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.cssDiff = undefined; exports. /*istanbul ignore end*/diffCss = diffCss; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/var cssDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/cssDiff = new /*istanbul ignore start*/_base2['default'](); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } }); unwrapExports(css); var json$1 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.jsonDiff = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; exports. /*istanbul ignore end*/diffJson = diffJson; /*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = canonicalize; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); /*istanbul ignore end*/ /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/ var objectPrototypeToString = Object.prototype.toString; var jsonDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/jsonDiff = new /*istanbul ignore start*/_base2['default'](); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = /*istanbul ignore start*/line$7.lineDiff. /*istanbul ignore end*/tokenize; jsonDiff.castInput = function (value) { /*istanbul ignore start*/var /*istanbul ignore end*/undefinedReplacement = this.options.undefinedReplacement; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), function (k, v) { if (typeof v === 'undefined') { return undefinedReplacement; } return v; }, ' '); }; jsonDiff.equals = function (left, right) { return (/*istanbul ignore start*/_base2['default']. /*istanbul ignore end*/prototype.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')) ); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. function canonicalize(obj, stack, replacementStack) { stack = stack || []; replacementStack = replacementStack || []; var i = /*istanbul ignore start*/void 0; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj = /*istanbul ignore start*/void 0; if ('[object Array]' === objectPrototypeToString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if ( /*istanbul ignore start*/(typeof /*istanbul ignore end*/obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], key = /*istanbul ignore start*/void 0; for (key in obj) { /* istanbul ignore else */ if (obj.hasOwnProperty(key)) { sortedKeys.push(key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { key = sortedKeys[i]; canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } }); unwrapExports(json$1); var array$1 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.arrayDiff = undefined; exports. /*istanbul ignore end*/diffArrays = diffArrays; /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/var arrayDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/arrayDiff = new /*istanbul ignore start*/_base2['default'](); arrayDiff.tokenize = arrayDiff.join = function (value) { return value.slice(); }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } }); unwrapExports(array$1); var parse$10 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports. /*istanbul ignore end*/parsePatch = parsePatch; function parsePatch(uniDiff) { /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line && options.strict) { // Ignore unexpected content unless in strict mode throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var headerPattern = /^(---|\+\+\+)\s+([\S ]*)(?:\t(.*?)\s*)?$/; var fileHeader = headerPattern.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; index[keyPrefix + 'FileName'] = fileHeader[2]; index[keyPrefix + 'Header'] = fileHeader[3]; i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: +chunkHeader[2] || 1, newStart: +chunkHeader[3], newLines: +chunkHeader[4] || 1, lines: [], linedelimiters: [] }; var addCount = 0, removeCount = 0; for (; i < diffstr.length; i++) { // Lines starting with '---' could be mistaken for the "remove line" operation // But they could be the header for the next file. Therefore prune such cases out. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { break; } var operation = diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); hunk.linedelimiters.push(delimiters[i] || '\n'); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { break; } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform optional sanity checking if (options.strict) { if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } }); unwrapExports(parse$10); var distanceIterator = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/"use strict"; exports.__esModule = true; exports["default"] = /*istanbul ignore end*/function (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return -localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text lenght, then // hunk can't fit on the text. Return undefined }; }; }); unwrapExports(distanceIterator); var apply = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports. /*istanbul ignore end*/applyPatch = applyPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = applyPatches; /*istanbul ignore start*/ var _distanceIterator2 = _interopRequireDefault(distanceIterator); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /*istanbul ignore end*/function applyPatch(source, uniDiff) { /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; if (typeof uniDiff === 'string') { uniDiff = /*istanbul ignore start*/(0, parse$10.parsePatch) /*istanbul ignore end*/(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } // Apply the diff to the input var lines = source.split(/\r\n|[\n\v\f\r\x85]/), delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) /*istanbul ignore start*/{ return (/*istanbul ignore end*/line === patchContent ); }, errorCount = 0, fuzzFactor = options.fuzzFactor || 0, minLine = 0, offset = 0, removeEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/, addEOFNL = /*istanbul ignore start*/void 0; /** * Checks if the hunk exactly fits on the provided location */ function hunkFits(hunk, toPos) { for (var j = 0; j < hunk.lines.length; j++) { var line = hunk.lines[j], operation = line[0], content = line.substr(1); if (operation === ' ' || operation === '-') { // Context sanity check if (!compareLine(toPos + 1, lines[toPos], operation, content)) { errorCount++; if (errorCount > fuzzFactor) { return false; } } toPos++; } } return true; } // Search best fit offsets for each hunk based on the previous ones for (var i = 0; i < hunks.length; i++) { var hunk = hunks[i], maxLine = lines.length - hunk.oldLines, localOffset = 0, toPos = offset + hunk.oldStart - 1; var iterator = /*istanbul ignore start*/(0, _distanceIterator2['default']) /*istanbul ignore end*/(toPos, minLine, maxLine); for (; localOffset !== undefined; localOffset = iterator()) { if (hunkFits(hunk, toPos + localOffset)) { hunk.offset = offset += localOffset; break; } } if (localOffset === undefined) { return false; } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunk.offset + hunk.oldStart + hunk.oldLines; } // Apply patch hunks for (var _i = 0; _i < hunks.length; _i++) { var _hunk = hunks[_i], _toPos = _hunk.offset + _hunk.newStart - 1; if (_hunk.newLines == 0) { _toPos++; } for (var j = 0; j < _hunk.lines.length; j++) { var line = _hunk.lines[j], operation = line[0], content = line.substr(1), delimiter = _hunk.linedelimiters[j]; if (operation === ' ') { _toPos++; } else if (operation === '-') { lines.splice(_toPos, 1); delimiters.splice(_toPos, 1); /* istanbul ignore else */ } else if (operation === '+') { lines.splice(_toPos, 0, content); delimiters.splice(_toPos, 0, delimiter); _toPos++; } else if (operation === '\\') { var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; if (previousOperation === '+') { removeEOFNL = true; } else if (previousOperation === '-') { addEOFNL = true; } } } } // Handle EOFNL insertion/removal if (removeEOFNL) { while (!lines[lines.length - 1]) { lines.pop(); delimiters.pop(); } } else if (addEOFNL) { lines.push(''); delimiters.push('\n'); } for (var _k = 0; _k < lines.length - 1; _k++) { lines[_k] = lines[_k] + delimiters[_k]; } return lines.join(''); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = /*istanbul ignore start*/(0, parse$10.parsePatch) /*istanbul ignore end*/(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } }); unwrapExports(apply); var create = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports. /*istanbul ignore end*/structuredPatch = structuredPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = createTwoFilesPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = createPatch; /*istanbul ignore start*/ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /*istanbul ignore end*/function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options.context === 'undefined') { options.context = 4; } var diff = /*istanbul ignore start*/(0, line$7.diffLines) /*istanbul ignore end*/(oldStr, newStr, options); diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; /*istanbul ignore start*/ var _loop = function _loop( /*istanbul ignore end*/i) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { /*istanbul ignore start*/ var _curRange; /*istanbul ignore end*/ // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes /*istanbul ignore start*/(_curRange = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { /*istanbul ignore start*/ var _curRange2; /*istanbul ignore end*/ // Overlapping /*istanbul ignore start*/(_curRange2 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines))); } else { /*istanbul ignore start*/ var _curRange3; /*istanbul ignore end*/ // end the range and output var contextSize = Math.min(lines.length, options.context); /*istanbul ignore start*/(_curRange3 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines.slice(0, contextSize)))); var hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; if (i >= diff.length - 2 && lines.length <= options.context) { // EOF is inside this hunk var oldEOFNewline = /\n$/.test(oldStr); var newEOFNewline = /\n$/.test(newStr); if (lines.length == 0 && !oldEOFNewline) { // special case: old has no eol and no trailing context; no-nl can end up before adds curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); } else if (!oldEOFNewline || !newEOFNewline) { curRange.push('\\ No newline at end of file'); } } hunks.push(hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { /*istanbul ignore start*/ _loop( /*istanbul ignore end*/i); } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); var ret = []; if (oldFileName == newFileName) { ret.push('Index: ' + oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } }); unwrapExports(create); var dmp = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/"use strict"; exports.__esModule = true; exports. /*istanbul ignore end*/convertChangesToDMP = convertChangesToDMP; // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change = /*istanbul ignore start*/void 0 /*istanbul ignore end*/, operation = /*istanbul ignore start*/void 0; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } }); unwrapExports(dmp); var xml = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports. /*istanbul ignore end*/convertChangesToXML = convertChangesToXML; function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push('<ins>'); } else if (change.removed) { ret.push('<del>'); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push('</ins>'); } else if (change.removed) { ret.push('</del>'); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&amp;'); n = n.replace(/</g, '&lt;'); n = n.replace(/>/g, '&gt;'); n = n.replace(/"/g, '&quot;'); return n; } }); unwrapExports(xml); var lib$5 = createCommonjsModule(function (module, exports) { /*istanbul ignore start*/'use strict'; exports.__esModule = true; exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffArrays = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diffTrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWords = exports.diffChars = exports.Diff = undefined; /*istanbul ignore end*/ /*istanbul ignore start*/ var _base2 = _interopRequireDefault(base); /*istanbul ignore end*/ /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports. /*istanbul ignore end*/Diff = _base2['default']; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffChars = character.diffChars; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWords = word$1.diffWords; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = word$1.diffWordsWithSpace; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffLines = line$7.diffLines; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = line$7.diffTrimmedLines; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffSentences = sentence.diffSentences; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffCss = css.diffCss; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffJson = json$1.diffJson; /*istanbul ignore start*/exports. /*istanbul ignore end*/diffArrays = array$1.diffArrays; /*istanbul ignore start*/exports. /*istanbul ignore end*/structuredPatch = create.structuredPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = create.createTwoFilesPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = create.createPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatch = apply.applyPatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = apply.applyPatches; /*istanbul ignore start*/exports. /*istanbul ignore end*/parsePatch = parse$10.parsePatch; /*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToDMP = dmp.convertChangesToDMP; /*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToXML = xml.convertChangesToXML; /*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = json$1.canonicalize; /* See LICENSE file for terms of use */ /* * Text diff implementation. * * This library supports the following APIS: * JsDiff.diffChars: Character by character diff * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace * JsDiff.diffLines: Line based diff * * JsDiff.diffCss: Diff targeted at CSS content * * These methods are based on the implementation proposed in * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 */ }); unwrapExports(lib$5); const cleanAST = cleanAst.cleanAST; const getSupportInfo$3 = support.getSupportInfo; const OPTION_USAGE_THRESHOLD = 25; const CHOICE_USAGE_MARGIN = 3; const CHOICE_USAGE_INDENTATION = 2; function getOptions(argv, detailedOptions) { return detailedOptions.filter(option => option.forwardToApi).reduce( (current, option) => Object.assign(current, { [option.forwardToApi]: argv[option.name] }), {} ); } function cliifyOptions(object, apiDetailedOptionMap) { return Object.keys(object || {}).reduce((output, key) => { const apiOption = apiDetailedOptionMap[key]; const cliKey = apiOption ? apiOption.name : key; output[dashify(cliKey)] = object[key]; return output; }, {}); } function diff(a, b) { return lib$5.createTwoFilesPatch("", "", a, b, "", "", { context: 2 }); } function handleError(context, filename, error) { const isParseError = Boolean(error && error.loc); const isValidationError = /Validation Error/.test(error && error.message); // For parse errors and validation errors, we only want to show the error // message formatted in a nice way. `String(error)` takes care of that. Other // (unexpected) errors are passed as-is as a separate argument to // `console.error`. That includes the stack trace (if any), and shows a nice // `util.inspect` of throws things that aren't `Error` objects. (The Flow // parser has mistakenly thrown arrays sometimes.) if (isParseError) { context.logger.error(`${filename}: ${String(error)}`); } else if (isValidationError || error instanceof errors.ConfigError) { context.logger.error(String(error)); // If validation fails for one file, it will fail for all of them. process.exit(1); } else if (error instanceof errors.DebugError) { context.logger.error(`${filename}: ${error.message}`); } else { context.logger.error(filename + ": " + (error.stack || error)); } // Don't exit the process if one file failed process.exitCode = 2; } function logResolvedConfigPathOrDie(context, filePath) { const configFile = resolveConfig_1.resolveConfigFile.sync(filePath); if (configFile) { context.logger.log(path.relative(process.cwd(), configFile)); } else { process.exit(1); } } function writeOutput(result, options) { // Don't use `console.log` here since it adds an extra newline at the end. process.stdout.write(result.formatted); if (options.cursorOffset >= 0) { process.stderr.write(result.cursorOffset + "\n"); } } function listDifferent(context, input, options, filename) { if (!context.argv["list-different"]) { return; } options = Object.assign({}, options, { filepath: filename }); if (!prettier$2.check(input, options)) { if (!context.argv["write"]) { context.logger.log(filename); } process.exitCode = 1; } return true; } function format$1(context, input, opt) { if (context.argv["debug-print-doc"]) { const doc = prettier$2.__debug.printToDoc(input, opt); return { formatted: prettier$2.__debug.formatDoc(doc) }; } if (context.argv["debug-check"]) { const pp = prettier$2.format(input, opt); const pppp = prettier$2.format(pp, opt); if (pp !== pppp) { throw new errors.DebugError( "prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp) ); } else { const normalizedOpts = options$12.normalize(opt); const ast = cleanAST( prettier$2.__debug.parse(input, opt).ast, normalizedOpts ); const past = cleanAST( prettier$2.__debug.parse(pp, opt).ast, normalizedOpts ); if (ast !== past) { const MAX_AST_SIZE = 2097152; // 2MB const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past); throw new errors.DebugError( "ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp) ); } } return { formatted: opt.filepath || "(stdin)\n" }; } return prettier$2.formatWithCursor(input, opt); } function getOptionsOrDie(context, filePath) { try { if (context.argv["config"] === false) { context.logger.debug( "'--no-config' option found, skip loading config file." ); return null; } context.logger.debug( context.argv["config"] ? `load config file from '${context.argv["config"]}'` : `resolve config from '${filePath}'` ); const options = resolveConfig_1.resolveConfig.sync(filePath, { editorconfig: context.argv["editorconfig"], config: context.argv["config"] }); context.logger.debug("loaded options `" + JSON.stringify(options) + "`"); return options; } catch (error) { context.logger.error("Invalid configuration file: " + error.message); process.exit(2); } } function getOptionsForFile(context, filepath) { const options = getOptionsOrDie(context, filepath); const hasPlugins = options && options.plugins; if (hasPlugins) { pushContextPlugins(context, options.plugins); } const appliedOptions = Object.assign( { filepath }, applyConfigPrecedence( context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, { logger: context.logger }) ) ); context.logger.debug( `applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}` ); if (hasPlugins) { popContextPlugins(context); } return appliedOptions; } function parseArgsToOptions(context, overrideDefaults) { const minimistOptions = createMinimistOptions(context.detailedOptions); const apiDetailedOptionMap = createApiDetailedOptionMap( context.detailedOptions ); return getOptions( optionsNormalizer.normalizeCliOptions( minimist_1( context.args, Object.assign({ string: minimistOptions.string, boolean: minimistOptions.boolean, default: cliifyOptions(overrideDefaults, apiDetailedOptionMap) }) ), context.detailedOptions, { logger: false } ), context.detailedOptions ); } function applyConfigPrecedence(context, options) { try { switch (context.argv["config-precedence"]) { case "cli-override": return parseArgsToOptions(context, options); case "file-override": return Object.assign({}, parseArgsToOptions(context), options); case "prefer-file": return options || parseArgsToOptions(context); } } catch (error) { context.logger.error(error.toString()); process.exit(2); } } function formatStdin(context) { const filepath = context.argv["stdin-filepath"] ? path.resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd(); const ignorer = createIgnorer(context); const relativeFilepath = path.relative(process.cwd(), filepath); thirdParty$1.getStream(process.stdin).then(input => { if (relativeFilepath && ignorer.filter([relativeFilepath]).length === 0) { writeOutput({ formatted: input }, {}); return; } const options = getOptionsForFile(context, filepath); if (listDifferent(context, input, options, "(stdin)")) { return; } try { writeOutput(format$1(context, input, options), options); } catch (error) { handleError(context, "stdin", error); } }); } function createIgnorer(context) { const ignoreFilePath = path.resolve(context.argv["ignore-path"]); let ignoreText = ""; try { ignoreText = fs.readFileSync(ignoreFilePath, "utf8"); } catch (readError) { if (readError.code !== "ENOENT") { context.logger.error( `Unable to read ${ignoreFilePath}: ` + readError.message ); process.exit(2); } } return ignore().add(ignoreText); } function eachFilename(context, patterns, callback) { const ignoreNodeModules = context.argv["with-node-modules"] !== true; if (ignoreNodeModules) { patterns = patterns.concat(["!**/node_modules/**", "!./node_modules/**"]); } try { const filePaths = globby .sync(patterns, { dot: true, nodir: true }) .map(filePath => path.relative(process.cwd(), filePath)); if (filePaths.length === 0) { context.logger.error( `No matching files. Patterns tried: ${patterns.join(" ")}` ); process.exitCode = 2; return; } filePaths.forEach(filePath => callback(filePath, getOptionsForFile(context, filePath)) ); } catch (error) { context.logger.error( `Unable to expand glob patterns: ${patterns.join(" ")}\n${error.message}` ); // Don't exit the process if one pattern failed process.exitCode = 2; } } function formatFiles(context) { // The ignorer will be used to filter file paths after the glob is checked, // before any files are actually written const ignorer = createIgnorer(context); eachFilename(context, context.filePatterns, (filename, options) => { const fileIgnored = ignorer.filter([filename]).length === 0; if ( fileIgnored && (context.argv["write"] || context.argv["list-different"]) ) { return; } if (context.argv["write"] && process.stdout.isTTY) { // Don't use `console.log` here since we need to replace this line. context.logger.log(filename, { newline: false }); } let input; try { input = fs.readFileSync(filename, "utf8"); } catch (error) { // Add newline to split errors from filename line. context.logger.log(""); context.logger.error( `Unable to read file: ${filename}\n${error.message}` ); // Don't exit the process if one file failed process.exitCode = 2; return; } if (fileIgnored) { writeOutput({ formatted: input }, options); return; } listDifferent(context, input, options, filename); const start = Date.now(); let result; let output; try { result = format$1( context, input, Object.assign({}, options, { filepath: filename }) ); output = result.formatted; } catch (error) { // Add newline to split errors from filename line. process.stdout.write("\n"); handleError(context, filename, error); return; } if (context.argv["write"]) { if (process.stdout.isTTY) { // Remove previously printed filename to log it with duration. readline.clearLine(process.stdout, 0); readline.cursorTo(process.stdout, 0, null); } // Don't write the file if it won't change in order not to invalidate // mtime based caches. if (output === input) { if (!context.argv["list-different"]) { context.logger.log(`${chalk$2.grey(filename)} ${Date.now() - start}ms`); } } else { if (context.argv["list-different"]) { context.logger.log(filename); } else { context.logger.log(`${filename} ${Date.now() - start}ms`); } try { fs.writeFileSync(filename, output, "utf8"); } catch (error) { context.logger.error( `Unable to write file: ${filename}\n${error.message}` ); // Don't exit the process if one file failed process.exitCode = 2; } } } else if (context.argv["debug-check"]) { if (output) { context.logger.log(output); } else { process.exitCode = 2; } } else if (!context.argv["list-different"]) { writeOutput(result, options); } }); } function getOptionsWithOpposites(options) { // Add --no-foo after --foo. const optionsWithOpposites = options.map(option => [ option.description ? option : null, option.oppositeDescription ? Object.assign({}, option, { name: `no-${option.name}`, type: "boolean", description: option.oppositeDescription }) : null ]); return flattenArray(optionsWithOpposites).filter(Boolean); } function createUsage(context) { const options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag> option => !( option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-") ) ); const groupedOptions = groupBy(options, option => option.category); const firstCategories = constant.categoryOrder.slice(0, -1); const lastCategories = constant.categoryOrder.slice(-1); const restCategories = Object.keys(groupedOptions).filter( category => firstCategories.indexOf(category) === -1 && lastCategories.indexOf(category) === -1 ); const allCategories = firstCategories.concat(restCategories, lastCategories); const optionsUsage = allCategories.map(category => { const categoryOptions = groupedOptions[category] .map(option => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)) .join("\n"); return `${category} options:\n\n${indent$9(categoryOptions, 2)}`; }); return [constant.usageSummary].concat(optionsUsage, [""]).join("\n\n"); } function createOptionUsage(context, option, threshold) { const header = createOptionUsageHeader(option); const optionDefaultValue = getOptionDefaultValue(context, option.name); return createOptionUsageRow( header, `${option.description}${ optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.` }`, threshold ); } function createDefaultValueDisplay(value) { return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value; } function createOptionUsageHeader(option) { const name = `--${option.name}`; const alias = option.alias ? `-${option.alias},` : null; const type = createOptionUsageType(option); return [alias, name, type].filter(Boolean).join(" "); } function createOptionUsageRow(header, content, threshold) { const separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length); const description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`); return `${header}${separator}${description}`; } function createOptionUsageType(option) { switch (option.type) { case "boolean": return null; case "choice": return `<${option.choices .filter(choice => !choice.deprecated) .map(choice => choice.value) .join("|")}>`; default: return `<${option.type}>`; } } function flattenArray(array) { return [].concat.apply([], array); } function getOptionWithLevenSuggestion(context, options, optionName) { // support aliases const optionNameContainers = flattenArray( options.map((option, index) => [ { value: option.name, index }, option.alias ? { value: option.alias, index } : null ]) ).filter(Boolean); const optionNameContainer = optionNameContainers.find( optionNameContainer => optionNameContainer.value === optionName ); if (optionNameContainer !== undefined) { return options[optionNameContainer.index]; } const suggestedOptionNameContainer = optionNameContainers.find( optionNameContainer => leven(optionNameContainer.value, optionName) < 3 ); if (suggestedOptionNameContainer !== undefined) { const suggestedOptionName = suggestedOptionNameContainer.value; context.logger.warn( `Unknown option name "${optionName}", did you mean "${suggestedOptionName}"?` ); return options[suggestedOptionNameContainer.index]; } context.logger.warn(`Unknown option name "${optionName}"`); return options.find(option => option.name === "help"); } function createChoiceUsages(choices, margin, indentation) { const activeChoices = choices.filter(choice => !choice.deprecated); const threshold = activeChoices .map(choice => choice.value.length) .reduce((current, length) => Math.max(current, length), 0) + margin; return activeChoices.map(choice => indent$9( createOptionUsageRow(choice.value, choice.description, threshold), indentation ) ); } function createDetailedUsage(context, optionName) { const option = getOptionWithLevenSuggestion( context, getOptionsWithOpposites(context.detailedOptions), optionName ); const header = createOptionUsageHeader(option); const description = `\n\n${indent$9(option.description, 2)}`; const choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages( option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION ).join("\n")}`; const optionDefaultValue = getOptionDefaultValue(context, option.name); const defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : ""; const pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map( key => `\n* ${key}: ${createDefaultValueDisplay( option.pluginDefaults[key] )}` )}` : ""; return `${header}${description}${choices}${defaults}${pluginDefaults}`; } function getOptionDefaultValue(context, optionName) { // --no-option if (!(optionName in context.detailedOptionMap)) { return undefined; } const option = context.detailedOptionMap[optionName]; if (option.default !== undefined) { return option.default; } const optionCamelName = camelcase(optionName); if (optionCamelName in context.apiDefaultOptions) { return context.apiDefaultOptions[optionCamelName]; } return undefined; } function indent$9(str, spaces) { return str.replace(/^/gm, " ".repeat(spaces)); } function groupBy(array, getKey) { return array.reduce((obj, item) => { const key = getKey(item); const previousItems = key in obj ? obj[key] : []; return Object.assign({}, obj, { [key]: previousItems.concat(item) }); }, Object.create(null)); } function pick(object, keys) { return !keys ? object : keys.reduce( (reduced, key) => Object.assign(reduced, { [key]: object[key] }), {} ); } function createLogger(logLevel) { return { warn: createLogFunc("warn", "yellow"), error: createLogFunc("error", "red"), debug: createLogFunc("debug", "blue"), log: createLogFunc("log") }; function createLogFunc(loggerName, color) { if (!shouldLog(loggerName)) { return () => {}; } const prefix = color ? `[${chalk$2[color](loggerName)}] ` : ""; return function(message, opts) { opts = Object.assign({ newline: true }, opts); const stream = process[loggerName === "log" ? "stdout" : "stderr"]; stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : "")); }; } function shouldLog(loggerName) { switch (logLevel) { case "silent": return false; default: return true; case "debug": if (loggerName === "debug") { return true; } // fall through case "log": if (loggerName === "log") { return true; } // fall through case "warn": if (loggerName === "warn") { return true; } // fall through case "error": return loggerName === "error"; } } } function normalizeDetailedOption(name, option) { return Object.assign({ category: constant.CATEGORY_OTHER }, option, { choices: option.choices && option.choices.map(choice => { const newChoice = Object.assign( { description: "", deprecated: false }, typeof choice === "object" ? choice : { value: choice } ); if (newChoice.value === true) { newChoice.value = ""; // backward compability for original boolean option } return newChoice; }) }); } function normalizeDetailedOptionMap(detailedOptionMap) { return Object.keys(detailedOptionMap) .sort() .reduce((normalized, name) => { const option = detailedOptionMap[name]; return Object.assign(normalized, { [name]: normalizeDetailedOption(name, option) }); }, {}); } function createMinimistOptions(detailedOptions) { return { boolean: detailedOptions .filter(option => option.type === "boolean") .map(option => option.name), string: detailedOptions .filter(option => option.type !== "boolean") .map(option => option.name), default: detailedOptions .filter(option => !option.deprecated) .filter(option => !option.forwardToApi || option.name === "plugin") .filter(option => option.default !== undefined) .reduce( (current, option) => Object.assign({ [option.name]: option.default }, current), {} ), alias: detailedOptions .filter(option => option.alias !== undefined) .reduce( (current, option) => Object.assign({ [option.name]: option.alias }, current), {} ) }; } function createApiDetailedOptionMap(detailedOptions) { return detailedOptions.reduce( (current, option) => option.forwardToApi && option.forwardToApi !== option.name ? Object.assign(current, { [option.forwardToApi]: option }) : current, {} ); } function createDetailedOptionMap(supportOptions) { return supportOptions.reduce((reduced, option) => { const newOption = Object.assign({}, option, { name: option.cliName || dashify(option.name), description: option.cliDescription || option.description, category: option.cliCategory || constant.CATEGORY_FORMAT, forwardToApi: option.name }); if (option.deprecated) { delete newOption.forwardToApi; delete newOption.description; delete newOption.oppositeDescription; newOption.deprecated = true; } return Object.assign(reduced, { [newOption.name]: newOption }); }, {}); } //-----------------------------context-util-start------------------------------- /** * @typedef {Object} Context * @property logger * @property args * @property argv * @property filePatterns * @property supportOptions * @property detailedOptions * @property detailedOptionMap * @property apiDefaultOptions */ function createContext(args) { const context = { args }; updateContextArgv(context); normalizeContextArgv(context, ["loglevel", "plugin"]); context.logger = createLogger(context.argv["loglevel"]); updateContextArgv(context, context.argv["plugin"]); return context; } function initContext(context) { // split into 2 step so that we could wrap this in a `try..catch` in cli/index.js normalizeContextArgv(context); } function updateContextOptions(context, plugins) { const supportOptions = getSupportInfo$3(null, { showDeprecated: true, showUnreleased: true, showInternal: true, plugins }).options; const detailedOptionMap = normalizeDetailedOptionMap( Object.assign({}, createDetailedOptionMap(supportOptions), constant.options) ); const detailedOptions = util$1.arrayify(detailedOptionMap, "name"); const apiDefaultOptions = supportOptions .filter(optionInfo => !optionInfo.deprecated) .reduce( (reduced, optionInfo) => Object.assign(reduced, { [optionInfo.name]: optionInfo.default }), Object.assign({}, options$12.hiddenDefaults) ); context.supportOptions = supportOptions; context.detailedOptions = detailedOptions; context.detailedOptionMap = detailedOptionMap; context.apiDefaultOptions = apiDefaultOptions; } function pushContextPlugins(context, plugins) { context._supportOptions = context.supportOptions; context._detailedOptions = context.detailedOptions; context._detailedOptionMap = context.detailedOptionMap; context._apiDefaultOptions = context.apiDefaultOptions; updateContextOptions(context, plugins); } function popContextPlugins(context) { context.supportOptions = context._supportOptions; context.detailedOptions = context._detailedOptions; context.detailedOptionMap = context._detailedOptionMap; context.apiDefaultOptions = context._apiDefaultOptions; } function updateContextArgv(context, plugins) { pushContextPlugins(context, plugins); const minimistOptions = createMinimistOptions(context.detailedOptions); const argv = minimist_1(context.args, minimistOptions); context.argv = argv; context.filePatterns = argv["_"]; } function normalizeContextArgv(context, keys) { const detailedOptions = !keys ? context.detailedOptions : context.detailedOptions.filter( option => keys.indexOf(option.name) !== -1 ); const argv = !keys ? context.argv : pick(context.argv, keys); context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, { logger: context.logger }); } //------------------------------context-util-end-------------------------------- var util_1 = { createContext, createDetailedOptionMap, createDetailedUsage, createUsage, format: format$1, formatFiles, formatStdin, initContext, logResolvedConfigPathOrDie, normalizeDetailedOptionMap }; function run(args) { const context = util_1.createContext(args); try { util_1.initContext(context); context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`); if (context.argv["write"] && context.argv["debug-check"]) { context.logger.error("Cannot use --write and --debug-check together."); process.exit(1); } if (context.argv["find-config-path"] && context.filePatterns.length) { context.logger.error("Cannot use --find-config-path with multiple files"); process.exit(1); } if (context.argv["version"]) { context.logger.log(prettier$2.version); process.exit(0); } if (context.argv["help"] !== undefined) { context.logger.log( typeof context.argv["help"] === "string" && context.argv["help"] !== "" ? util_1.createDetailedUsage(context, context.argv["help"]) : util_1.createUsage(context) ); process.exit(0); } if (context.argv["support-info"]) { context.logger.log( prettier$2.format(jsonStableStringify(prettier$2.getSupportInfo()), { parser: "json" }) ); process.exit(0); } const hasFilePatterns = context.filePatterns.length !== 0; const useStdin = context.argv["stdin"] || (!hasFilePatterns && !process.stdin.isTTY); if (context.argv["find-config-path"]) { util_1.logResolvedConfigPathOrDie( context, context.argv["find-config-path"] ); } else if (useStdin) { util_1.formatStdin(context); } else if (hasFilePatterns) { util_1.formatFiles(context); } else { context.logger.log(util_1.createUsage(context)); process.exit(1); } } catch (error) { context.logger.error(error.message); process.exit(1); } } var cli = { run }; cli.run(process.argv.slice(2)); var prettier = { }; module.exports = prettier; kodo - Gogs: Go Git Service

暫無描述

aboutus.html 1.7KB

    <!doctype html> <html> <head> <meta charset="UTF-8"> <title>拍爱 PAI.AI 关于我们</title> <meta name="keywords" content="摄影 图片 影像 分享 交流 社交 交友 摄影师 女性 孩子 亲子 旅行 旅游 约拍 iphone android app" /> <link href="css/layout.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <div id="header"> <div class="content"> <a href="index.html" target="_self" class="logo"></a> <div class="navigation"> <a href="contactus.html" target="_self" >联系我们</a> <a href="joinus.html" target="_self" >加入拍爱</a> <a href="aboutus.html" target="_self"class="current" >关于我们</a> <a href="index.html" target="_self" >首页</a> </div> </div> </div> <div id="container" > <div class="content aboutus"> <div class="container_box"> <p><strong>关于拍爱 PAI.AI </strong><br> 一起走过的路,<br> 一起看过的美景,<br> 一起醉过的Party,<br> ……<br> 回忆容易消逝,<br> 一起拍,<br> 照片让爱历久弥新。<br> 拍爱——用心拍,分享爱<br> 拍爱让您和小伙伴更便捷、更快速——几乎是一瞬间,分享拍摄的照片。<br> 不论是聚会,还是旅行。<br> 拍摄即分享。<br> 你可以对照片点赞、评论,零距离互动。<br> 不论手机丢失还是损坏,<br> 照片一直在拍爱等你。 </p> </div> </div> </div> <div id="footer"> <div class="content foot"> <a href="aboutus.html" target="_self" >关于我们</a> <span>|</span> <a href="contactus.html" target="_self" >联系我们</a> ©2016 拍爱 PAI.AI 琼ICP备16000076号 </div> </div> </body> </html>