(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.OmegaTarget = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],2:[function(require,module,exports){ (function (process,global){ /* @preserve * The MIT License (MIT) * * Copyright (c) 2013-2015 Petka Antonov * * 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. * */ /** * bluebird build version 2.11.0 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0; }; Async.prototype.throwLater = function(fn, arg) { if (arguments.length === 1) { arg = fn; fn = function () { throw arg; }; } if (typeof setTimeout !== "undefined") { setTimeout(function() { fn(arg); }, 0); } else try { this._schedule(function() { fn(arg); }); } catch (e) { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); } }; function AsyncInvokeLater(fn, receiver, arg) { this._lateQueue.push(fn, receiver, arg); this._queueTick(); } function AsyncInvoke(fn, receiver, arg) { this._normalQueue.push(fn, receiver, arg); this._queueTick(); } function AsyncSettlePromises(promise) { this._normalQueue._pushOne(promise); this._queueTick(); } if (!util.hasDevTools) { Async.prototype.invokeLater = AsyncInvokeLater; Async.prototype.invoke = AsyncInvoke; Async.prototype.settlePromises = AsyncSettlePromises; } else { if (schedule.isStatic) { schedule = function(fn) { setTimeout(fn, 0); }; } Async.prototype.invokeLater = function (fn, receiver, arg) { if (this._trampolineEnabled) { AsyncInvokeLater.call(this, fn, receiver, arg); } else { this._schedule(function() { setTimeout(function() { fn.call(receiver, arg); }, 100); }); } }; Async.prototype.invoke = function (fn, receiver, arg) { if (this._trampolineEnabled) { AsyncInvoke.call(this, fn, receiver, arg); } else { this._schedule(function() { fn.call(receiver, arg); }); } }; Async.prototype.settlePromises = function(promise) { if (this._trampolineEnabled) { AsyncSettlePromises.call(this, promise); } else { this._schedule(function() { promise._settlePromises(); }); } }; } Async.prototype.invokeFirst = function (fn, receiver, arg) { this._normalQueue.unshift(fn, receiver, arg); this._queueTick(); }; Async.prototype._drainQueue = function(queue) { while (queue.length() > 0) { var fn = queue.shift(); if (typeof fn !== "function") { fn._settlePromises(); continue; } var receiver = queue.shift(); var arg = queue.shift(); fn.call(receiver, arg); } }; Async.prototype._drainQueues = function () { this._drainQueue(this._normalQueue); this._reset(); this._drainQueue(this._lateQueue); }; Async.prototype._queueTick = function () { if (!this._isTickUsed) { this._isTickUsed = true; this._schedule(this.drainQueues); } }; Async.prototype._reset = function () { this._isTickUsed = false; }; module.exports = new Async(); module.exports.firstLineError = firstLineError; },{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise) { var rejectThis = function(_, e) { this._reject(e); }; var targetRejected = function(e, context) { context.promiseRejectionQueued = true; context.bindingPromise._then(rejectThis, rejectThis, null, this, e); }; var bindingResolved = function(thisArg, context) { if (this._isPending()) { this._resolveCallback(context.target); } }; var bindingRejected = function(e, context) { if (!context.promiseRejectionQueued) this._reject(e); }; Promise.prototype.bind = function (thisArg) { var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); ret._propagateFrom(this, 1); var target = this._target(); ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { var context = { promiseRejectionQueued: false, promise: ret, target: target, bindingPromise: maybePromise }; target._then(INTERNAL, targetRejected, ret._progress, ret, context); maybePromise._then( bindingResolved, bindingRejected, ret._progress, ret, context); } else { ret._resolveCallback(target); } return ret; }; Promise.prototype._setBoundTo = function (obj) { if (obj !== undefined) { this._bitField = this._bitField | 131072; this._boundTo = obj; } else { this._bitField = this._bitField & (~131072); } }; Promise.prototype._isBound = function () { return (this._bitField & 131072) === 131072; }; Promise.bind = function (thisArg, value) { var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { maybePromise._then(function() { ret._resolveCallback(value); }, ret._reject, ret._progress, ret, null); } else { ret._resolveCallback(value); } return ret; }; }; },{}],4:[function(_dereq_,module,exports){ "use strict"; var old; if (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = _dereq_("./promise.js")(); bluebird.noConflict = noConflict; module.exports = bluebird; },{"./promise.js":23}],5:[function(_dereq_,module,exports){ "use strict"; var cr = Object.create; if (cr) { var callerCache = cr(null); var getterCache = cr(null); callerCache[" size"] = getterCache[" size"] = 0; } module.exports = function(Promise) { var util = _dereq_("./util.js"); var canEvaluate = util.canEvaluate; var isIdentifier = util.isIdentifier; var getMethodCaller; var getGetter; if (!true) { var makeMethodCaller = function (methodName) { return new Function("ensureMethod", " \n\ return function(obj) { \n\ 'use strict' \n\ var len = this.length; \n\ ensureMethod(obj, 'methodName'); \n\ switch(len) { \n\ case 1: return obj.methodName(this[0]); \n\ case 2: return obj.methodName(this[0], this[1]); \n\ case 3: return obj.methodName(this[0], this[1], this[2]); \n\ case 0: return obj.methodName(); \n\ default: \n\ return obj.methodName.apply(obj, this); \n\ } \n\ }; \n\ ".replace(/methodName/g, methodName))(ensureMethod); }; var makeGetter = function (propertyName) { return new Function("obj", " \n\ 'use strict'; \n\ return obj.propertyName; \n\ ".replace("propertyName", propertyName)); }; var getCompiled = function(name, compiler, cache) { var ret = cache[name]; if (typeof ret !== "function") { if (!isIdentifier(name)) { return null; } ret = compiler(name); cache[name] = ret; cache[" size"]++; if (cache[" size"] > 512) { var keys = Object.keys(cache); for (var i = 0; i < 256; ++i) delete cache[keys[i]]; cache[" size"] = keys.length - 256; } } return ret; }; getMethodCaller = function(name) { return getCompiled(name, makeMethodCaller, callerCache); }; getGetter = function(name) { return getCompiled(name, makeGetter, getterCache); }; } function ensureMethod(obj, methodName) { var fn; if (obj != null) fn = obj[methodName]; if (typeof fn !== "function") { var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'"; throw new Promise.TypeError(message); } return fn; } function caller(obj) { var methodName = this.pop(); var fn = ensureMethod(obj, methodName); return fn.apply(obj, this); } Promise.prototype.call = function (methodName) { var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} if (!true) { if (canEvaluate) { var maybeCaller = getMethodCaller(methodName); if (maybeCaller !== null) { return this._then( maybeCaller, undefined, undefined, args, undefined); } } } args.push(methodName); return this._then(caller, undefined, undefined, args, undefined); }; function namedGetter(obj) { return obj[this]; } function indexedGetter(obj) { var index = +this; if (index < 0) index = Math.max(0, index + obj.length); return obj[index]; } Promise.prototype.get = function (propertyName) { var isIndex = (typeof propertyName === "number"); var getter; if (!isIndex) { if (canEvaluate) { var maybeGetter = getGetter(propertyName); getter = maybeGetter !== null ? maybeGetter : namedGetter; } else { getter = namedGetter; } } else { getter = indexedGetter; } return this._then(getter, undefined, undefined, propertyName, undefined); }; }; },{"./util.js":38}],6:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var errors = _dereq_("./errors.js"); var async = _dereq_("./async.js"); var CancellationError = errors.CancellationError; Promise.prototype._cancel = function (reason) { if (!this.isCancellable()) return this; var parent; var promiseToReject = this; while ((parent = promiseToReject._cancellationParent) !== undefined && parent.isCancellable()) { promiseToReject = parent; } this._unsetCancellable(); promiseToReject._target()._rejectCallback(reason, false, true); }; Promise.prototype.cancel = function (reason) { if (!this.isCancellable()) return this; if (reason === undefined) reason = new CancellationError(); async.invokeLater(this._cancel, this, reason); return this; }; Promise.prototype.cancellable = function () { if (this._cancellable()) return this; async.enableTrampoline(); this._setCancellable(); this._cancellationParent = undefined; return this; }; Promise.prototype.uncancellable = function () { var ret = this.then(); ret._unsetCancellable(); return ret; }; Promise.prototype.fork = function (didFulfill, didReject, didProgress) { var ret = this._then(didFulfill, didReject, didProgress, undefined, undefined); ret._setCancellable(); ret._cancellationParent = undefined; return ret; }; }; },{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){ "use strict"; module.exports = function() { var async = _dereq_("./async.js"); var util = _dereq_("./util.js"); var bluebirdFramePattern = /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; var stackFramePattern = null; var formatStack = null; var indentStackFrames = false; var warn; function CapturedTrace(parent) { this._parent = parent; var length = this._length = 1 + (parent === undefined ? 0 : parent._length); captureStackTrace(this, CapturedTrace); if (length > 32) this.uncycle(); } util.inherits(CapturedTrace, Error); CapturedTrace.prototype.uncycle = function() { var length = this._length; if (length < 2) return; var nodes = []; var stackToIndex = {}; for (var i = 0, node = this; node !== undefined; ++i) { nodes.push(node); node = node._parent; } length = this._length = i; for (var i = length - 1; i >= 0; --i) { var stack = nodes[i].stack; if (stackToIndex[stack] === undefined) { stackToIndex[stack] = i; } } for (var i = 0; i < length; ++i) { var currentStack = nodes[i].stack; var index = stackToIndex[currentStack]; if (index !== undefined && index !== i) { if (index > 0) { nodes[index - 1]._parent = undefined; nodes[index - 1]._length = 1; } nodes[i]._parent = undefined; nodes[i]._length = 1; var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; if (index < length - 1) { cycleEdgeNode._parent = nodes[index + 1]; cycleEdgeNode._parent.uncycle(); cycleEdgeNode._length = cycleEdgeNode._parent._length + 1; } else { cycleEdgeNode._parent = undefined; cycleEdgeNode._length = 1; } var currentChildLength = cycleEdgeNode._length + 1; for (var j = i - 2; j >= 0; --j) { nodes[j]._length = currentChildLength; currentChildLength++; } return; } } }; CapturedTrace.prototype.parent = function() { return this._parent; }; CapturedTrace.prototype.hasParent = function() { return this._parent !== undefined; }; CapturedTrace.prototype.attachExtraTrace = function(error) { if (error.__stackCleaned__) return; this.uncycle(); var parsed = CapturedTrace.parseStackAndMessage(error); var message = parsed.message; var stacks = [parsed.stack]; var trace = this; while (trace !== undefined) { stacks.push(cleanStack(trace.stack.split("\n"))); trace = trace._parent; } removeCommonRoots(stacks); removeDuplicateOrEmptyJumps(stacks); util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); util.notEnumerableProp(error, "__stackCleaned__", true); }; function reconstructStack(message, stacks) { for (var i = 0; i < stacks.length - 1; ++i) { stacks[i].push("From previous event:"); stacks[i] = stacks[i].join("\n"); } if (i < stacks.length) { stacks[i] = stacks[i].join("\n"); } return message + "\n" + stacks.join("\n"); } function removeDuplicateOrEmptyJumps(stacks) { for (var i = 0; i < stacks.length; ++i) { if (stacks[i].length === 0 || ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { stacks.splice(i, 1); i--; } } } function removeCommonRoots(stacks) { var current = stacks[0]; for (var i = 1; i < stacks.length; ++i) { var prev = stacks[i]; var currentLastIndex = current.length - 1; var currentLastLine = current[currentLastIndex]; var commonRootMeetPoint = -1; for (var j = prev.length - 1; j >= 0; --j) { if (prev[j] === currentLastLine) { commonRootMeetPoint = j; break; } } for (var j = commonRootMeetPoint; j >= 0; --j) { var line = prev[j]; if (current[currentLastIndex] === line) { current.pop(); currentLastIndex--; } else { break; } } current = prev; } } function cleanStack(stack) { var ret = []; for (var i = 0; i < stack.length; ++i) { var line = stack[i]; var isTraceLine = stackFramePattern.test(line) || " (No stack trace)" === line; var isInternalFrame = isTraceLine && shouldIgnore(line); if (isTraceLine && !isInternalFrame) { if (indentStackFrames && line.charAt(0) !== " ") { line = " " + line; } ret.push(line); } } return ret; } function stackFramesAsArray(error) { var stack = error.stack.replace(/\s+$/g, "").split("\n"); for (var i = 0; i < stack.length; ++i) { var line = stack[i]; if (" (No stack trace)" === line || stackFramePattern.test(line)) { break; } } if (i > 0) { stack = stack.slice(i); } return stack; } CapturedTrace.parseStackAndMessage = function(error) { var stack = error.stack; var message = error.toString(); stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error) : [" (No stack trace)"]; return { message: message, stack: cleanStack(stack) }; }; CapturedTrace.formatAndLogError = function(error, title) { if (typeof console !== "undefined") { var message; if (typeof error === "object" || typeof error === "function") { var stack = error.stack; message = title + formatStack(stack, error); } else { message = title + String(error); } if (typeof warn === "function") { warn(message); } else if (typeof console.log === "function" || typeof console.log === "object") { console.log(message); } } }; CapturedTrace.unhandledRejection = function (reason) { CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: "); }; CapturedTrace.isSupported = function () { return typeof captureStackTrace === "function"; }; CapturedTrace.fireRejectionEvent = function(name, localHandler, reason, promise) { var localEventFired = false; try { if (typeof localHandler === "function") { localEventFired = true; if (name === "rejectionHandled") { localHandler(promise); } else { localHandler(reason, promise); } } } catch (e) { async.throwLater(e); } var globalEventFired = false; try { globalEventFired = fireGlobalEvent(name, reason, promise); } catch (e) { globalEventFired = true; async.throwLater(e); } var domEventFired = false; if (fireDomEvent) { try { domEventFired = fireDomEvent(name.toLowerCase(), { reason: reason, promise: promise }); } catch (e) { domEventFired = true; async.throwLater(e); } } if (!globalEventFired && !localEventFired && !domEventFired && name === "unhandledRejection") { CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); } }; function formatNonError(obj) { var str; if (typeof obj === "function") { str = "[function " + (obj.name || "anonymous") + "]"; } else { str = obj.toString(); var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; if (ruselessToString.test(str)) { try { var newStr = JSON.stringify(obj); str = newStr; } catch(e) { } } if (str.length === 0) { str = "(empty array)"; } } return ("(<" + snip(str) + ">, no stack trace)"); } function snip(str) { var maxChars = 41; if (str.length < maxChars) { return str; } return str.substr(0, maxChars - 3) + "..."; } var shouldIgnore = function() { return false; }; var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; function parseLineInfo(line) { var matches = line.match(parseLineInfoRegex); if (matches) { return { fileName: matches[1], line: parseInt(matches[2], 10) }; } } CapturedTrace.setBounds = function(firstLineError, lastLineError) { if (!CapturedTrace.isSupported()) return; var firstStackLines = firstLineError.stack.split("\n"); var lastStackLines = lastLineError.stack.split("\n"); var firstIndex = -1; var lastIndex = -1; var firstFileName; var lastFileName; for (var i = 0; i < firstStackLines.length; ++i) { var result = parseLineInfo(firstStackLines[i]); if (result) { firstFileName = result.fileName; firstIndex = result.line; break; } } for (var i = 0; i < lastStackLines.length; ++i) { var result = parseLineInfo(lastStackLines[i]); if (result) { lastFileName = result.fileName; lastIndex = result.line; break; } } if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || firstFileName !== lastFileName || firstIndex >= lastIndex) { return; } shouldIgnore = function(line) { if (bluebirdFramePattern.test(line)) return true; var info = parseLineInfo(line); if (info) { if (info.fileName === firstFileName && (firstIndex <= info.line && info.line <= lastIndex)) { return true; } } return false; }; }; var captureStackTrace = (function stackDetection() { var v8stackFramePattern = /^\s*at\s*/; var v8stackFormatter = function(stack, error) { if (typeof stack === "string") return stack; if (error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { Error.stackTraceLimit = Error.stackTraceLimit + 6; stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; var captureStackTrace = Error.captureStackTrace; shouldIgnore = function(line) { return bluebirdFramePattern.test(line); }; return function(receiver, ignoreUntil) { Error.stackTraceLimit = Error.stackTraceLimit + 6; captureStackTrace(receiver, ignoreUntil); Error.stackTraceLimit = Error.stackTraceLimit - 6; }; } var err = new Error(); if (typeof err.stack === "string" && err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { stackFramePattern = /@/; formatStack = v8stackFormatter; indentStackFrames = true; return function captureStackTrace(o) { o.stack = new Error().stack; }; } var hasStackAfterThrow; try { throw new Error(); } catch(e) { hasStackAfterThrow = ("stack" in e); } if (!("stack" in err) && hasStackAfterThrow && typeof Error.stackTraceLimit === "number") { stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; return function captureStackTrace(o) { Error.stackTraceLimit = Error.stackTraceLimit + 6; try { throw new Error(); } catch(e) { o.stack = e.stack; } Error.stackTraceLimit = Error.stackTraceLimit - 6; }; } formatStack = function(stack, error) { if (typeof stack === "string") return stack; if ((typeof error === "object" || typeof error === "function") && error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; return null; })([]); var fireDomEvent; var fireGlobalEvent = (function() { if (util.isNode) { return function(name, reason, promise) { if (name === "rejectionHandled") { return process.emit(name, promise); } else { return process.emit(name, reason, promise); } }; } else { var customEventWorks = false; var anyEventWorks = true; try { var ev = new self.CustomEvent("test"); customEventWorks = ev instanceof CustomEvent; } catch (e) {} if (!customEventWorks) { try { var event = document.createEvent("CustomEvent"); event.initCustomEvent("testingtheevent", false, true, {}); self.dispatchEvent(event); } catch (e) { anyEventWorks = false; } } if (anyEventWorks) { fireDomEvent = function(type, detail) { var event; if (customEventWorks) { event = new self.CustomEvent(type, { detail: detail, bubbles: false, cancelable: true }); } else if (self.dispatchEvent) { event = document.createEvent("CustomEvent"); event.initCustomEvent(type, false, true, detail); } return event ? !self.dispatchEvent(event) : false; }; } var toWindowMethodNameMap = {}; toWindowMethodNameMap["unhandledRejection"] = ("on" + "unhandledRejection").toLowerCase(); toWindowMethodNameMap["rejectionHandled"] = ("on" + "rejectionHandled").toLowerCase(); return function(name, reason, promise) { var methodName = toWindowMethodNameMap[name]; var method = self[methodName]; if (!method) return false; if (name === "rejectionHandled") { method.call(self, promise); } else { method.call(self, reason, promise); } return true; }; } })(); if (typeof console !== "undefined" && typeof console.warn !== "undefined") { warn = function (message) { console.warn(message); }; if (util.isNode && process.stderr.isTTY) { warn = function(message) { process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); }; } else if (!util.isNode && typeof (new Error().stack) === "string") { warn = function(message) { console.warn("%c" + message, "color: red"); }; } } return CapturedTrace; }; },{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){ "use strict"; module.exports = function(NEXT_FILTER) { var util = _dereq_("./util.js"); var errors = _dereq_("./errors.js"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var keys = _dereq_("./es5.js").keys; var TypeError = errors.TypeError; function CatchFilter(instances, callback, promise) { this._instances = instances; this._callback = callback; this._promise = promise; } function safePredicate(predicate, e) { var safeObject = {}; var retfilter = tryCatch(predicate).call(safeObject, e); if (retfilter === errorObj) return retfilter; var safeKeys = keys(safeObject); if (safeKeys.length) { errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); return errorObj; } return retfilter; } CatchFilter.prototype.doFilter = function (e) { var cb = this._callback; var promise = this._promise; var boundTo = promise._boundValue(); for (var i = 0, len = this._instances.length; i < len; ++i) { var item = this._instances[i]; var itemIsErrorType = item === Error || (item != null && item.prototype instanceof Error); if (itemIsErrorType && e instanceof item) { var ret = tryCatch(cb).call(boundTo, e); if (ret === errorObj) { NEXT_FILTER.e = ret.e; return NEXT_FILTER; } return ret; } else if (typeof item === "function" && !itemIsErrorType) { var shouldHandle = safePredicate(item, e); if (shouldHandle === errorObj) { e = errorObj.e; break; } else if (shouldHandle) { var ret = tryCatch(cb).call(boundTo, e); if (ret === errorObj) { NEXT_FILTER.e = ret.e; return NEXT_FILTER; } return ret; } } } NEXT_FILTER.e = e; return NEXT_FILTER; }; return CatchFilter; }; },{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, CapturedTrace, isDebugging) { var contextStack = []; function Context() { this._trace = new CapturedTrace(peekContext()); } Context.prototype._pushContext = function () { if (!isDebugging()) return; if (this._trace !== undefined) { contextStack.push(this._trace); } }; Context.prototype._popContext = function () { if (!isDebugging()) return; if (this._trace !== undefined) { contextStack.pop(); } }; function createContext() { if (isDebugging()) return new Context(); } function peekContext() { var lastIndex = contextStack.length - 1; if (lastIndex >= 0) { return contextStack[lastIndex]; } return undefined; } Promise.prototype._peekContext = peekContext; Promise.prototype._pushContext = Context.prototype._pushContext; Promise.prototype._popContext = Context.prototype._popContext; return createContext; }; },{}],10:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, CapturedTrace) { var getDomain = Promise._getDomain; var async = _dereq_("./async.js"); var Warning = _dereq_("./errors.js").Warning; var util = _dereq_("./util.js"); var canAttachTrace = util.canAttachTrace; var unhandledRejectionHandled; var possiblyUnhandledRejection; var debugging = false || (util.isNode && (!!process.env["BLUEBIRD_DEBUG"] || process.env["NODE_ENV"] === "development")); if (util.isNode && process.env["BLUEBIRD_DEBUG"] == 0) debugging = false; if (debugging) { async.disableTrampolineIfNecessary(); } Promise.prototype._ignoreRejections = function() { this._unsetRejectionIsUnhandled(); this._bitField = this._bitField | 16777216; }; Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 16777216) !== 0) return; this._setRejectionIsUnhandled(); async.invokeLater(this._notifyUnhandledRejection, this, undefined); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { CapturedTrace.fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this); }; Promise.prototype._notifyUnhandledRejection = function () { if (this._isRejectionUnhandled()) { var reason = this._getCarriedStackTrace() || this._settledValue; this._setUnhandledRejectionIsNotified(); CapturedTrace.fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this); } }; Promise.prototype._setUnhandledRejectionIsNotified = function () { this._bitField = this._bitField | 524288; }; Promise.prototype._unsetUnhandledRejectionIsNotified = function () { this._bitField = this._bitField & (~524288); }; Promise.prototype._isUnhandledRejectionNotified = function () { return (this._bitField & 524288) > 0; }; Promise.prototype._setRejectionIsUnhandled = function () { this._bitField = this._bitField | 2097152; }; Promise.prototype._unsetRejectionIsUnhandled = function () { this._bitField = this._bitField & (~2097152); if (this._isUnhandledRejectionNotified()) { this._unsetUnhandledRejectionIsNotified(); this._notifyUnhandledRejectionIsHandled(); } }; Promise.prototype._isRejectionUnhandled = function () { return (this._bitField & 2097152) > 0; }; Promise.prototype._setCarriedStackTrace = function (capturedTrace) { this._bitField = this._bitField | 1048576; this._fulfillmentHandler0 = capturedTrace; }; Promise.prototype._isCarryingStackTrace = function () { return (this._bitField & 1048576) > 0; }; Promise.prototype._getCarriedStackTrace = function () { return this._isCarryingStackTrace() ? this._fulfillmentHandler0 : undefined; }; Promise.prototype._captureStackTrace = function () { if (debugging) { this._trace = new CapturedTrace(this._peekContext()); } return this; }; Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { if (debugging && canAttachTrace(error)) { var trace = this._trace; if (trace !== undefined) { if (ignoreSelf) trace = trace._parent; } if (trace !== undefined) { trace.attachExtraTrace(error); } else if (!error.__stackCleaned__) { var parsed = CapturedTrace.parseStackAndMessage(error); util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n")); util.notEnumerableProp(error, "__stackCleaned__", true); } } }; Promise.prototype._warn = function(message) { var warning = new Warning(message); var ctx = this._peekContext(); if (ctx) { ctx.attachExtraTrace(warning); } else { var parsed = CapturedTrace.parseStackAndMessage(warning); warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); } CapturedTrace.formatAndLogError(warning, ""); }; Promise.onPossiblyUnhandledRejection = function (fn) { var domain = getDomain(); possiblyUnhandledRejection = typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) : undefined; }; Promise.onUnhandledRejectionHandled = function (fn) { var domain = getDomain(); unhandledRejectionHandled = typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) : undefined; }; Promise.longStackTraces = function () { if (async.haveItemsQueued() && debugging === false ) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); } debugging = CapturedTrace.isSupported(); if (debugging) { async.disableTrampolineIfNecessary(); } }; Promise.hasLongStackTraces = function () { return debugging && CapturedTrace.isSupported(); }; if (!CapturedTrace.isSupported()) { Promise.longStackTraces = function(){}; debugging = false; } return function() { return debugging; }; }; },{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util.js"); var isPrimitive = util.isPrimitive; module.exports = function(Promise) { var returner = function () { return this; }; var thrower = function () { throw this; }; var returnUndefined = function() {}; var throwUndefined = function() { throw undefined; }; var wrapper = function (value, action) { if (action === 1) { return function () { throw value; }; } else if (action === 2) { return function () { return value; }; } }; Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) { if (value === undefined) return this.then(returnUndefined); if (isPrimitive(value)) { return this._then( wrapper(value, 2), undefined, undefined, undefined, undefined ); } else if (value instanceof Promise) { value._ignoreRejections(); } return this._then(returner, undefined, undefined, value, undefined); }; Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { if (reason === undefined) return this.then(throwUndefined); if (isPrimitive(reason)) { return this._then( wrapper(reason, 1), undefined, undefined, undefined, undefined ); } return this._then(thrower, undefined, undefined, reason, undefined); }; }; },{"./util.js":38}],12:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseReduce = Promise.reduce; Promise.prototype.each = function (fn) { return PromiseReduce(this, fn, null, INTERNAL); }; Promise.each = function (promises, fn) { return PromiseReduce(promises, fn, null, INTERNAL); }; }; },{}],13:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5.js"); var Objectfreeze = es5.freeze; var util = _dereq_("./util.js"); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; function subError(nameProperty, defaultMessage) { function SubError(message) { if (!(this instanceof SubError)) return new SubError(message); notEnumerableProp(this, "message", typeof message === "string" ? message : defaultMessage); notEnumerableProp(this, "name", nameProperty); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { Error.call(this); } } inherits(SubError, Error); return SubError; } var _TypeError, _RangeError; var Warning = subError("Warning", "warning"); var CancellationError = subError("CancellationError", "cancellation error"); var TimeoutError = subError("TimeoutError", "timeout error"); var AggregateError = subError("AggregateError", "aggregate error"); try { _TypeError = TypeError; _RangeError = RangeError; } catch(e) { _TypeError = subError("TypeError", "type error"); _RangeError = subError("RangeError", "range error"); } var methods = ("join pop push shift unshift slice filter forEach some " + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); for (var i = 0; i < methods.length; ++i) { if (typeof Array.prototype[methods[i]] === "function") { AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; } } es5.defineProperty(AggregateError.prototype, "length", { value: 0, configurable: false, writable: true, enumerable: true }); AggregateError.prototype["isOperational"] = true; var level = 0; AggregateError.prototype.toString = function() { var indent = Array(level * 4 + 1).join(" "); var ret = "\n" + indent + "AggregateError of:" + "\n"; level++; indent = Array(level * 4 + 1).join(" "); for (var i = 0; i < this.length; ++i) { var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; var lines = str.split("\n"); for (var j = 0; j < lines.length; ++j) { lines[j] = indent + lines[j]; } str = lines.join("\n"); ret += str + "\n"; } level--; return ret; }; function OperationalError(message) { if (!(this instanceof OperationalError)) return new OperationalError(message); notEnumerableProp(this, "name", "OperationalError"); notEnumerableProp(this, "message", message); this.cause = message; this["isOperational"] = true; if (message instanceof Error) { notEnumerableProp(this, "message", message.message); notEnumerableProp(this, "stack", message.stack); } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } inherits(OperationalError, Error); var errorTypes = Error["__BluebirdErrorTypes__"]; if (!errorTypes) { errorTypes = Objectfreeze({ CancellationError: CancellationError, TimeoutError: TimeoutError, OperationalError: OperationalError, RejectionError: OperationalError, AggregateError: AggregateError }); notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); } module.exports = { Error: Error, TypeError: _TypeError, RangeError: _RangeError, CancellationError: errorTypes.CancellationError, OperationalError: errorTypes.OperationalError, TimeoutError: errorTypes.TimeoutError, AggregateError: errorTypes.AggregateError, Warning: Warning }; },{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){ var isES5 = (function(){ "use strict"; return this === undefined; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, getDescriptor: Object.getOwnPropertyDescriptor, keys: Object.keys, names: Object.getOwnPropertyNames, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: isES5, propertyIsWritable: function(obj, prop) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop); return !!(!descriptor || descriptor.writable || descriptor.set); } }; } else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; var ObjectKeys = function (o) { var ret = []; for (var key in o) { if (has.call(o, key)) { ret.push(key); } } return ret; }; var ObjectGetDescriptor = function(o, key) { return {value: o[key]}; }; var ObjectDefineProperty = function (o, key, desc) { o[key] = desc.value; return o; }; var ObjectFreeze = function (obj) { return obj; }; var ObjectGetPrototypeOf = function (obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } }; var ArrayIsArray = function (obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } }; module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, names: ObjectKeys, defineProperty: ObjectDefineProperty, getDescriptor: ObjectGetDescriptor, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, isES5: isES5, propertyIsWritable: function() { return true; } }; } },{}],15:[function(_dereq_,module,exports){ "use strict"; module.exports = 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); }; }; },{}],16:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { var util = _dereq_("./util.js"); var isPrimitive = util.isPrimitive; var thrower = util.thrower; function returnThis() { return this; } function throwThis() { throw this; } function return$(r) { return function() { return r; }; } function throw$(r) { return function() { throw r; }; } function promisedFinally(ret, reasonOrValue, isFulfilled) { var then; if (isPrimitive(reasonOrValue)) { then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); } else { then = isFulfilled ? returnThis : throwThis; } return ret._then(then, thrower, undefined, reasonOrValue, undefined); } function finallyHandler(reasonOrValue) { var promise = this.promise; var handler = this.handler; var ret = promise._isBound() ? handler.call(promise._boundValue()) : handler(); if (ret !== undefined) { var maybePromise = tryConvertToPromise(ret, promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); return promisedFinally(maybePromise, reasonOrValue, promise.isFulfilled()); } } if (promise.isRejected()) { NEXT_FILTER.e = reasonOrValue; return NEXT_FILTER; } else { return reasonOrValue; } } function tapHandler(value) { var promise = this.promise; var handler = this.handler; var ret = promise._isBound() ? handler.call(promise._boundValue(), value) : handler(value); if (ret !== undefined) { var maybePromise = tryConvertToPromise(ret, promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); return promisedFinally(maybePromise, value, true); } } return value; } Promise.prototype._passThroughHandler = function (handler, isFinally) { if (typeof handler !== "function") return this.then(); var promiseAndHandler = { promise: this, handler: handler }; return this._then( isFinally ? finallyHandler : tapHandler, isFinally ? finallyHandler : undefined, undefined, promiseAndHandler, undefined); }; Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) { return this._passThroughHandler(handler, true); }; Promise.prototype.tap = function (handler) { return this._passThroughHandler(handler, false); }; }; },{"./util.js":38}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, apiRejection, INTERNAL, tryConvertToPromise) { var errors = _dereq_("./errors.js"); var TypeError = errors.TypeError; var util = _dereq_("./util.js"); var errorObj = util.errorObj; var tryCatch = util.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) { 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; } PromiseSpawn.prototype.promise = function () { return this._promise; }; PromiseSpawn.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver); this._receiver = this._generatorFunction = undefined; this._next(undefined); }; PromiseSpawn.prototype._continue = function (result) { if (result === errorObj) { return this._promise._rejectCallback(result.e, false, true); } var value = result.value; if (result.done === true) { this._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._throw( new TypeError( "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) ); return; } } maybePromise._then( this._next, this._throw, undefined, this, null ); } }; PromiseSpawn.prototype._throw = function (reason) { 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._next = function (value) { this._promise._pushContext(); var result = tryCatch(this._generator.next).call(this._generator, value); this._promise._popContext(); this._continue(result); }; Promise.coroutine = function (generatorFunction, options) { if (typeof generatorFunction !== "function") { throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\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); spawn._generator = generator; spawn._next(undefined); return spawn.promise(); }; }; Promise.coroutine.addYieldHandler = function(fn) { if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); yieldHandlers.push(fn); }; Promise.spawn = function (generatorFunction) { if (typeof generatorFunction !== "function") { return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); } var spawn = new PromiseSpawn(generatorFunction, this); var ret = spawn.promise(); spawn._run(Promise.spawn); return ret; }; }; },{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { var util = _dereq_("./util.js"); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; var errorObj = util.errorObj; var reject; if (!true) { if (canEvaluate) { var thenCallback = function(i) { return new Function("value", "holder", " \n\ 'use strict'; \n\ holder.pIndex = value; \n\ holder.checkFulfillment(this); \n\ ".replace(/Index/g, i)); }; var caller = function(count) { var values = []; for (var i = 1; i <= count; ++i) values.push("holder.p" + i); return new Function("holder", " \n\ 'use strict'; \n\ var callback = holder.fn; \n\ return callback(values); \n\ ".replace(/values/g, values.join(", "))); }; var thenCallbacks = []; var callers = [undefined]; for (var i = 1; i <= 5; ++i) { thenCallbacks.push(thenCallback(i)); callers.push(caller(i)); } var Holder = function(total, fn) { this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; this.fn = fn; this.total = total; this.now = 0; }; Holder.prototype.callers = callers; Holder.prototype.checkFulfillment = function(promise) { var now = this.now; now++; var total = this.total; if (now >= total) { var handler = this.callers[total]; promise._pushContext(); var ret = tryCatch(handler)(this); promise._popContext(); if (ret === errorObj) { promise._rejectCallback(ret.e, false, true); } else { promise._resolveCallback(ret); } } else { this.now = now; } }; var reject = function (reason) { this._reject(reason); }; } } Promise.join = function () { var last = arguments.length - 1; var fn; if (last > 0 && typeof arguments[last] === "function") { fn = arguments[last]; if (!true) { if (last < 6 && canEvaluate) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var holder = new Holder(last, fn); var callbacks = thenCallbacks; for (var i = 0; i < last; ++i) { var maybePromise = tryConvertToPromise(arguments[i], ret); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); if (maybePromise._isPending()) { maybePromise._then(callbacks[i], reject, undefined, ret, holder); } else if (maybePromise._isFulfilled()) { callbacks[i].call(ret, maybePromise._value(), holder); } else { ret._reject(maybePromise._reason()); } } else { callbacks[i].call(ret, maybePromise, holder); } } return ret; } } } var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} if (fn) args.pop(); var ret = new PromiseArray(args).promise(); return fn !== undefined ? ret.spread(fn) : ret; }; }; },{"./util.js":38}],19:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL) { var getDomain = Promise._getDomain; var async = _dereq_("./async.js"); var util = _dereq_("./util.js"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var PENDING = {}; var EMPTY_ARRAY = []; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); var domain = getDomain(); this._callback = domain === null ? fn : domain.bind(fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; this._limit = limit; this._inFlight = 0; this._queue = limit >= 1 ? [] : EMPTY_ARRAY; async.invoke(init, this, undefined); } util.inherits(MappingPromiseArray, PromiseArray); function init() {this._init$(undefined, -2);} MappingPromiseArray.prototype._init = function () {}; MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { var values = this._values; var length = this.length(); var preservedValues = this._preservedValues; var limit = this._limit; if (values[index] === PENDING) { values[index] = value; if (limit >= 1) { this._inFlight--; this._drainQueue(); if (this._isResolved()) return; } } else { if (limit >= 1 && this._inFlight >= limit) { values[index] = value; this._queue.push(index); return; } if (preservedValues !== null) preservedValues[index] = value; var callback = this._callback; var receiver = this._promise._boundValue(); this._promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); this._promise._popContext(); if (ret === errorObj) return this._reject(ret.e); var maybePromise = tryConvertToPromise(ret, this._promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); if (maybePromise._isPending()) { if (limit >= 1) this._inFlight++; values[index] = PENDING; return maybePromise._proxyPromiseArray(this, index); } else if (maybePromise._isFulfilled()) { ret = maybePromise._value(); } else { return this._reject(maybePromise._reason()); } } values[index] = ret; } var totalResolved = ++this._totalResolved; if (totalResolved >= length) { if (preservedValues !== null) { this._filter(values, preservedValues); } else { this._resolve(values); } } }; MappingPromiseArray.prototype._drainQueue = function () { var queue = this._queue; var limit = this._limit; var values = this._values; while (queue.length > 0 && this._inFlight < limit) { if (this._isResolved()) return; var index = queue.pop(); this._promiseFulfilled(values[index], index); } }; MappingPromiseArray.prototype._filter = function (booleans, values) { var len = values.length; var ret = new Array(len); var j = 0; for (var i = 0; i < len; ++i) { if (booleans[i]) ret[j++] = values[i]; } ret.length = j; this._resolve(ret); }; MappingPromiseArray.prototype.preservedValues = function () { return this._preservedValues; }; function map(promises, fn, options, _filter) { var limit = typeof options === "object" && options !== null ? options.concurrency : 0; limit = typeof limit === "number" && isFinite(limit) && limit >= 1 ? limit : 0; return new MappingPromiseArray(promises, fn, limit, _filter); } Promise.prototype.map = function (fn, options) { if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); return map(this, fn, options, null).promise(); }; Promise.map = function (promises, fn, options, _filter) { if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); return map(promises, fn, options, _filter).promise(); }; }; },{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { var util = _dereq_("./util.js"); var tryCatch = util.tryCatch; Promise.method = function (fn) { if (typeof fn !== "function") { throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); } return function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); ret._popContext(); ret._resolveFromSyncValue(value); return ret; }; }; Promise.attempt = Promise["try"] = function (fn, args, ctx) { if (typeof fn !== "function") { return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); } var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = util.isArray(args) ? tryCatch(fn).apply(ctx, args) : tryCatch(fn).call(ctx, args); ret._popContext(); ret._resolveFromSyncValue(value); return ret; }; Promise.prototype._resolveFromSyncValue = function (value) { if (value === util.errorObj) { this._rejectCallback(value.e, false, true); } else { this._resolveCallback(value, true); } }; }; },{"./util.js":38}],21:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var util = _dereq_("./util.js"); var async = _dereq_("./async.js"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; function spreadAdapter(val, nodeback) { var promise = this; if (!util.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 target = promise._target(); var newReason = target._getCarriedStackTrace(); 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; }; }; },{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray) { var util = _dereq_("./util.js"); var async = _dereq_("./async.js"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; Promise.prototype.progressed = function (handler) { return this._then(undefined, undefined, handler, undefined, undefined); }; Promise.prototype._progress = function (progressValue) { if (this._isFollowingOrFulfilledOrRejected()) return; this._target()._progressUnchecked(progressValue); }; Promise.prototype._progressHandlerAt = function (index) { return index === 0 ? this._progressHandler0 : this[(index << 2) + index - 5 + 2]; }; Promise.prototype._doProgressWith = function (progression) { var progressValue = progression.value; var handler = progression.handler; var promise = progression.promise; var receiver = progression.receiver; var ret = tryCatch(handler).call(receiver, progressValue); if (ret === errorObj) { if (ret.e != null && ret.e.name !== "StopProgressPropagation") { var trace = util.canAttachTrace(ret.e) ? ret.e : new Error(util.toString(ret.e)); promise._attachExtraTrace(trace); promise._progress(ret.e); } } else if (ret instanceof Promise) { ret._then(promise._progress, null, null, promise, undefined); } else { promise._progress(ret); } }; Promise.prototype._progressUnchecked = function (progressValue) { var len = this._length(); var progress = this._progress; for (var i = 0; i < len; i++) { var handler = this._progressHandlerAt(i); var promise = this._promiseAt(i); if (!(promise instanceof Promise)) { var receiver = this._receiverAt(i); if (typeof handler === "function") { handler.call(receiver, progressValue, promise); } else if (receiver instanceof PromiseArray && !receiver._isResolved()) { receiver._promiseProgressed(progressValue, promise); } continue; } if (typeof handler === "function") { async.invoke(this._doProgressWith, this, { handler: handler, promise: promise, receiver: this._receiverAt(i), value: progressValue }); } else { async.invoke(progress, promise, progressValue); } } }; }; },{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){ "use strict"; module.exports = function() { var makeSelfResolutionError = function () { return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); }; var reflect = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; var util = _dereq_("./util.js"); var getDomain; if (util.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util.notEnumerableProp(Promise, "_getDomain", getDomain); var UNDEFINED_BINDING = {}; var async = _dereq_("./async.js"); var errors = _dereq_("./errors.js"); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; 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 = {e: null}; var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL); var PromiseArray = _dereq_("./promise_array.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); var CapturedTrace = _dereq_("./captured_trace.js")(); var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace); /*jshint unused:false*/ var createContext = _dereq_("./context.js")(Promise, CapturedTrace, isDebugging); var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER); var PromiseResolver = _dereq_("./promise_resolver.js"); var nodebackForPromise = PromiseResolver._nodebackForPromise; var errorObj = util.errorObj; var tryCatch = util.tryCatch; function Promise(resolver) { if (typeof resolver !== "function") { throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); } if (this.constructor !== Promise) { throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); } this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._progressHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; this._settledValue = undefined; if (resolver !== INTERNAL) this._resolveFromResolver(resolver); } 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 (typeof item === "function") { catchInstances[j++] = item; } else { return Promise.reject( new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); } } catchInstances.length = j; fn = arguments[i]; var catchFilter = new CatchFilter(catchInstances, fn, this); return this._then(undefined, catchFilter.doFilter, undefined, catchFilter, undefined); } return this._then(undefined, fn, undefined, undefined, undefined); }; Promise.prototype.reflect = function () { return this._then(reflect, reflect, undefined, this, undefined); }; Promise.prototype.then = function (didFulfill, didReject, didProgress) { if (isDebugging() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, didProgress, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject, didProgress) { var promise = this._then(didFulfill, didReject, didProgress, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (didFulfill, didReject) { return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); }; Promise.prototype.isCancellable = function () { return !this.isResolved() && this._cancellable(); }; 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 () { return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util.originatesFromRejection, fn); }; Promise.getNewLibraryCopy = module.exports; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = function(fn) { var ret = new Promise(INTERNAL); var result = tryCatch(fn)(nodebackForPromise(ret)); if (result === errorObj) { ret._rejectCallback(result.e, true, true); } return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.defer = Promise.pending = function () { var promise = new Promise(INTERNAL); return new PromiseResolver(promise); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { var val = ret; ret = new Promise(INTERNAL); ret._fulfillUnchecked(val); } 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("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); var prev = async._schedule; async._schedule = fn; return prev; }; Promise.prototype._then = function ( didFulfill, didReject, didProgress, receiver, internalData ) { var haveInternalData = internalData !== undefined; var ret = haveInternalData ? internalData : new Promise(INTERNAL); if (!haveInternalData) { ret._propagateFrom(this, 4 | 1); ret._captureStackTrace(); } var target = this._target(); if (target !== this) { if (receiver === undefined) receiver = this._boundTo; if (!haveInternalData) ret._setIsMigrated(); } var callbackIndex = target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver, getDomain()); if (target._isResolved() && !target._isSettlePromisesQueued()) { async.invoke( target._settlePromiseAtPostResolution, target, callbackIndex); } return ret; }; Promise.prototype._settlePromiseAtPostResolution = function (index) { if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); this._settlePromiseAt(index); }; Promise.prototype._length = function () { return this._bitField & 131071; }; Promise.prototype._isFollowingOrFulfilledOrRejected = function () { return (this._bitField & 939524096) > 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 536870912) === 536870912; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -131072) | (len & 131071); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 268435456; }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 134217728; }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 536870912; }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 33554432; }; Promise.prototype._isFinal = function () { return (this._bitField & 33554432) > 0; }; Promise.prototype._cancellable = function () { return (this._bitField & 67108864) > 0; }; Promise.prototype._setCancellable = function () { this._bitField = this._bitField | 67108864; }; Promise.prototype._unsetCancellable = function () { this._bitField = this._bitField & (~67108864); }; Promise.prototype._setIsMigrated = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._unsetIsMigrated = function () { this._bitField = this._bitField & (~4194304); }; Promise.prototype._isMigrated = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 5 - 5 + 4]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return index === 0 ? this._promise0 : this[index * 5 - 5 + 3]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return index === 0 ? this._fulfillmentHandler0 : this[index * 5 - 5 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return index === 0 ? this._rejectionHandler0 : this[index * 5 - 5 + 1]; }; Promise.prototype._boundValue = function() { var ret = this._boundTo; if (ret !== undefined) { if (ret instanceof Promise) { if (ret.isFulfilled()) { return ret.value(); } else { return undefined; } } } return ret; }; Promise.prototype._migrateCallbacks = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var progress = follower._progressHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (promise instanceof Promise) promise._setIsMigrated(); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, progress, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, progress, promise, receiver, domain ) { var index = this._length(); if (index >= 131071 - 5) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; if (receiver !== undefined) this._receiver0 = receiver; if (typeof fulfill === "function" && !this._isCarryingStackTrace()) { this._fulfillmentHandler0 = domain === null ? fulfill : domain.bind(fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : domain.bind(reject); } if (typeof progress === "function") { this._progressHandler0 = domain === null ? progress : domain.bind(progress); } } else { var base = index * 5 - 5; this[base + 3] = promise; this[base + 4] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : domain.bind(fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : domain.bind(reject); } if (typeof progress === "function") { this[base + 2] = domain === null ? progress : domain.bind(progress); } } this._setLength(index + 1); return index; }; Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { var index = this._length(); if (index >= 131071 - 5) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promiseSlotValue; this._receiver0 = receiver; } else { var base = index * 5 - 5; this[base + 3] = promiseSlotValue; this[base + 4] = receiver; } this._setLength(index + 1); }; Promise.prototype._proxyPromiseArray = function (promiseArray, index) { this._setProxyHandlers(promiseArray, index); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (this._isFollowingOrFulfilledOrRejected()) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false, true); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); var propagationFlags = 1 | (shouldBind ? 4 : 0); this._propagateFrom(maybePromise, propagationFlags); var promise = maybePromise._target(); if (promise._isPending()) { var len = this._length(); for (var i = 0; i < len; ++i) { promise._migrateCallbacks(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (promise._isFulfilled()) { this._fulfillUnchecked(promise._value()); } else { this._rejectUnchecked(promise._reason(), promise._getCarriedStackTrace()); } }; Promise.prototype._rejectCallback = function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { if (!shouldNotMarkOriginatingFromRejection) { util.markAsOriginatingFromRejection(reason); } var trace = util.ensureErrorObject(reason); var hasStack = trace === reason; this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason, hasStack ? undefined : trace); }; Promise.prototype._resolveFromResolver = function (resolver) { var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = tryCatch(resolver)(function(value) { if (promise === null) return; promise._resolveCallback(value); promise = null; }, function (reason) { if (promise === null) return; promise._rejectCallback(reason, synchronous); promise = null; }); synchronous = false; this._popContext(); if (r !== undefined && r === errorObj && promise !== null) { promise._rejectCallback(r.e, true, true); promise = null; } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { if (promise._isRejected()) return; promise._pushContext(); var x; if (receiver === APPLY && !this._isRejected()) { x = tryCatch(handler).apply(this._boundValue(), value); } else { x = tryCatch(handler).call(receiver, value); } promise._popContext(); if (x === errorObj || x === promise || x === NEXT_FILTER) { var err = x === promise ? makeSelfResolutionError() : x.e; promise._rejectCallback(err, false, true); } else { 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._cleanValues = function () { if (this._cancellable()) { this._cancellationParent = undefined; } }; Promise.prototype._propagateFrom = function (parent, flags) { if ((flags & 1) > 0 && parent._cancellable()) { this._setCancellable(); this._cancellationParent = parent; } if ((flags & 4) > 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } }; Promise.prototype._fulfill = function (value) { if (this._isFollowingOrFulfilledOrRejected()) return; this._fulfillUnchecked(value); }; Promise.prototype._reject = function (reason, carriedStackTrace) { if (this._isFollowingOrFulfilledOrRejected()) return; this._rejectUnchecked(reason, carriedStackTrace); }; Promise.prototype._settlePromiseAt = function (index) { var promise = this._promiseAt(index); var isPromise = promise instanceof Promise; if (isPromise && promise._isMigrated()) { promise._unsetIsMigrated(); return async.invoke(this._settlePromiseAt, this, index); } var handler = this._isFulfilled() ? this._fulfillmentHandlerAt(index) : this._rejectionHandlerAt(index); var carriedStackTrace = this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; var value = this._settledValue; var receiver = this._receiverAt(index); this._clearCallbackDataAtIndex(index); if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof PromiseArray) { if (!receiver._isResolved()) { if (this._isFulfilled()) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (this._isFulfilled()) { promise._fulfill(value); } else { promise._reject(value, carriedStackTrace); } } if (index >= 4 && (index & 31) === 4) async.invokeLater(this._setLength, this, 0); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { if (index === 0) { if (!this._isCarryingStackTrace()) { this._fulfillmentHandler0 = undefined; } this._rejectionHandler0 = this._progressHandler0 = this._receiver0 = this._promise0 = undefined; } else { var base = index * 5 - 5; this[base + 3] = this[base + 4] = this[base + 0] = this[base + 1] = this[base + 2] = undefined; } }; Promise.prototype._isSettlePromisesQueued = function () { return (this._bitField & -1073741824) === -1073741824; }; Promise.prototype._setSettlePromisesQueued = function () { this._bitField = this._bitField | -1073741824; }; Promise.prototype._unsetSettlePromisesQueued = function () { this._bitField = this._bitField & (~-1073741824); }; Promise.prototype._queueSettlePromises = function() { async.settlePromises(this); this._setSettlePromisesQueued(); }; Promise.prototype._fulfillUnchecked = function (value) { if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._rejectUnchecked(err, undefined); } this._setFulfilled(); this._settledValue = value; this._cleanValues(); if (this._length() > 0) { this._queueSettlePromises(); } }; Promise.prototype._rejectUncheckedCheckError = function (reason) { var trace = util.ensureErrorObject(reason); this._rejectUnchecked(reason, trace === reason ? undefined : trace); }; Promise.prototype._rejectUnchecked = function (reason, trace) { if (reason === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._rejectUnchecked(err); } this._setRejected(); this._settledValue = reason; this._cleanValues(); if (this._isFinal()) { async.throwLater(function(e) { if ("stack" in e) { async.invokeFirst( CapturedTrace.unhandledRejection, undefined, e); } throw e; }, trace === undefined ? reason : trace); return; } if (trace !== undefined && trace !== reason) { this._setCarriedStackTrace(trace); } if (this._length() > 0) { this._queueSettlePromises(); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._settlePromises = function () { this._unsetSettlePromisesQueued(); var len = this._length(); for (var i = 0; i < len; i++) { this._settlePromiseAt(i); } }; util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); _dereq_("./progress.js")(Promise, PromiseArray); _dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); _dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise); _dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); _dereq_("./direct_resolve.js")(Promise); _dereq_("./synchronous_inspection.js")(Promise); _dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); Promise.version = "2.11.0"; Promise.Promise = Promise; _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); _dereq_('./cancel.js')(Promise); _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); _dereq_('./nodeify.js')(Promise); _dereq_('./call_get.js')(Promise); _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); _dereq_('./settle.js')(Promise, PromiseArray); _dereq_('./some.js')(Promise, PromiseArray, apiRejection); _dereq_('./promisify.js')(Promise, INTERNAL); _dereq_('./any.js')(Promise); _dereq_('./each.js')(Promise, INTERNAL); _dereq_('./timers.js')(Promise, INTERNAL); _dereq_('./filter.js')(Promise, INTERNAL); util.toFastProperties(Promise); util.toFastProperties(Promise.prototype); function fillTypes(value) { var p = new Promise(INTERNAL); p._fulfillmentHandler0 = value; p._rejectionHandler0 = value; p._progressHandler0 = value; p._promise0 = value; p._receiver0 = value; p._settledValue = 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)); CapturedTrace.setBounds(async.firstLineError, util.lastLineError); return Promise; }; },{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { var util = _dereq_("./util.js"); var isArray = util.isArray; function toResolutionValue(val) { switch(val) { case -2: return []; case -3: return {}; } } function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); var parent; if (values instanceof Promise) { parent = values; promise._propagateFrom(parent, 1 | 4); } this._values = values; this._length = 0; this._totalResolved = 0; this._init(undefined, -2); } PromiseArray.prototype.length = function () { return this._length; }; PromiseArray.prototype.promise = function () { return this._promise; }; PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { var values = tryConvertToPromise(this._values, this._promise); if (values instanceof Promise) { values = values._target(); this._values = values; if (values._isFulfilled()) { values = values._value(); if (!isArray(values)) { var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); this.__hardReject__(err); return; } } else if (values._isPending()) { values._then( init, this._reject, undefined, this, resolveValueIfEmpty ); return; } else { this._reject(values._reason()); return; } } else if (!isArray(values)) { this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); return; } if (values.length === 0) { if (resolveValueIfEmpty === -5) { this._resolveEmptyArray(); } else { this._resolve(toResolutionValue(resolveValueIfEmpty)); } return; } var len = this.getActualLength(values.length); this._length = len; this._values = this.shouldCopyValues() ? new Array(len) : this._values; var promise = this._promise; for (var i = 0; i < len; ++i) { var isResolved = this._isResolved(); var maybePromise = tryConvertToPromise(values[i], promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); if (isResolved) { maybePromise._ignoreRejections(); } else if (maybePromise._isPending()) { maybePromise._proxyPromiseArray(this, i); } else if (maybePromise._isFulfilled()) { this._promiseFulfilled(maybePromise._value(), i); } else { this._promiseRejected(maybePromise._reason(), i); } } else if (!isResolved) { this._promiseFulfilled(maybePromise, i); } } }; PromiseArray.prototype._isResolved = function () { return this._values === null; }; PromiseArray.prototype._resolve = function (value) { this._values = null; this._promise._fulfill(value); }; PromiseArray.prototype.__hardReject__ = PromiseArray.prototype._reject = function (reason) { this._values = null; this._promise._rejectCallback(reason, false, true); }; PromiseArray.prototype._promiseProgressed = function (progressValue, index) { this._promise._progress({ index: index, value: progressValue }); }; PromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); } }; PromiseArray.prototype._promiseRejected = function (reason, index) { this._totalResolved++; this._reject(reason); }; PromiseArray.prototype.shouldCopyValues = function () { return true; }; PromiseArray.prototype.getActualLength = function (len) { return len; }; return PromiseArray; }; },{"./util.js":38}],25:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util.js"); var maybeWrapAsError = util.maybeWrapAsError; var errors = _dereq_("./errors.js"); var TimeoutError = errors.TimeoutError; var OperationalError = errors.OperationalError; var haveGetters = util.haveGetters; var es5 = _dereq_("./es5.js"); function isUntypedError(obj) { return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype; } var rErrorKey = /^(?:name|message|stack|cause)$/; function wrapAsOperationalError(obj) { var ret; if (isUntypedError(obj)) { ret = new OperationalError(obj); ret.name = obj.name; ret.message = obj.message; ret.stack = obj.stack; var keys = es5.keys(obj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!rErrorKey.test(key)) { ret[key] = obj[key]; } } return ret; } util.markAsOriginatingFromRejection(obj); return obj; } function nodebackForPromise(promise) { return function(err, value) { if (promise === null) return; if (err) { var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); promise._attachExtraTrace(wrapped); promise._reject(wrapped); } else if (arguments.length > 2) { var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} promise._fulfill(args); } else { promise._fulfill(value); } promise = null; }; } var PromiseResolver; if (!haveGetters) { PromiseResolver = function (promise) { this.promise = promise; this.asCallback = nodebackForPromise(promise); this.callback = this.asCallback; }; } else { PromiseResolver = function (promise) { this.promise = promise; }; } if (haveGetters) { var prop = { get: function() { return nodebackForPromise(this.promise); } }; es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); es5.defineProperty(PromiseResolver.prototype, "callback", prop); } PromiseResolver._nodebackForPromise = nodebackForPromise; PromiseResolver.prototype.toString = function () { return "[object PromiseResolver]"; }; PromiseResolver.prototype.resolve = PromiseResolver.prototype.fulfill = function (value) { if (!(this instanceof PromiseResolver)) { throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); } this.promise._resolveCallback(value); }; PromiseResolver.prototype.reject = function (reason) { if (!(this instanceof PromiseResolver)) { throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); } this.promise._rejectCallback(reason); }; PromiseResolver.prototype.progress = function (value) { if (!(this instanceof PromiseResolver)) { throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); } this.promise._progress(value); }; PromiseResolver.prototype.cancel = function (err) { this.promise.cancel(err); }; PromiseResolver.prototype.timeout = function () { this.reject(new TimeoutError("timeout")); }; PromiseResolver.prototype.isResolved = function () { return this.promise.isResolved(); }; PromiseResolver.prototype.toJSON = function () { return this.promise.toJSON(); }; module.exports = PromiseResolver; },{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var THIS = {}; var util = _dereq_("./util.js"); var nodebackForPromise = _dereq_("./promise_resolver.js") ._nodebackForPromise; var withAppended = util.withAppended; var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; var TypeError = _dereq_("./errors").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.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.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/iWrZbw\u000a" .replace("%s", suffix)); } } } } } function promisifiableMethods(obj, suffix, suffixRegexp, filter) { var keys = util.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; if (!true) { 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.filledRange(argumentCount, "_arg", ""); }; var parameterDeclaration = function(parameterCount) { return util.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) { 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"; return new Function("Promise", "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", "tryCatch", "errorObj", "notEnumerableProp", "INTERNAL","'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); \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\ return promise; \n\ }; \n\ notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ " .replace("Parameters", parameterDeclaration(newParameterCount)) .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) .replace("[GetFunctionCode]", getFunctionCode))( Promise, fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, util.tryCatch, util.errorObj, util.notEnumerableProp, INTERNAL ); }; } function makeNodePromisifiedClosure(callback, receiver, _, fn) { 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); try { cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { promise._rejectCallback(maybeWrapAsError(e), true, true); } return promise; } util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; function promisifyAll(obj, suffix, filter, promisifier) { 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); } else { var promisified = promisifier(fn, function() { return makeNodePromisified(key, THIS, key, fn, suffix); }); util.notEnumerableProp(promisified, "__isPromisified__", true); obj[promisifiedKey] = promisified; } } util.toFastProperties(obj); return obj; } function promisify(callback, receiver) { return makeNodePromisified(callback, receiver, undefined, callback); } Promise.promisify = function (fn, receiver) { if (typeof fn !== "function") { throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); } if (isPromisified(fn)) { return fn; } var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); util.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/9ITlV0\u000a"); } options = Object(options); 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.isIdentifier(suffix)) { throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); } var keys = util.inheritedDataKeys(target); for (var i = 0; i < keys.length; ++i) { var value = target[keys[i]]; if (keys[i] !== "constructor" && util.isClass(value)) { promisifyAll(value.prototype, suffix, filter, promisifier); promisifyAll(value, suffix, filter, promisifier); } } return promisifyAll(target, suffix, filter, promisifier); }; }; },{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { var util = _dereq_("./util.js"); var isObject = util.isObject; var es5 = _dereq_("./es5.js"); function PropertiesPromiseArray(obj) { var keys = es5.keys(obj); var len = keys.length; var values = new Array(len * 2); for (var i = 0; i < len; ++i) { var key = keys[i]; values[i] = obj[key]; values[i + len] = key; } this.constructor$(values); } util.inherits(PropertiesPromiseArray, PromiseArray); PropertiesPromiseArray.prototype._init = function () { this._init$(undefined, -3) ; }; PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { var 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); } }; PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { this._promise._progress({ key: this._values[index + this.length()], value: value }); }; 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/OsFKC8\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, 4); } return ret; } Promise.prototype.props = function () { return props(this); }; Promise.props = function (promises) { return props(promises); }; }; },{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){ "use strict"; function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } function Queue(capacity) { this._capacity = capacity; this._length = 0; this._front = 0; } Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); this[i] = arg; this._length = length + 1; }; Queue.prototype._unshiftOne = function(value) { var capacity = this._capacity; this._checkCapacity(this.length() + 1); var front = this._front; var i = (((( front - 1 ) & ( capacity - 1) ) ^ capacity ) - capacity ); this[i] = value; this._front = i; this._length = this.length() + 1; }; Queue.prototype.unshift = function(fn, receiver, arg) { this._unshiftOne(arg); this._unshiftOne(receiver); this._unshiftOne(fn); }; Queue.prototype.push = function (fn, receiver, arg) { var length = this.length() + 3; if (this._willBeOverCapacity(length)) { this._pushOne(fn); this._pushOne(receiver); this._pushOne(arg); return; } var j = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; this[(j + 0) & wrapMask] = fn; this[(j + 1) & wrapMask] = receiver; this[(j + 2) & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function () { var front = this._front, ret = this[front]; this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._resizeTo(this._capacity << 1); } }; Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var front = this._front; var length = this._length; var moveItemsCount = (front + length) & (oldCapacity - 1); arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue; },{}],29:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { var isArray = _dereq_("./util.js").isArray; 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 if (!isArray(promises)) { return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); } var ret = new Promise(INTERNAL); if (parent !== undefined) { ret._propagateFrom(parent, 4 | 1); } 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); }; }; },{"./util.js":38}],30:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL) { var getDomain = Promise._getDomain; var async = _dereq_("./async.js"); var util = _dereq_("./util.js"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; function ReductionPromiseArray(promises, fn, accum, _each) { this.constructor$(promises); this._promise._captureStackTrace(); this._preservedValues = _each === INTERNAL ? [] : null; this._zerothIsAccum = (accum === undefined); this._gotAccum = false; this._reducingIndex = (this._zerothIsAccum ? 1 : 0); this._valuesPhase = undefined; var maybePromise = tryConvertToPromise(accum, this._promise); var rejected = false; var isPromise = maybePromise instanceof Promise; if (isPromise) { maybePromise = maybePromise._target(); if (maybePromise._isPending()) { maybePromise._proxyPromiseArray(this, -1); } else if (maybePromise._isFulfilled()) { accum = maybePromise._value(); this._gotAccum = true; } else { this._reject(maybePromise._reason()); rejected = true; } } if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; var domain = getDomain(); this._callback = domain === null ? fn : domain.bind(fn); this._accum = accum; if (!rejected) async.invoke(init, this, undefined); } function init() { this._init$(undefined, -5); } util.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._init = function () {}; ReductionPromiseArray.prototype._resolveEmptyArray = function () { if (this._gotAccum || this._zerothIsAccum) { this._resolve(this._preservedValues !== null ? [] : this._accum); } }; ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { var values = this._values; values[index] = value; var length = this.length(); var preservedValues = this._preservedValues; var isEach = preservedValues !== null; var gotAccum = this._gotAccum; var valuesPhase = this._valuesPhase; var valuesPhaseIndex; if (!valuesPhase) { valuesPhase = this._valuesPhase = new Array(length); for (valuesPhaseIndex=0; valuesPhaseIndex= this._length) { this._resolve(this._values); } }; SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); ret._bitField = 268435456; ret._settledValue = value; this._promiseResolved(index, ret); }; SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); ret._bitField = 134217728; ret._settledValue = reason; this._promiseResolved(index, ret); }; Promise.settle = function (promises) { return new SettledPromiseArray(promises).promise(); }; Promise.prototype.settle = function () { return new SettledPromiseArray(this).promise(); }; }; },{"./util.js":38}],33:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection) { var util = _dereq_("./util.js"); var RangeError = _dereq_("./errors.js").RangeError; var AggregateError = _dereq_("./errors.js").AggregateError; var isArray = util.isArray; function SomePromiseArray(values) { this.constructor$(values); this._howMany = 0; this._unwrap = false; this._initialized = false; } util.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); } } }; SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); if (this.howMany() > this._canPossiblyFulfill()) { var e = new AggregateError(); for (var i = this.length(); i < this._values.length; ++i) { e.push(this._values[i]); } this._reject(e); } }; 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/1wAmHx\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; }; },{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function PromiseInspection(promise) { if (promise !== undefined) { promise = promise._target(); this._bitField = promise._bitField; this._settledValue = promise._settledValue; } else { this._bitField = 0; this._settledValue = undefined; } } PromiseInspection.prototype.value = function () { if (!this.isFulfilled()) { throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); } return this._settledValue; }; PromiseInspection.prototype.error = PromiseInspection.prototype.reason = function () { if (!this.isRejected()) { throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); } return this._settledValue; }; PromiseInspection.prototype.isFulfilled = Promise.prototype._isFulfilled = function () { return (this._bitField & 268435456) > 0; }; PromiseInspection.prototype.isRejected = Promise.prototype._isRejected = function () { return (this._bitField & 134217728) > 0; }; PromiseInspection.prototype.isPending = Promise.prototype._isPending = function () { return (this._bitField & 402653184) === 0; }; PromiseInspection.prototype.isResolved = Promise.prototype._isResolved = function () { return (this._bitField & 402653184) > 0; }; Promise.prototype.isPending = function() { return this._target()._isPending(); }; Promise.prototype.isRejected = function() { return this._target()._isRejected(); }; Promise.prototype.isFulfilled = function() { return this._target()._isFulfilled(); }; Promise.prototype.isResolved = function() { return this._target()._isResolved(); }; Promise.prototype._value = function() { return this._settledValue; }; Promise.prototype._reason = function() { this._unsetRejectionIsUnhandled(); return this._settledValue; }; Promise.prototype.value = function() { var target = this._target(); if (!target.isFulfilled()) { throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); } return target._settledValue; }; Promise.prototype.reason = function() { var target = this._target(); if (!target.isRejected()) { throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); } target._unsetRejectionIsUnhandled(); return target._settledValue; }; Promise.PromiseInspection = PromiseInspection; }; },{}],35:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var util = _dereq_("./util.js"); var errorObj = util.errorObj; var isObject = util.isObject; function tryConvertToPromise(obj, context) { if (isObject(obj)) { if (obj instanceof Promise) { return obj; } else if (isAnyBluebirdPromise(obj)) { var ret = new Promise(INTERNAL); obj._then( ret._fulfillUnchecked, ret._rejectUncheckedCheckError, ret._progressUnchecked, ret, null ); return ret; } var then = util.tryCatch(getThen)(obj); if (then === errorObj) { if (context) context._pushContext(); var ret = Promise.reject(then.e); if (context) context._popContext(); return ret; } else if (typeof then === "function") { return doThenable(obj, then, context); } } return obj; } function getThen(obj) { return obj.then; } var hasProp = {}.hasOwnProperty; function isAnyBluebirdPromise(obj) { return hasProp.call(obj, "_promise0"); } function doThenable(x, then, context) { var promise = new Promise(INTERNAL); var ret = promise; if (context) context._pushContext(); promise._captureStackTrace(); if (context) context._popContext(); var synchronous = true; var result = util.tryCatch(then).call(x, resolveFromThenable, rejectFromThenable, progressFromThenable); synchronous = false; if (promise && result === errorObj) { promise._rejectCallback(result.e, true, true); promise = null; } function resolveFromThenable(value) { if (!promise) return; promise._resolveCallback(value); promise = null; } function rejectFromThenable(reason) { if (!promise) return; promise._rejectCallback(reason, synchronous, true); promise = null; } function progressFromThenable(value) { if (!promise) return; if (typeof promise._progress === "function") { promise._progress(value); } } return ret; } return tryConvertToPromise; }; },{"./util.js":38}],36:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var util = _dereq_("./util.js"); var TimeoutError = Promise.TimeoutError; var afterTimeout = function (promise, message) { if (!promise.isPending()) return; var err; if(!util.isPrimitive(message) && (message instanceof Error)) { err = message; } else { if (typeof message !== "string") { message = "operation timed out"; } err = new TimeoutError(message); } util.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); promise._cancel(err); }; var afterValue = function(value) { return delay(+this).thenReturn(value); }; var delay = Promise.delay = function (value, ms) { if (ms === undefined) { ms = value; value = undefined; var ret = new Promise(INTERNAL); setTimeout(function() { ret._fulfill(); }, ms); return ret; } ms = +ms; return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); }; Promise.prototype.delay = function (ms) { return delay(this, ms); }; function successClear(value) { var handle = this; if (handle instanceof Number) handle = +handle; clearTimeout(handle); return value; } function failureClear(reason) { var handle = this; if (handle instanceof Number) handle = +handle; clearTimeout(handle); throw reason; } Promise.prototype.timeout = function (ms, message) { ms = +ms; var ret = this.then().cancellable(); ret._cancellationParent = this; var handle = setTimeout(function timeoutTimeout() { afterTimeout(ret, message); }, ms); return ret._then(successClear, failureClear, undefined, handle, undefined); }; }; },{"./util.js":38}],37:[function(_dereq_,module,exports){ "use strict"; module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext) { var TypeError = _dereq_("./errors.js").TypeError; var inherits = _dereq_("./util.js").inherits; var PromiseInspection = Promise.PromiseInspection; function inspectionMapper(inspections) { var len = inspections.length; for (var i = 0; i < len; ++i) { var inspection = inspections[i]; if (inspection.isRejected()) { return Promise.reject(inspection.error()); } inspections[i] = inspection._settledValue; } return inspections; } function thrower(e) { setTimeout(function(){throw e;}, 0); } function castPreservingDisposable(thenable) { var maybePromise = tryConvertToPromise(thenable); if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && thenable._isDisposable()) { maybePromise._setDisposable(thenable._getDisposer()); } return maybePromise; } function dispose(resources, inspection) { var i = 0; var len = resources.length; var ret = Promise.defer(); function iterator() { if (i >= len) return ret.resolve(); var maybePromise = castPreservingDisposable(resources[i++]); if (maybePromise instanceof Promise && maybePromise._isDisposable()) { try { maybePromise = tryConvertToPromise( maybePromise._getDisposer().tryDispose(inspection), resources.promise); } catch (e) { return thrower(e); } if (maybePromise instanceof Promise) { return maybePromise._then(iterator, thrower, null, null, null); } } iterator(); } iterator(); return ret.promise; } function disposerSuccess(value) { var inspection = new PromiseInspection(); inspection._settledValue = value; inspection._bitField = 268435456; return dispose(this, inspection).thenReturn(value); } function disposerFail(reason) { var inspection = new PromiseInspection(); inspection._settledValue = reason; inspection._bitField = 134217728; return dispose(this, inspection).thenThrow(reason); } function Disposer(data, promise, context) { this._data = data; this._promise = promise; this._context = context; } Disposer.prototype.data = function () { return this._data; }; Disposer.prototype.promise = function () { return this._promise; }; Disposer.prototype.resource = function () { if (this.promise().isFulfilled()) { return this.promise().value(); } return null; }; Disposer.prototype.tryDispose = function(inspection) { var resource = this.resource(); var context = this._context; if (context !== undefined) context._pushContext(); var ret = resource !== null ? this.doDispose(resource, inspection) : null; if (context !== undefined) context._popContext(); this._promise._unsetDisposable(); this._data = null; return ret; }; Disposer.isDisposer = function (d) { return (d != null && typeof d.resource === "function" && typeof d.tryDispose === "function"); }; function FunctionDisposer(fn, promise, context) { this.constructor$(fn, promise, context); } inherits(FunctionDisposer, Disposer); FunctionDisposer.prototype.doDispose = function (resource, inspection) { var fn = this.data(); return fn.call(resource, resource, inspection); }; function maybeUnwrapDisposer(value) { if (Disposer.isDisposer(value)) { this.resources[this.index]._setDisposable(value); return value.promise(); } return value; } Promise.using = function () { var len = arguments.length; if (len < 2) return apiRejection( "you must pass at least 2 arguments to Promise.using"); var fn = arguments[len - 1]; if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); var input; var spreadArgs = true; if (len === 2 && Array.isArray(arguments[0])) { input = arguments[0]; len = input.length; spreadArgs = false; } else { input = arguments; len--; } var resources = new Array(len); for (var i = 0; i < len; ++i) { var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); resource._setDisposable(disposer); } else { var maybePromise = tryConvertToPromise(resource); if (maybePromise instanceof Promise) { resource = maybePromise._then(maybeUnwrapDisposer, null, null, { resources: resources, index: i }, undefined); } } resources[i] = resource; } var promise = Promise.settle(resources) .then(inspectionMapper) .then(function(vals) { promise._pushContext(); var ret; try { ret = spreadArgs ? fn.apply(undefined, vals) : fn.call(undefined, vals); } finally { promise._popContext(); } return ret; }) ._then( disposerSuccess, disposerFail, undefined, resources, undefined); resources.promise = promise; return promise; }; Promise.prototype._setDisposable = function (disposer) { this._bitField = this._bitField | 262144; this._disposer = disposer; }; Promise.prototype._isDisposable = function () { return (this._bitField & 262144) > 0; }; Promise.prototype._getDisposer = function () { return this._disposer; }; Promise.prototype._unsetDisposable = function () { this._bitField = this._bitField & (~262144); this._disposer = undefined; }; Promise.prototype.disposer = function (fn) { if (typeof fn === "function") { return new FunctionDisposer(fn, this, createContext()); } throw new TypeError(); }; }; },{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5.js"); var canEvaluate = typeof navigator == "undefined"; var haveGetters = (function(){ try { var o = {}; es5.defineProperty(o, "f", { get: function () { return 3; } }); return o.f === 3; } catch (e) { return false; } })(); var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { var target = tryCatchTarget; tryCatchTarget = null; return target.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { tryCatchTarget = fn; return tryCatcher; } var inherits = function(Child, Parent) { var hasProp = {}.hasOwnProperty; function T() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length-1) !== "$" ) { this[propertyName + "$"] = Parent.prototype[propertyName]; } } } T.prototype = Parent.prototype; Child.prototype = new T(); return Child.prototype; }; function isPrimitive(val) { return val == null || val === true || val === false || typeof val === "string" || typeof val === "number"; } function isObject(value) { return !isPrimitive(value); } function maybeWrapAsError(maybeError) { if (!isPrimitive(maybeError)) return maybeError; return new Error(safeToString(maybeError)); } function withAppended(target, appendee) { var len = target.length; var ret = new Array(len + 1); var i; for (i = 0; i < len; ++i) { ret[i] = target[i]; } ret[i] = appendee; return ret; } function getDataPropertyOrDefault(obj, key, defaultValue) { if (es5.isES5) { var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null) { return desc.get == null && desc.set == null ? desc.value : defaultValue; } } else { return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; } } function notEnumerableProp(obj, name, value) { if (isPrimitive(obj)) return obj; var descriptor = { value: value, configurable: true, enumerable: false, writable: true }; es5.defineProperty(obj, name, descriptor); return obj; } function thrower(r) { throw r; } var inheritedDataKeys = (function() { var excludedPrototypes = [ Array.prototype, Object.prototype, Function.prototype ]; var isExcludedProto = function(val) { for (var i = 0; i < excludedPrototypes.length; ++i) { if (excludedPrototypes[i] === val) { return true; } } return false; }; if (es5.isES5) { var getKeys = Object.getOwnPropertyNames; return function(obj) { var ret = []; var visitedKeys = Object.create(null); while (obj != null && !isExcludedProto(obj)) { var keys; try { keys = getKeys(obj); } catch (e) { return ret; } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (visitedKeys[key]) continue; visitedKeys[key] = true; var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null && desc.get == null && desc.set == null) { ret.push(key); } } obj = es5.getPrototypeOf(obj); } return ret; }; } else { var hasProp = {}.hasOwnProperty; return function(obj) { if (isExcludedProto(obj)) return []; var ret = []; /*jshint forin:false */ enumeration: for (var key in obj) { if (hasProp.call(obj, key)) { ret.push(key); } else { for (var i = 0; i < excludedPrototypes.length; ++i) { if (hasProp.call(excludedPrototypes[i], key)) { continue enumeration; } } ret.push(key); } } return ret; }; } })(); var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; function isClass(fn) { try { if (typeof fn === "function") { var keys = es5.names(fn.prototype); var hasMethods = es5.isES5 && keys.length > 1; var hasMethodsOtherThanConstructor = keys.length > 0 && !(keys.length === 1 && keys[0] === "constructor"); var hasThisAssignmentAndStaticMethods = thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; if (hasMethods || hasMethodsOtherThanConstructor || hasThisAssignmentAndStaticMethods) { return true; } } return false; } catch (e) { return false; } } function toFastProperties(obj) { /*jshint -W027,-W055,-W031*/ function f() {} f.prototype = obj; var l = 8; while (l--) new f(); return obj; eval(obj); } var rident = /^[a-z$_][a-z$_0-9]*$/i; function isIdentifier(str) { return rident.test(str); } function filledRange(count, prefix, suffix) { var ret = new Array(count); for(var i = 0; i < count; ++i) { ret[i] = prefix + i + suffix; } return ret; } function safeToString(obj) { try { return obj + ""; } catch (e) { return "[no string representation]"; } } function markAsOriginatingFromRejection(e) { try { notEnumerableProp(e, "isOperational", true); } catch(ignore) {} } function originatesFromRejection(e) { if (e == null) return false; return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || e["isOperational"] === true); } function canAttachTrace(obj) { return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); } var ensureErrorObject = (function() { if (!("stack" in new Error())) { return function(value) { if (canAttachTrace(value)) return value; try {throw new Error(safeToString(value));} catch(err) {return err;} }; } else { return function(value) { if (canAttachTrace(value)) return value; return new Error(safeToString(value)); }; } })(); function classString(obj) { return {}.toString.call(obj); } function copyDescriptors(from, to, filter) { var keys = es5.names(from); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (filter(key)) { try { es5.defineProperty(to, key, es5.getDescriptor(from, key)); } catch (ignore) {} } } } var ret = { isClass: isClass, isIdentifier: isIdentifier, inheritedDataKeys: inheritedDataKeys, getDataPropertyOrDefault: getDataPropertyOrDefault, thrower: thrower, isArray: es5.isArray, haveGetters: haveGetters, notEnumerableProp: notEnumerableProp, isPrimitive: isPrimitive, isObject: isObject, canEvaluate: canEvaluate, errorObj: errorObj, tryCatch: tryCatch, inherits: inherits, withAppended: withAppended, maybeWrapAsError: maybeWrapAsError, toFastProperties: toFastProperties, filledRange: filledRange, toString: safeToString, canAttachTrace: canAttachTrace, ensureErrorObject: ensureErrorObject, originatesFromRejection: originatesFromRejection, markAsOriginatingFromRejection: markAsOriginatingFromRejection, classString: classString, copyDescriptors: copyDescriptors, hasDevTools: typeof chrome !== "undefined" && chrome && typeof chrome.loadTimes === "function", isNode: typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]" }; ret.isRecentNode = ret.isNode && (function() { var version = process.versions.node.split(".").map(Number); return (version[0] === 0 && version[1] > 10) || (version[0] > 0); })(); if (ret.isNode) ret.toFastProperties(process); try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; },{"./es5.js":14}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":26}],3:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property * on objects. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() function typedArraySupport () { function Bar () {} try { var arr = new Uint8Array(1) arr.foo = function () { return 42 } arr.constructor = Bar return arr.foo() === 42 && // typed array instances can be augmented arr.constructor === Bar && // constructor can be set typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (arg) { if (!(this instanceof Buffer)) { // Avoid going through an ArgumentsAdaptorTrampoline in the common case. if (arguments.length > 1) return new Buffer(arg, arguments[1]) return new Buffer(arg) } if (!Buffer.TYPED_ARRAY_SUPPORT) { this.length = 0 this.parent = undefined } // Common case. if (typeof arg === 'number') { return fromNumber(this, arg) } // Slightly less common case. if (typeof arg === 'string') { return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } // Unusual. return fromObject(this, arg) } function fromNumber (that, length) { that = allocate(that, length < 0 ? 0 : checked(length) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < length; i++) { that[i] = 0 } } return that } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' // Assumption: byteLength() return value is always < kMaxLength. var length = byteLength(string, encoding) | 0 that = allocate(that, length) that.write(string, encoding) return that } function fromObject (that, object) { if (Buffer.isBuffer(object)) return fromBuffer(that, object) if (isArray(object)) return fromArray(that, object) if (object == null) { throw new TypeError('must start with number, buffer, array or string') } if (typeof ArrayBuffer !== 'undefined') { if (object.buffer instanceof ArrayBuffer) { return fromTypedArray(that, object) } if (object instanceof ArrayBuffer) { return fromArrayBuffer(that, object) } } if (object.length) return fromArrayLike(that, object) return fromJsonObject(that, object) } function fromBuffer (that, buffer) { var length = checked(buffer.length) | 0 that = allocate(that, length) buffer.copy(that, 0, 0, length) return that } function fromArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Duplicate of fromArray() to keep fromArray() monomorphic. function fromTypedArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) // Truncating the elements is probably not what people expect from typed // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior // of the old Buffer constructor. for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance array.byteLength that = Buffer._augment(new Uint8Array(array)) } else { // Fallback: Return an object instance of the Buffer class that = fromTypedArray(that, new Uint8Array(array)) } return that } function fromArrayLike (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. // Returns a zero-length buffer for inputs that don't conform to the spec. function fromJsonObject (that, object) { var array var length = 0 if (object.type === 'Buffer' && isArray(object.data)) { array = object.data length = checked(array.length) | 0 } that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array } else { // pre-set for values that may exist in the future Buffer.prototype.length = undefined Buffer.prototype.parent = undefined } function allocate (that, length) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = Buffer._augment(new Uint8Array(length)) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that.length = length that._isBuffer = true } var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 if (fromPool) that.parent = rootParent return that } function checked (length) { // Note: cannot use `length < kMaxLength` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (subject, encoding) { if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) var buf = new Buffer(subject, encoding) delete buf.parent return buf } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length var i = 0 var len = Math.min(x, y) while (i < len) { if (a[i] !== b[i]) break ++i } if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') if (list.length === 0) { return new Buffer(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; i++) { length += list[i].length } } var buf = new Buffer(length) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } function byteLength (string, encoding) { if (typeof string !== 'string') string = '' + string var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'binary': // Deprecated case 'raw': case 'raws': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false start = start | 0 end = end === undefined || end === Infinity ? this.length : end | 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return 0 return Buffer.compare(this, b) } Buffer.prototype.indexOf = function indexOf (val, byteOffset) { if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff else if (byteOffset < -0x80000000) byteOffset = -0x80000000 byteOffset >>= 0 if (this.length === 0) return -1 if (byteOffset >= this.length) return -1 // Negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) if (typeof val === 'string') { if (val.length === 0) return -1 // special case: looking for empty string always fails return String.prototype.indexOf.call(this, val, byteOffset) } if (Buffer.isBuffer(val)) { return arrayIndexOf(this, val, byteOffset) } if (typeof val === 'number') { if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } return arrayIndexOf(this, [ val ], byteOffset) } function arrayIndexOf (arr, val, byteOffset) { var foundIndex = -1 for (var i = 0; byteOffset + i < arr.length; i++) { if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex } else { foundIndex = -1 } } return -1 } throw new TypeError('val must be string, number or Buffer') } // `get` is deprecated Buffer.prototype.get = function get (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` is deprecated Buffer.prototype.set = function set (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) throw new Error('Invalid hex string') buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { var swap = encoding encoding = offset offset = length | 0 length = swap } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'binary': return binaryWrite(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function binarySlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } } if (newBuf.length) newBuf.parent = this.parent || this return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') if (offset < 0) throw new RangeError('index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; i--) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; i++) { target[i + targetStart] = this[i + start] } } else { target._set(this.subarray(start, start + len), targetStart) } return len } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function fill (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (end < start) throw new RangeError('end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') if (end < 0 || end > this.length) throw new RangeError('end out of bounds') var i if (typeof value === 'number') { for (i = start; i < end; i++) { this[i] = value } } else { var bytes = utf8ToBytes(value.toString()) var len = bytes.length for (i = start; i < end; i++) { this[i] = bytes[i % len] } } return this } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function toArrayBuffer () { if (typeof Uint8Array !== 'undefined') { if (Buffer.TYPED_ARRAY_SUPPORT) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) { buf[i] = this[i] } return buf.buffer } } else { throw new TypeError('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function _augment (arr) { arr.constructor = Buffer arr._isBuffer = true // save reference to original Uint8Array set method before overwriting arr._set = arr.set // deprecated arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.equals = BP.equals arr.compare = BP.compare arr.indexOf = BP.indexOf arr.copy = BP.copy arr.slice = BP.slice arr.readUIntLE = BP.readUIntLE arr.readUIntBE = BP.readUIntBE arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readIntLE = BP.readIntLE arr.readIntBE = BP.readIntBE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUIntLE = BP.writeUIntLE arr.writeUIntBE = BP.writeUIntBE arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeIntLE = BP.writeIntLE arr.writeIntBE = BP.writeIntBE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; i++) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"base64-js":1,"ieee754":5,"isarray":4}],4:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],5:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],6:[function(require,module,exports){ var Pipe = require('../pipe').Pipe; var Context = function Context(){ }; Context.prototype.setResult = function(result) { this.result = result; this.hasResult = true; return this; }; Context.prototype.exit = function() { this.exiting = true; return this; }; Context.prototype.switchTo = function(next, pipe) { if (typeof next === 'string' || next instanceof Pipe) { this.nextPipe = next; } else { this.next = next; if (pipe) { this.nextPipe = pipe; } } return this; }; Context.prototype.push = function(child, name) { child.parent = this; if (typeof name !== 'undefined') { child.childName = name; } child.root = this.root || this; child.options = child.options || this.options; if (!this.children) { this.children = [child]; this.nextAfterChildren = this.next || null; this.next = child; } else { this.children[this.children.length - 1].next = child; this.children.push(child); } child.next = this; return this; }; exports.Context = Context; },{"../pipe":20}],7:[function(require,module,exports){ var Context = require('./context').Context; var dateReviver = require('../date-reviver'); var DiffContext = function DiffContext(left, right) { this.left = left; this.right = right; this.pipe = 'diff'; }; DiffContext.prototype = new Context(); DiffContext.prototype.setResult = function(result) { if (this.options.cloneDiffValues) { var clone = typeof this.options.cloneDiffValues === 'function' ? this.options.cloneDiffValues : function(value) { return JSON.parse(JSON.stringify(value), dateReviver); }; if (typeof result[0] === 'object') { result[0] = clone(result[0]); } if (typeof result[1] === 'object') { result[1] = clone(result[1]); } } return Context.prototype.setResult.apply(this, arguments); }; exports.DiffContext = DiffContext; },{"../date-reviver":10,"./context":6}],8:[function(require,module,exports){ var Context = require('./context').Context; var PatchContext = function PatchContext(left, delta) { this.left = left; this.delta = delta; this.pipe = 'patch'; }; PatchContext.prototype = new Context(); exports.PatchContext = PatchContext; },{"./context":6}],9:[function(require,module,exports){ var Context = require('./context').Context; var ReverseContext = function ReverseContext(delta) { this.delta = delta; this.pipe = 'reverse'; }; ReverseContext.prototype = new Context(); exports.ReverseContext = ReverseContext; },{"./context":6}],10:[function(require,module,exports){ // use as 2nd parameter for JSON.parse to revive Date instances module.exports = function dateReviver(key, value) { var parts; if (typeof value === 'string') { parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d*))?(Z|([+\-])(\d{2}):(\d{2}))$/.exec(value); if (parts) { return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3], +parts[4], +parts[5], +parts[6], +(parts[7] || 0))); } } return value; }; },{}],11:[function(require,module,exports){ var Processor = require('./processor').Processor; var Pipe = require('./pipe').Pipe; var DiffContext = require('./contexts/diff').DiffContext; var PatchContext = require('./contexts/patch').PatchContext; var ReverseContext = require('./contexts/reverse').ReverseContext; var trivial = require('./filters/trivial'); var nested = require('./filters/nested'); var arrays = require('./filters/arrays'); var dates = require('./filters/dates'); var texts = require('./filters/texts'); var DiffPatcher = function DiffPatcher(options) { this.processor = new Processor(options); this.processor.pipe(new Pipe('diff').append( nested.collectChildrenDiffFilter, trivial.diffFilter, dates.diffFilter, texts.diffFilter, nested.objectsDiffFilter, arrays.diffFilter ).shouldHaveResult()); this.processor.pipe(new Pipe('patch').append( nested.collectChildrenPatchFilter, arrays.collectChildrenPatchFilter, trivial.patchFilter, texts.patchFilter, nested.patchFilter, arrays.patchFilter ).shouldHaveResult()); this.processor.pipe(new Pipe('reverse').append( nested.collectChildrenReverseFilter, arrays.collectChildrenReverseFilter, trivial.reverseFilter, texts.reverseFilter, nested.reverseFilter, arrays.reverseFilter ).shouldHaveResult()); }; DiffPatcher.prototype.options = function() { return this.processor.options.apply(this.processor, arguments); }; DiffPatcher.prototype.diff = function(left, right) { return this.processor.process(new DiffContext(left, right)); }; DiffPatcher.prototype.patch = function(left, delta) { return this.processor.process(new PatchContext(left, delta)); }; DiffPatcher.prototype.reverse = function(delta) { return this.processor.process(new ReverseContext(delta)); }; DiffPatcher.prototype.unpatch = function(right, delta) { return this.patch(right, this.reverse(delta)); }; exports.DiffPatcher = DiffPatcher; },{"./contexts/diff":7,"./contexts/patch":8,"./contexts/reverse":9,"./filters/arrays":13,"./filters/dates":14,"./filters/nested":16,"./filters/texts":17,"./filters/trivial":18,"./pipe":20,"./processor":21}],12:[function(require,module,exports){ exports.isBrowser = typeof window !== 'undefined'; },{}],13:[function(require,module,exports){ var DiffContext = require('../contexts/diff').DiffContext; var PatchContext = require('../contexts/patch').PatchContext; var ReverseContext = require('../contexts/reverse').ReverseContext; var lcs = require('./lcs'); var ARRAY_MOVE = 3; var isArray = (typeof Array.isArray === 'function') ? // use native function Array.isArray : // use instanceof operator function(a) { return a instanceof Array; }; var arrayIndexOf = typeof Array.prototype.indexOf === 'function' ? function(array, item) { return array.indexOf(item); } : function(array, item) { var length = array.length; for (var i = 0; i < length; i++) { if (array[i] === item) { return i; } } return -1; }; function arraysHaveMatchByRef(array1, array2, len1, len2) { for (var index1 = 0; index1 < len1; index1++) { var val1 = array1[index1]; for (var index2 = 0; index2 < len2; index2++) { var val2 = array2[index2]; if (val1 === val2) { return true; } } } } function matchItems(array1, array2, index1, index2, context) { var value1 = array1[index1]; var value2 = array2[index2]; if (value1 === value2) { return true; } if (typeof value1 !== 'object' || typeof value2 !== 'object') { return false; } var objectHash = context.objectHash; if (!objectHash) { // no way to match objects was provided, try match by position return context.matchByPosition && index1 === index2; } var hash1; var hash2; if (typeof index1 === 'number') { context.hashCache1 = context.hashCache1 || []; hash1 = context.hashCache1[index1]; if (typeof hash1 === 'undefined') { context.hashCache1[index1] = hash1 = objectHash(value1, index1); } } else { hash1 = objectHash(value1); } if (typeof hash1 === 'undefined') { return false; } if (typeof index2 === 'number') { context.hashCache2 = context.hashCache2 || []; hash2 = context.hashCache2[index2]; if (typeof hash2 === 'undefined') { context.hashCache2[index2] = hash2 = objectHash(value2, index2); } } else { hash2 = objectHash(value2); } if (typeof hash2 === 'undefined') { return false; } return hash1 === hash2; } var diffFilter = function arraysDiffFilter(context) { if (!context.leftIsArray) { return; } var matchContext = { objectHash: context.options && context.options.objectHash, matchByPosition: context.options && context.options.matchByPosition }; var commonHead = 0; var commonTail = 0; var index; var index1; var index2; var array1 = context.left; var array2 = context.right; var len1 = array1.length; var len2 = array2.length; var child; if (len1 > 0 && len2 > 0 && !matchContext.objectHash && typeof matchContext.matchByPosition !== 'boolean') { matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2); } // separate common head while (commonHead < len1 && commonHead < len2 && matchItems(array1, array2, commonHead, commonHead, matchContext)) { index = commonHead; child = new DiffContext(context.left[index], context.right[index]); context.push(child, index); commonHead++; } // separate common tail while (commonTail + commonHead < len1 && commonTail + commonHead < len2 && matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) { index1 = len1 - 1 - commonTail; index2 = len2 - 1 - commonTail; child = new DiffContext(context.left[index1], context.right[index2]); context.push(child, index2); commonTail++; } var result; if (commonHead + commonTail === len1) { if (len1 === len2) { // arrays are identical context.setResult(undefined).exit(); return; } // trivial case, a block (1 or more consecutive items) was added result = result || { _t: 'a' }; for (index = commonHead; index < len2 - commonTail; index++) { result[index] = [array2[index]]; } context.setResult(result).exit(); return; } if (commonHead + commonTail === len2) { // trivial case, a block (1 or more consecutive items) was removed result = result || { _t: 'a' }; for (index = commonHead; index < len1 - commonTail; index++) { result['_' + index] = [array1[index], 0, 0]; } context.setResult(result).exit(); return; } // reset hash cache delete matchContext.hashCache1; delete matchContext.hashCache2; // diff is not trivial, find the LCS (Longest Common Subsequence) var trimmed1 = array1.slice(commonHead, len1 - commonTail); var trimmed2 = array2.slice(commonHead, len2 - commonTail); var seq = lcs.get( trimmed1, trimmed2, matchItems, matchContext ); var removedItems = []; result = result || { _t: 'a' }; for (index = commonHead; index < len1 - commonTail; index++) { if (arrayIndexOf(seq.indices1, index - commonHead) < 0) { // removed result['_' + index] = [array1[index], 0, 0]; removedItems.push(index); } } var detectMove = true; if (context.options && context.options.arrays && context.options.arrays.detectMove === false) { detectMove = false; } var includeValueOnMove = false; if (context.options && context.options.arrays && context.options.arrays.includeValueOnMove) { includeValueOnMove = true; } var removedItemsLength = removedItems.length; for (index = commonHead; index < len2 - commonTail; index++) { var indexOnArray2 = arrayIndexOf(seq.indices2, index - commonHead); if (indexOnArray2 < 0) { // added, try to match with a removed item and register as position move var isMove = false; if (detectMove && removedItemsLength > 0) { for (var removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) { index1 = removedItems[removeItemIndex1]; if (matchItems(trimmed1, trimmed2, index1 - commonHead, index - commonHead, matchContext)) { // store position move as: [originalValue, newPosition, ARRAY_MOVE] result['_' + index1].splice(1, 2, index, ARRAY_MOVE); if (!includeValueOnMove) { // don't include moved value on diff, to save bytes result['_' + index1][0] = ''; } index2 = index; child = new DiffContext(context.left[index1], context.right[index2]); context.push(child, index2); removedItems.splice(removeItemIndex1, 1); isMove = true; break; } } } if (!isMove) { // added result[index] = [array2[index]]; } } else { // match, do inner diff index1 = seq.indices1[indexOnArray2] + commonHead; index2 = seq.indices2[indexOnArray2] + commonHead; child = new DiffContext(context.left[index1], context.right[index2]); context.push(child, index2); } } context.setResult(result).exit(); }; diffFilter.filterName = 'arrays'; var compare = { numerically: function(a, b) { return a - b; }, numericallyBy: function(name) { return function(a, b) { return a[name] - b[name]; }; } }; var patchFilter = function nestedPatchFilter(context) { if (!context.nested) { return; } if (context.delta._t !== 'a') { return; } var index, index1; var delta = context.delta; var array = context.left; // first, separate removals, insertions and modifications var toRemove = []; var toInsert = []; var toModify = []; for (index in delta) { if (index !== '_t') { if (index[0] === '_') { // removed item from original array if (delta[index][2] === 0 || delta[index][2] === ARRAY_MOVE) { toRemove.push(parseInt(index.slice(1), 10)); } else { throw new Error('only removal or move can be applied at original array indices' + ', invalid diff type: ' + delta[index][2]); } } else { if (delta[index].length === 1) { // added item at new array toInsert.push({ index: parseInt(index, 10), value: delta[index][0] }); } else { // modified item at new array toModify.push({ index: parseInt(index, 10), delta: delta[index] }); } } } } // remove items, in reverse order to avoid sawing our own floor toRemove = toRemove.sort(compare.numerically); for (index = toRemove.length - 1; index >= 0; index--) { index1 = toRemove[index]; var indexDiff = delta['_' + index1]; var removedValue = array.splice(index1, 1)[0]; if (indexDiff[2] === ARRAY_MOVE) { // reinsert later toInsert.push({ index: indexDiff[1], value: removedValue }); } } // insert items, in reverse order to avoid moving our own floor toInsert = toInsert.sort(compare.numericallyBy('index')); var toInsertLength = toInsert.length; for (index = 0; index < toInsertLength; index++) { var insertion = toInsert[index]; array.splice(insertion.index, 0, insertion.value); } // apply modifications var toModifyLength = toModify.length; var child; if (toModifyLength > 0) { for (index = 0; index < toModifyLength; index++) { var modification = toModify[index]; child = new PatchContext(context.left[modification.index], modification.delta); context.push(child, modification.index); } } if (!context.children) { context.setResult(context.left).exit(); return; } context.exit(); }; patchFilter.filterName = 'arrays'; var collectChildrenPatchFilter = function collectChildrenPatchFilter(context) { if (!context || !context.children) { return; } if (context.delta._t !== 'a') { return; } var length = context.children.length; var child; for (var index = 0; index < length; index++) { child = context.children[index]; context.left[child.childName] = child.result; } context.setResult(context.left).exit(); }; collectChildrenPatchFilter.filterName = 'arraysCollectChildren'; var reverseFilter = function arraysReverseFilter(context) { if (!context.nested) { if (context.delta[2] === ARRAY_MOVE) { context.newName = '_' + context.delta[1]; context.setResult([context.delta[0], parseInt(context.childName.substr(1), 10), ARRAY_MOVE]).exit(); } return; } if (context.delta._t !== 'a') { return; } var name, child; for (name in context.delta) { if (name === '_t') { continue; } child = new ReverseContext(context.delta[name]); context.push(child, name); } context.exit(); }; reverseFilter.filterName = 'arrays'; var reverseArrayDeltaIndex = function(delta, index, itemDelta) { if (typeof index === 'string' && index[0] === '_') { return parseInt(index.substr(1), 10); } else if (isArray(itemDelta) && itemDelta[2] === 0) { return '_' + index; } var reverseIndex = +index; for (var deltaIndex in delta) { var deltaItem = delta[deltaIndex]; if (isArray(deltaItem)) { if (deltaItem[2] === ARRAY_MOVE) { var moveFromIndex = parseInt(deltaIndex.substr(1), 10); var moveToIndex = deltaItem[1]; if (moveToIndex === +index) { return moveFromIndex; } if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) { reverseIndex++; } else if (moveFromIndex >= reverseIndex && moveToIndex < reverseIndex) { reverseIndex--; } } else if (deltaItem[2] === 0) { var deleteIndex = parseInt(deltaIndex.substr(1), 10); if (deleteIndex <= reverseIndex) { reverseIndex++; } } else if (deltaItem.length === 1 && deltaIndex <= reverseIndex) { reverseIndex--; } } } return reverseIndex; }; var collectChildrenReverseFilter = function collectChildrenReverseFilter(context) { if (!context || !context.children) { return; } if (context.delta._t !== 'a') { return; } var length = context.children.length; var child; var delta = { _t: 'a' }; for (var index = 0; index < length; index++) { child = context.children[index]; var name = child.newName; if (typeof name === 'undefined') { name = reverseArrayDeltaIndex(context.delta, child.childName, child.result); } if (delta[name] !== child.result) { delta[name] = child.result; } } context.setResult(delta).exit(); }; collectChildrenReverseFilter.filterName = 'arraysCollectChildren'; exports.diffFilter = diffFilter; exports.patchFilter = patchFilter; exports.collectChildrenPatchFilter = collectChildrenPatchFilter; exports.reverseFilter = reverseFilter; exports.collectChildrenReverseFilter = collectChildrenReverseFilter; },{"../contexts/diff":7,"../contexts/patch":8,"../contexts/reverse":9,"./lcs":15}],14:[function(require,module,exports){ var diffFilter = function datesDiffFilter(context) { if (context.left instanceof Date) { if (context.right instanceof Date) { if (context.left.getTime() !== context.right.getTime()) { context.setResult([context.left, context.right]); } else { context.setResult(undefined); } } else { context.setResult([context.left, context.right]); } context.exit(); } else if (context.right instanceof Date) { context.setResult([context.left, context.right]).exit(); } }; diffFilter.filterName = 'dates'; exports.diffFilter = diffFilter; },{}],15:[function(require,module,exports){ /* LCS implementation that supports arrays or strings reference: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem */ var defaultMatch = function(array1, array2, index1, index2) { return array1[index1] === array2[index2]; }; var lengthMatrix = function(array1, array2, match, context) { var len1 = array1.length; var len2 = array2.length; var x, y; // initialize empty matrix of len1+1 x len2+1 var matrix = [len1 + 1]; for (x = 0; x < len1 + 1; x++) { matrix[x] = [len2 + 1]; for (y = 0; y < len2 + 1; y++) { matrix[x][y] = 0; } } matrix.match = match; // save sequence lengths for each coordinate for (x = 1; x < len1 + 1; x++) { for (y = 1; y < len2 + 1; y++) { if (match(array1, array2, x - 1, y - 1, context)) { matrix[x][y] = matrix[x - 1][y - 1] + 1; } else { matrix[x][y] = Math.max(matrix[x - 1][y], matrix[x][y - 1]); } } } return matrix; }; var backtrack = function(matrix, array1, array2, index1, index2, context) { if (index1 === 0 || index2 === 0) { return { sequence: [], indices1: [], indices2: [] }; } if (matrix.match(array1, array2, index1 - 1, index2 - 1, context)) { var subsequence = backtrack(matrix, array1, array2, index1 - 1, index2 - 1, context); subsequence.sequence.push(array1[index1 - 1]); subsequence.indices1.push(index1 - 1); subsequence.indices2.push(index2 - 1); return subsequence; } if (matrix[index1][index2 - 1] > matrix[index1 - 1][index2]) { return backtrack(matrix, array1, array2, index1, index2 - 1, context); } else { return backtrack(matrix, array1, array2, index1 - 1, index2, context); } }; var get = function(array1, array2, match, context) { context = context || {}; var matrix = lengthMatrix(array1, array2, match || defaultMatch, context); var result = backtrack(matrix, array1, array2, array1.length, array2.length, context); if (typeof array1 === 'string' && typeof array2 === 'string') { result.sequence = result.sequence.join(''); } return result; }; exports.get = get; },{}],16:[function(require,module,exports){ var DiffContext = require('../contexts/diff').DiffContext; var PatchContext = require('../contexts/patch').PatchContext; var ReverseContext = require('../contexts/reverse').ReverseContext; var collectChildrenDiffFilter = function collectChildrenDiffFilter(context) { if (!context || !context.children) { return; } var length = context.children.length; var child; var result = context.result; for (var index = 0; index < length; index++) { child = context.children[index]; if (typeof child.result === 'undefined') { continue; } result = result || {}; result[child.childName] = child.result; } if (result && context.leftIsArray) { result._t = 'a'; } context.setResult(result).exit(); }; collectChildrenDiffFilter.filterName = 'collectChildren'; var objectsDiffFilter = function objectsDiffFilter(context) { if (context.leftIsArray || context.leftType !== 'object') { return; } var name, child, propertyFilter = context.options.propertyFilter; for (name in context.left) { if (!Object.prototype.hasOwnProperty.call(context.left, name)) { continue; } if (propertyFilter && !propertyFilter(name, context)) { continue; } child = new DiffContext(context.left[name], context.right[name]); context.push(child, name); } for (name in context.right) { if (!Object.prototype.hasOwnProperty.call(context.right, name)) { continue; } if (propertyFilter && !propertyFilter(name, context)) { continue; } if (typeof context.left[name] === 'undefined') { child = new DiffContext(undefined, context.right[name]); context.push(child, name); } } if (!context.children || context.children.length === 0) { context.setResult(undefined).exit(); return; } context.exit(); }; objectsDiffFilter.filterName = 'objects'; var patchFilter = function nestedPatchFilter(context) { if (!context.nested) { return; } if (context.delta._t) { return; } var name, child; for (name in context.delta) { child = new PatchContext(context.left[name], context.delta[name]); context.push(child, name); } context.exit(); }; patchFilter.filterName = 'objects'; var collectChildrenPatchFilter = function collectChildrenPatchFilter(context) { if (!context || !context.children) { return; } if (context.delta._t) { return; } var length = context.children.length; var child; for (var index = 0; index < length; index++) { child = context.children[index]; if (Object.prototype.hasOwnProperty.call(context.left, child.childName) && child.result === undefined) { delete context.left[child.childName]; } else if (context.left[child.childName] !== child.result) { context.left[child.childName] = child.result; } } context.setResult(context.left).exit(); }; collectChildrenPatchFilter.filterName = 'collectChildren'; var reverseFilter = function nestedReverseFilter(context) { if (!context.nested) { return; } if (context.delta._t) { return; } var name, child; for (name in context.delta) { child = new ReverseContext(context.delta[name]); context.push(child, name); } context.exit(); }; reverseFilter.filterName = 'objects'; var collectChildrenReverseFilter = function collectChildrenReverseFilter(context) { if (!context || !context.children) { return; } if (context.delta._t) { return; } var length = context.children.length; var child; var delta = {}; for (var index = 0; index < length; index++) { child = context.children[index]; if (delta[child.childName] !== child.result) { delta[child.childName] = child.result; } } context.setResult(delta).exit(); }; collectChildrenReverseFilter.filterName = 'collectChildren'; exports.collectChildrenDiffFilter = collectChildrenDiffFilter; exports.objectsDiffFilter = objectsDiffFilter; exports.patchFilter = patchFilter; exports.collectChildrenPatchFilter = collectChildrenPatchFilter; exports.reverseFilter = reverseFilter; exports.collectChildrenReverseFilter = collectChildrenReverseFilter; },{"../contexts/diff":7,"../contexts/patch":8,"../contexts/reverse":9}],17:[function(require,module,exports){ /* global diff_match_patch */ var TEXT_DIFF = 2; var DEFAULT_MIN_LENGTH = 60; var cachedDiffPatch = null; var getDiffMatchPatch = function(required) { /*jshint camelcase: false */ if (!cachedDiffPatch) { var instance; if (typeof diff_match_patch !== 'undefined') { // already loaded, probably a browser instance = typeof diff_match_patch === 'function' ? new diff_match_patch() : new diff_match_patch.diff_match_patch(); } else if (typeof require === 'function') { try { var dmpModuleName = 'diff_match_patch_uncompressed'; var dmp = require('../../public/external/' + dmpModuleName); instance = new dmp.diff_match_patch(); } catch (err) { instance = null; } } if (!instance) { if (!required) { return null; } var error = new Error('text diff_match_patch library not found'); error.diff_match_patch_not_found = true; throw error; } cachedDiffPatch = { diff: function(txt1, txt2) { return instance.patch_toText(instance.patch_make(txt1, txt2)); }, patch: function(txt1, patch) { var results = instance.patch_apply(instance.patch_fromText(patch), txt1); for (var i = 0; i < results[1].length; i++) { if (!results[1][i]) { var error = new Error('text patch failed'); error.textPatchFailed = true; } } return results[0]; } }; } return cachedDiffPatch; }; var diffFilter = function textsDiffFilter(context) { if (context.leftType !== 'string') { return; } var minLength = (context.options && context.options.textDiff && context.options.textDiff.minLength) || DEFAULT_MIN_LENGTH; if (context.left.length < minLength || context.right.length < minLength) { context.setResult([context.left, context.right]).exit(); return; } // large text, try to use a text-diff algorithm var diffMatchPatch = getDiffMatchPatch(); if (!diffMatchPatch) { // diff-match-patch library not available, fallback to regular string replace context.setResult([context.left, context.right]).exit(); return; } var diff = diffMatchPatch.diff; context.setResult([diff(context.left, context.right), 0, TEXT_DIFF]).exit(); }; diffFilter.filterName = 'texts'; var patchFilter = function textsPatchFilter(context) { if (context.nested) { return; } if (context.delta[2] !== TEXT_DIFF) { return; } // text-diff, use a text-patch algorithm var patch = getDiffMatchPatch(true).patch; context.setResult(patch(context.left, context.delta[0])).exit(); }; patchFilter.filterName = 'texts'; var textDeltaReverse = function(delta) { var i, l, lines, line, lineTmp, header = null, headerRegex = /^@@ +\-(\d+),(\d+) +\+(\d+),(\d+) +@@$/, lineHeader, lineAdd, lineRemove; lines = delta.split('\n'); for (i = 0, l = lines.length; i < l; i++) { line = lines[i]; var lineStart = line.slice(0, 1); if (lineStart === '@') { header = headerRegex.exec(line); lineHeader = i; lineAdd = null; lineRemove = null; // fix header lines[lineHeader] = '@@ -' + header[3] + ',' + header[4] + ' +' + header[1] + ',' + header[2] + ' @@'; } else if (lineStart === '+') { lineAdd = i; lines[i] = '-' + lines[i].slice(1); if (lines[i - 1].slice(0, 1) === '+') { // swap lines to keep default order (-+) lineTmp = lines[i]; lines[i] = lines[i - 1]; lines[i - 1] = lineTmp; } } else if (lineStart === '-') { lineRemove = i; lines[i] = '+' + lines[i].slice(1); } } return lines.join('\n'); }; var reverseFilter = function textsReverseFilter(context) { if (context.nested) { return; } if (context.delta[2] !== TEXT_DIFF) { return; } // text-diff, use a text-diff algorithm context.setResult([textDeltaReverse(context.delta[0]), 0, TEXT_DIFF]).exit(); }; reverseFilter.filterName = 'texts'; exports.diffFilter = diffFilter; exports.patchFilter = patchFilter; exports.reverseFilter = reverseFilter; },{}],18:[function(require,module,exports){ var isArray = (typeof Array.isArray === 'function') ? // use native function Array.isArray : // use instanceof operator function(a) { return a instanceof Array; }; var diffFilter = function trivialMatchesDiffFilter(context) { if (context.left === context.right) { context.setResult(undefined).exit(); return; } if (typeof context.left === 'undefined') { if (typeof context.right === 'function') { throw new Error('functions are not supported'); } context.setResult([context.right]).exit(); return; } if (typeof context.right === 'undefined') { context.setResult([context.left, 0, 0]).exit(); return; } if (typeof context.left === 'function' || typeof context.right === 'function') { throw new Error('functions are not supported'); } context.leftType = context.left === null ? 'null' : typeof context.left; context.rightType = context.right === null ? 'null' : typeof context.right; if (context.leftType !== context.rightType) { context.setResult([context.left, context.right]).exit(); return; } if (context.leftType === 'boolean' || context.leftType === 'number') { context.setResult([context.left, context.right]).exit(); return; } if (context.leftType === 'object') { context.leftIsArray = isArray(context.left); } if (context.rightType === 'object') { context.rightIsArray = isArray(context.right); } if (context.leftIsArray !== context.rightIsArray) { context.setResult([context.left, context.right]).exit(); return; } }; diffFilter.filterName = 'trivial'; var patchFilter = function trivialMatchesPatchFilter(context) { if (typeof context.delta === 'undefined') { context.setResult(context.left).exit(); return; } context.nested = !isArray(context.delta); if (context.nested) { return; } if (context.delta.length === 1) { context.setResult(context.delta[0]).exit(); return; } if (context.delta.length === 2) { context.setResult(context.delta[1]).exit(); return; } if (context.delta.length === 3 && context.delta[2] === 0) { context.setResult(undefined).exit(); return; } }; patchFilter.filterName = 'trivial'; var reverseFilter = function trivialReferseFilter(context) { if (typeof context.delta === 'undefined') { context.setResult(context.delta).exit(); return; } context.nested = !isArray(context.delta); if (context.nested) { return; } if (context.delta.length === 1) { context.setResult([context.delta[0], 0, 0]).exit(); return; } if (context.delta.length === 2) { context.setResult([context.delta[1], context.delta[0]]).exit(); return; } if (context.delta.length === 3 && context.delta[2] === 0) { context.setResult([context.delta[0]]).exit(); return; } }; reverseFilter.filterName = 'trivial'; exports.diffFilter = diffFilter; exports.patchFilter = patchFilter; exports.reverseFilter = reverseFilter; },{}],19:[function(require,module,exports){ var environment = require('./environment'); var DiffPatcher = require('./diffpatcher').DiffPatcher; exports.DiffPatcher = DiffPatcher; exports.create = function(options){ return new DiffPatcher(options); }; exports.dateReviver = require('./date-reviver'); var defaultInstance; exports.diff = function() { if (!defaultInstance) { defaultInstance = new DiffPatcher(); } return defaultInstance.diff.apply(defaultInstance, arguments); }; exports.patch = function() { if (!defaultInstance) { defaultInstance = new DiffPatcher(); } return defaultInstance.patch.apply(defaultInstance, arguments); }; exports.unpatch = function() { if (!defaultInstance) { defaultInstance = new DiffPatcher(); } return defaultInstance.unpatch.apply(defaultInstance, arguments); }; exports.reverse = function() { if (!defaultInstance) { defaultInstance = new DiffPatcher(); } return defaultInstance.reverse.apply(defaultInstance, arguments); }; if (environment.isBrowser) { exports.homepage = '{{package-homepage}}'; exports.version = '{{package-version}}'; } else { var packageInfoModuleName = '../package.json'; var packageInfo = require(packageInfoModuleName); exports.homepage = packageInfo.homepage; exports.version = packageInfo.version; var formatterModuleName = './formatters'; var formatters = require(formatterModuleName); exports.formatters = formatters; // shortcut for console exports.console = formatters.console; } },{"./date-reviver":10,"./diffpatcher":11,"./environment":12}],20:[function(require,module,exports){ var Pipe = function Pipe(name) { this.name = name; this.filters = []; }; Pipe.prototype.process = function(input) { if (!this.processor) { throw new Error('add this pipe to a processor before using it'); } var debug = this.debug; var length = this.filters.length; var context = input; for (var index = 0; index < length; index++) { var filter = this.filters[index]; if (debug) { this.log('filter: ' + filter.filterName); } filter(context); if (typeof context === 'object' && context.exiting) { context.exiting = false; break; } } if (!context.next && this.resultCheck) { this.resultCheck(context); } }; Pipe.prototype.log = function(msg) { console.log('[jsondiffpatch] ' + this.name + ' pipe, ' + msg); }; Pipe.prototype.append = function() { this.filters.push.apply(this.filters, arguments); return this; }; Pipe.prototype.prepend = function() { this.filters.unshift.apply(this.filters, arguments); return this; }; Pipe.prototype.indexOf = function(filterName) { if (!filterName) { throw new Error('a filter name is required'); } for (var index = 0; index < this.filters.length; index++) { var filter = this.filters[index]; if (filter.filterName === filterName) { return index; } } throw new Error('filter not found: ' + filterName); }; Pipe.prototype.list = function() { var names = []; for (var index = 0; index < this.filters.length; index++) { var filter = this.filters[index]; names.push(filter.filterName); } return names; }; Pipe.prototype.after = function(filterName) { var index = this.indexOf(filterName); var params = Array.prototype.slice.call(arguments, 1); if (!params.length) { throw new Error('a filter is required'); } params.unshift(index + 1, 0); Array.prototype.splice.apply(this.filters, params); return this; }; Pipe.prototype.before = function(filterName) { var index = this.indexOf(filterName); var params = Array.prototype.slice.call(arguments, 1); if (!params.length) { throw new Error('a filter is required'); } params.unshift(index, 0); Array.prototype.splice.apply(this.filters, params); return this; }; Pipe.prototype.clear = function() { this.filters.length = 0; return this; }; Pipe.prototype.shouldHaveResult = function(should) { if (should === false) { this.resultCheck = null; return; } if (this.resultCheck) { return; } var pipe = this; this.resultCheck = function(context) { if (!context.hasResult) { console.log(context); var error = new Error(pipe.name + ' failed'); error.noResult = true; throw error; } }; return this; }; exports.Pipe = Pipe; },{}],21:[function(require,module,exports){ var Processor = function Processor(options){ this.selfOptions = options || {}; this.pipes = {}; }; Processor.prototype.options = function(options) { if (options) { this.selfOptions = options; } return this.selfOptions; }; Processor.prototype.pipe = function(name, pipe) { if (typeof name === 'string') { if (typeof pipe === 'undefined') { return this.pipes[name]; } else { this.pipes[name] = pipe; } } if (name && name.name) { pipe = name; if (pipe.processor === this) { return pipe; } this.pipes[pipe.name] = pipe; } pipe.processor = this; return pipe; }; Processor.prototype.process = function(input, pipe) { var context = input; context.options = this.options(); var nextPipe = pipe || input.pipe || 'default'; var lastPipe, lastContext; while (nextPipe) { if (typeof context.nextAfterChildren !== 'undefined') { // children processed and coming back to parent context.next = context.nextAfterChildren; context.nextAfterChildren = null; } if (typeof nextPipe === 'string') { nextPipe = this.pipe(nextPipe); } nextPipe.process(context); lastContext = context; lastPipe = nextPipe; nextPipe = null; if (context) { if (context.next) { context = context.next; nextPipe = lastContext.nextPipe || context.pipe || lastPipe; } } } return context.hasResult ? context.result : undefined; }; exports.Processor = Processor; },{}],22:[function(require,module,exports){ exports.RateLimiter = require('./lib/rateLimiter'); exports.TokenBucket = require('./lib/tokenBucket'); },{"./lib/rateLimiter":24,"./lib/tokenBucket":25}],23:[function(require,module,exports){ (function (process){ var getMilliseconds = function() { if (typeof process !== 'undefined' && process.hrtime) { var hrtime = process.hrtime(); var seconds = hrtime[0]; var nanoseconds = hrtime[1]; return seconds * 1e3 + Math.floor(nanoseconds / 1e6); } return new Date().getTime(); } module.exports = getMilliseconds; }).call(this,require('_process')) },{"_process":26}],24:[function(require,module,exports){ (function (process){ var TokenBucket = require('./tokenBucket'); var getMilliseconds = require('./clock'); /** * A generic rate limiter. Underneath the hood, this uses a token bucket plus * an additional check to limit how many tokens we can remove each interval. * @author John Hurliman * * @param {Number} tokensPerInterval Maximum number of tokens that can be * removed at any given moment and over the course of one interval. * @param {String|Number} interval The interval length in milliseconds, or as * one of the following strings: 'second', 'minute', 'hour', day'. * @param {Boolean} fireImmediately Optional. Whether or not the callback * will fire immediately when rate limiting is in effect (default is false). */ var RateLimiter = function(tokensPerInterval, interval, fireImmediately) { this.tokenBucket = new TokenBucket(tokensPerInterval, tokensPerInterval, interval, null); // Fill the token bucket to start this.tokenBucket.content = tokensPerInterval; this.curIntervalStart = getMilliseconds(); this.tokensThisInterval = 0; this.fireImmediately = fireImmediately; }; RateLimiter.prototype = { tokenBucket: null, curIntervalStart: 0, tokensThisInterval: 0, fireImmediately: false, /** * Remove the requested number of tokens and fire the given callback. If the * rate limiter contains enough tokens and we haven't spent too many tokens * in this interval already, this will happen immediately. Otherwise, the * removal and callback will happen when enough tokens become available. * @param {Number} count The number of tokens to remove. * @param {Function} callback(err, remainingTokens) * @returns {Boolean} True if the callback was fired immediately, otherwise * false. */ removeTokens: function(count, callback) { // Make sure the request isn't for more than we can handle if (count > this.tokenBucket.bucketSize) { process.nextTick(callback.bind(null, 'Requested tokens ' + count + ' exceeds maximum tokens per interval ' + this.tokenBucket.bucketSize, null)); return false; } var self = this; var now = getMilliseconds(); // Advance the current interval and reset the current interval token count // if needed if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) { this.curIntervalStart = now; this.tokensThisInterval = 0; } // If we don't have enough tokens left in this interval, wait until the // next interval if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) { if (this.fireImmediately) { process.nextTick(callback.bind(null, null, -1)); } else { var waitInterval = Math.ceil( this.curIntervalStart + this.tokenBucket.interval - now); setTimeout(function() { self.tokenBucket.removeTokens(count, afterTokensRemoved); }, waitInterval); } return false; } // Remove the requested number of tokens from the token bucket return this.tokenBucket.removeTokens(count, afterTokensRemoved); function afterTokensRemoved(err, tokensRemaining) { if (err) return callback(err, null); self.tokensThisInterval += count; callback(null, tokensRemaining); } }, /** * Attempt to remove the requested number of tokens and return immediately. * If the bucket (and any parent buckets) contains enough tokens and we * haven't spent too many tokens in this interval already, this will return * true. Otherwise, false is returned. * @param {Number} count The number of tokens to remove. * @param {Boolean} True if the tokens were successfully removed, otherwise * false. */ tryRemoveTokens: function(count) { // Make sure the request isn't for more than we can handle if (count > this.tokenBucket.bucketSize) return false; var now = getMilliseconds(); // Advance the current interval and reset the current interval token count // if needed if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) { this.curIntervalStart = now; this.tokensThisInterval = 0; } // If we don't have enough tokens left in this interval, return false if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) return false; // Try to remove the requested number of tokens from the token bucket var removed = this.tokenBucket.tryRemoveTokens(count); if (removed) { this.tokensThisInterval += count; } return removed; }, /** * Returns the number of tokens remaining in the TokenBucket. * @returns {Number} The number of tokens remaining. */ getTokensRemaining: function () { this.tokenBucket.drip(); return this.tokenBucket.content; } }; module.exports = RateLimiter; }).call(this,require('_process')) },{"./clock":23,"./tokenBucket":25,"_process":26}],25:[function(require,module,exports){ (function (process){ /** * A hierarchical token bucket for rate limiting. See * http://en.wikipedia.org/wiki/Token_bucket for more information. * @author John Hurliman * * @param {Number} bucketSize Maximum number of tokens to hold in the bucket. * Also known as the burst rate. * @param {Number} tokensPerInterval Number of tokens to drip into the bucket * over the course of one interval. * @param {String|Number} interval The interval length in milliseconds, or as * one of the following strings: 'second', 'minute', 'hour', day'. * @param {TokenBucket} parentBucket Optional. A token bucket that will act as * the parent of this bucket. */ var TokenBucket = function(bucketSize, tokensPerInterval, interval, parentBucket) { this.bucketSize = bucketSize; this.tokensPerInterval = tokensPerInterval; if (typeof interval === 'string') { switch (interval) { case 'sec': case 'second': this.interval = 1000; break; case 'min': case 'minute': this.interval = 1000 * 60; break; case 'hr': case 'hour': this.interval = 1000 * 60 * 60; break; case 'day': this.interval = 1000 * 60 * 60 * 24; break; default: throw new Error('Invaid interval ' + interval); } } else { this.interval = interval; } this.parentBucket = parentBucket; this.content = 0; this.lastDrip = +new Date(); }; TokenBucket.prototype = { bucketSize: 1, tokensPerInterval: 1, interval: 1000, parentBucket: null, content: 0, lastDrip: 0, /** * Remove the requested number of tokens and fire the given callback. If the * bucket (and any parent buckets) contains enough tokens this will happen * immediately. Otherwise, the removal and callback will happen when enough * tokens become available. * @param {Number} count The number of tokens to remove. * @param {Function} callback(err, remainingTokens) * @returns {Boolean} True if the callback was fired immediately, otherwise * false. */ removeTokens: function(count, callback) { var self = this; // Is this an infinite size bucket? if (!this.bucketSize) { process.nextTick(callback.bind(null, null, count, Number.POSITIVE_INFINITY)); return true; } // Make sure the bucket can hold the requested number of tokens if (count > this.bucketSize) { process.nextTick(callback.bind(null, 'Requested tokens ' + count + ' exceeds bucket size ' + this.bucketSize, null)); return false; } // Drip new tokens into this bucket this.drip(); // If we don't have enough tokens in this bucket, come back later if (count > this.content) return comeBackLater(); if (this.parentBucket) { // Remove the requested from the parent bucket first return this.parentBucket.removeTokens(count, function(err, remainingTokens) { if (err) return callback(err, null); // Check that we still have enough tokens in this bucket if (count > self.content) return comeBackLater(); // Tokens were removed from the parent bucket, now remove them from // this bucket and fire the callback. Note that we look at the current // bucket and parent bucket's remaining tokens and return the smaller // of the two values self.content -= count; callback(null, Math.min(remainingTokens, self.content)); }); } else { // Remove the requested tokens from this bucket and fire the callback this.content -= count; process.nextTick(callback.bind(null, null, this.content)); return true; } function comeBackLater() { // How long do we need to wait to make up the difference in tokens? var waitInterval = Math.ceil( (count - self.content) * (self.interval / self.tokensPerInterval)); setTimeout(function() { self.removeTokens(count, callback); }, waitInterval); return false; } }, /** * Attempt to remove the requested number of tokens and return immediately. * If the bucket (and any parent buckets) contains enough tokens this will * return true, otherwise false is returned. * @param {Number} count The number of tokens to remove. * @param {Boolean} True if the tokens were successfully removed, otherwise * false. */ tryRemoveTokens: function(count) { // Is this an infinite size bucket? if (!this.bucketSize) return true; // Make sure the bucket can hold the requested number of tokens if (count > this.bucketSize) return false; // Drip new tokens into this bucket this.drip(); // If we don't have enough tokens in this bucket, return false if (count > this.content) return false; // Try to remove the requested tokens from the parent bucket if (this.parentBucket && !this.parent.tryRemoveTokens(count)) return false; // Remove the requested tokens from this bucket and return this.content -= count; return true; }, /** * Add any new tokens to the bucket since the last drip. * @returns {Boolean} True if new tokens were added, otherwise false. */ drip: function() { if (!this.tokensPerInterval) { this.content = this.bucketSize; return; } var now = +new Date(); var deltaMS = Math.max(now - this.lastDrip, 0); this.lastDrip = now; var dripAmount = deltaMS * (this.tokensPerInterval / this.interval); this.content = Math.min(this.content + dripAmount, this.bucketSize); } }; module.exports = TokenBucket; }).call(this,require('_process')) },{"_process":26}],26:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],27:[function(require,module,exports){ module.exports = OmegaPac; },{}],28:[function(require,module,exports){ var BrowserStorage, Promise, Storage, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Storage = require('./storage'); Promise = require('bluebird'); BrowserStorage = (function(superClass) { extend(BrowserStorage, superClass); function BrowserStorage(storage, prefix) { this.storage = storage; this.prefix = prefix != null ? prefix : ''; this.proto = Object.getPrototypeOf(this.storage); } BrowserStorage.prototype.get = function(keys) { var i, key, len, map, value; map = {}; if (typeof keys === 'string') { map[keys] = void 0; } else if (Array.isArray(keys)) { for (i = 0, len = keys.length; i < len; i++) { key = keys[i]; map[key] = void 0; } } else if (typeof keys === 'object') { map = keys; } for (key in map) { if (!hasProp.call(map, key)) continue; try { value = JSON.parse(this.proto.getItem.call(this.storage, this.prefix + key)); } catch (error) {} if (value != null) { map[key] = value; } if (typeof map[key] === 'undefined') { delete map[key]; } } return Promise.resolve(map); }; BrowserStorage.prototype.set = function(items) { var key, value; for (key in items) { if (!hasProp.call(items, key)) continue; value = items[key]; value = JSON.stringify(value); this.proto.setItem.call(this.storage, this.prefix + key, value); } return Promise.resolve(items); }; BrowserStorage.prototype.remove = function(keys) { var i, index, key, len; if (keys == null) { if (!this.prefix) { this.proto.clear.call(this.storage); } else { index = 0; while (true) { key = this.proto.key.call(index); if (key === null) { break; } if (this.key.substr(0, this.prefix.length) === this.prefix) { this.proto.removeItem.call(this.storage, this.prefix + keys); } else { index++; } } } } if (typeof keys === 'string') { this.proto.removeItem.call(this.storage, this.prefix + keys); } for (i = 0, len = keys.length; i < len; i++) { key = keys[i]; this.proto.removeItem.call(this.storage, this.prefix + key); } return Promise.resolve(); }; return BrowserStorage; })(Storage); module.exports = BrowserStorage; },{"./storage":34,"bluebird":2}],29:[function(require,module,exports){ module.exports = function() { return { schemaVersion: 2, "-enableQuickSwitch": false, "-refreshOnProfileChange": true, "-startupProfileName": "", "-quickSwitchProfiles": [], "-revertProxyChanges": true, "-confirmDeletion": true, "-showInspectMenu": true, "-addConditionsToBottom": false, "-showExternalProfile": true, "-downloadInterval": 1440, "+proxy": { bypassList: [ { pattern: "127.0.0.1", conditionType: "BypassCondition" }, { pattern: "::1", conditionType: "BypassCondition" }, { pattern: "localhost", conditionType: "BypassCondition" } ], profileType: "FixedProfile", name: "proxy", color: "#99ccee", fallbackProxy: { port: 8080, scheme: "http", host: "proxy.example.com" } }, "+auto switch": { profileType: "SwitchProfile", rules: [ { condition: { pattern: "internal.example.com", conditionType: "HostWildcardCondition" }, profileName: "direct" }, { condition: { pattern: "*.example.com", conditionType: "HostWildcardCondition" }, profileName: "proxy" } ], name: "auto switch", color: "#99dd99", defaultProfileName: "direct" } }; }; },{}],30:[function(require,module,exports){ var ContentTypeRejectedError, HttpError, HttpNotFoundError, HttpServerError, NetworkError, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NetworkError = (function(superClass) { extend(NetworkError, superClass); function NetworkError(err) { NetworkError.__super__.constructor.apply(this, arguments); this.cause = err; this.name = 'NetworkError'; } return NetworkError; })(Error); HttpError = (function(superClass) { extend(HttpError, superClass); function HttpError() { var ref; HttpError.__super__.constructor.apply(this, arguments); this.statusCode = (ref = this.cause) != null ? ref.statusCode : void 0; this.name = 'HttpError'; } return HttpError; })(NetworkError); HttpNotFoundError = (function(superClass) { extend(HttpNotFoundError, superClass); function HttpNotFoundError() { HttpNotFoundError.__super__.constructor.apply(this, arguments); this.name = 'HttpNotFoundError'; } return HttpNotFoundError; })(HttpError); HttpServerError = (function(superClass) { extend(HttpServerError, superClass); function HttpServerError() { HttpServerError.__super__.constructor.apply(this, arguments); this.name = 'HttpServerError'; } return HttpServerError; })(HttpError); ContentTypeRejectedError = (function(superClass) { extend(ContentTypeRejectedError, superClass); function ContentTypeRejectedError() { ContentTypeRejectedError.__super__.constructor.apply(this, arguments); this.name = 'ContentTypeRejectedError'; } return ContentTypeRejectedError; })(Error); module.exports = { NetworkError: NetworkError, HttpError: HttpError, HttpNotFoundError: HttpNotFoundError, HttpServerError: HttpServerError, ContentTypeRejectedError: ContentTypeRejectedError }; },{}],31:[function(require,module,exports){ /* @module omega-target/log */ var Log, replacer; Log = require('./log'); replacer = function(key, value) { switch (key) { case "username": case "password": case "host": case "port": return ""; default: return value; } }; module.exports = Log = { /** * Pretty-print an object and return the result string. * @param {{}} obj The object to format * @returns {String} the formatted object in string */ str: function(obj) { if (typeof obj === 'object' && obj !== null) { if (obj.debugStr != null) { if (typeof obj.debugStr === 'function') { return obj.debugStr(); } else { return obj.debugStr; } } else if (obj instanceof Error) { return obj.stack || obj.message; } else { return JSON.stringify(obj, replacer, 4); } } else if (typeof obj === 'function') { if (obj.name) { return ""; } else { return obj.toString(); } } else { return '' + obj; } }, /** * Print something to the log. * @param {...{}} args The objects to log */ log: console.log.bind(console), /** * Print something to the error log. * @param {...{}} args The objects to log */ error: console.error.bind(console), /** * Log a function call with target and arguments * @param {string} name The name of the method * @param {Array} args The arguments to the method call */ func: function(name, args) { return this.log(name, '(', [].slice.call(args), ')'); }, /** * Log a method call with target and arguments * @param {string} name The name of the method * @param {{}} self The target of the method call * @param {Array} args The arguments to the method call */ method: function(name, self, args) { return this.log(this.str(self), '<<', name, [].slice.call(args)); } }; },{"./log":31}],32:[function(require,module,exports){ /* @module omega-target/options */ var Log, OmegaPac, Options, Promise, Storage, jsondiffpatch, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Promise = require('bluebird'); Log = require('./log'); Storage = require('./storage'); OmegaPac = require('omega-pac'); jsondiffpatch = require('jsondiffpatch'); Options = (function() { /** * The entire set of options including profiles and other settings. * @typedef OmegaOptions * @type {object} */ /** * All the options, in a map from key to value. * @type OmegaOptions */ var NoOptionsError, ProfileNotExistError; Options.prototype._options = null; Options.prototype._storage = null; Options.prototype._state = null; Options.prototype._currentProfileName = null; Options.prototype._revertToProfileName = null; Options.prototype._watchingProfiles = {}; Options.prototype._tempProfile = null; Options.prototype._tempProfileActive = false; Options.prototype.fallbackProfileName = 'system'; Options.prototype._isSystem = false; Options.prototype.debugStr = 'Options'; Options.prototype.ready = null; Options.ProfileNotExistError = ProfileNotExistError = (function(superClass) { extend(ProfileNotExistError, superClass); function ProfileNotExistError(profileName1) { this.profileName = profileName1; ProfileNotExistError.__super__.constructor.apply(this, arguments).constructor("Profile " + this.profileName + " does not exist!"); } return ProfileNotExistError; })(Error); Options.NoOptionsError = NoOptionsError = (function(superClass) { extend(NoOptionsError, superClass); function NoOptionsError() { NoOptionsError.__super__.constructor.apply(this, arguments); } return NoOptionsError; })(Error); /** * Transform options values (especially profiles) for syncing. * @param {{}} value The value to transform * @param {{}} key The key of the options * @returns {{}} The transformed value */ Options.transformValueForSync = function(value, key) { var k, profile, v; if (key[0] === '+') { if (OmegaPac.Profiles.updateUrl(value)) { profile = {}; for (k in value) { v = value[k]; if (k === 'lastUpdate' || k === 'ruleList' || k === 'pacScript') { continue; } profile[k] = v; } value = profile; } } return value; }; function Options(options, _storage, _state, log, sync, proxyImpl) { this._storage = _storage; this._state = _state; this.log = log; this.sync = sync; this.proxyImpl = proxyImpl; this._setOptions = bind(this._setOptions, this); this._options = {}; this._tempProfileRules = {}; this._tempProfileRulesByProfile = {}; if (this._storage == null) { this._storage = Storage(); } if (this._state == null) { this._state = Storage(); } if (this.log == null) { this.log = Log; } if (options == null) { this.init(); } else { this.ready = this._storage.remove().then((function(_this) { return function() { return _this._storage.set(options); }; })(this)).then((function(_this) { return function() { return _this.init(); }; })(this)); } } /** * Attempt to load options from local and remote storage. * @param {?{}} args Extra arguments * @param {number=3} args.retry Number of retries before giving up. * @returns {Promise} The loaded options */ Options.prototype.loadOptions = function(arg) { var loadRaw, ref, retry; retry = (arg != null ? arg : {}).retry; if (retry == null) { retry = 3; } if (typeof this._syncWatchStop === "function") { this._syncWatchStop(); } this._syncWatchStop = null; if (typeof this._watchStop === "function") { this._watchStop(); } this._watchStop = null; loadRaw = typeof options !== "undefined" && options !== null ? Promise.resolve(options) : !((ref = this.sync) != null ? ref.enabled : void 0) ? (this.sync == null ? this._state.set({ 'syncOptions': 'unsupported' }) : void 0, this._storage.get(null)) : (this._state.set({ 'syncOptions': 'sync' }), this._syncWatchStop = this.sync.watchAndPull(this._storage), this.sync.copyTo(this._storage)["catch"](Storage.StorageUnavailableError, (function(_this) { return function() { console.error('Warning: Sync storage is not available in this ' + 'browser! Disabling options sync.'); if (typeof _this._syncWatchStop === "function") { _this._syncWatchStop(); } _this._syncWatchStop = null; _this.sync = null; return _this._state.set({ 'syncOptions': 'unsupported' }); }; })(this)).then((function(_this) { return function() { return _this._storage.get(null); }; })(this))); return this.optionsLoaded = loadRaw.then((function(_this) { return function(options) { return _this.upgrade(options); }; })(this)).then((function(_this) { return function(arg1) { var changes, options; options = arg1[0], changes = arg1[1]; return _this._storage.apply({ changes: changes })["return"](options); }; })(this)).tap((function(_this) { return function(options) { _this._options = options; _this._watchStop = _this._watch(); return _this._state.get({ 'syncOptions': '' }).then(function(arg1) { var syncOptions; syncOptions = arg1.syncOptions; if (syncOptions) { return; } _this._state.set({ 'syncOptions': 'conflict' }); return _this.sync.storage.get('schemaVersion').then(function(arg2) { var schemaVersion; schemaVersion = arg2.schemaVersion; if (!schemaVersion) { return _this._state.set({ 'syncOptions': 'pristine' }); } }); }); }; })(this))["catch"]((function(_this) { return function(e) { var getFallbackOptions; if (!(retry > 0)) { return Promise.reject(e); } getFallbackOptions = Promise.resolve().then(function() { if (e instanceof NoOptionsError) { _this._state.get({ 'firstRun': 'new', 'web.switchGuide': 'showOnFirstUse' }).then(function(items) { return _this._state.set(items); }); if (_this.sync == null) { return null; } return _this._state.get({ 'syncOptions': '' }).then(function(arg1) { var syncOptions; syncOptions = arg1.syncOptions; if (syncOptions === 'conflict') { return; } return _this.sync.storage.get(null).then(function(options) { if (!options['schemaVersion']) { _this._state.set({ 'syncOptions': 'pristine' }); return null; } else { _this._state.set({ 'syncOptions': 'sync' }); _this.sync.enabled = true; _this.log.log('Options#loadOptions::fromSync', options); return options; } })["catch"](function() { return null; }); }); } else { _this.log.error(e.stack); _this._state.remove(['syncOptions']); return null; } }); return getFallbackOptions.then(function(options) { var prevEnabled; if (options == null) { options = _this.parseOptions(_this.getDefaultOptions()); } if (_this.sync != null) { prevEnabled = _this.sync.enabled; _this.sync.enabled = false; } return _this._storage.remove().then(function() { return _this._storage.set(options); }).then(function() { if (_this.sync != null) { _this.sync.enabled = prevEnabled; } return _this.loadOptions({ retry: retry - 1 }); }); }); }; })(this)); }; /** * Attempt to initialize (or reinitialize) options. * @returns {Promise} A promise that is fulfilled on ready. */ Options.prototype.init = function() { this.ready = this.loadOptions().then((function(_this) { return function() { if (_this._options['-startupProfileName']) { return _this.applyProfile(_this._options['-startupProfileName']); } else { return _this._state.get({ 'currentProfileName': _this.fallbackProfileName, 'isSystemProfile': false }).then(function(st) { if (st['isSystemProfile']) { return _this.applyProfile('system'); } else { return _this.applyProfile(st['currentProfileName'] || _this.fallbackProfileName); } }); } }; })(this))["catch"]((function(_this) { return function(err) { if (!err instanceof ProfileNotExistError) { _this.log.error(err); } return _this.applyProfile(_this.fallbackProfileName); }; })(this))["catch"]((function(_this) { return function(err) { return _this.log.error(err); }; })(this)).then((function(_this) { return function() { return _this.getAll(); }; })(this)); this.ready.then((function(_this) { return function() { var ref; if ((ref = _this.sync) != null ? ref.enabled : void 0) { _this.sync.requestPush(_this._options); } _this._state.get({ 'firstRun': '' }).then(function(arg) { var firstRun; firstRun = arg.firstRun; if (firstRun) { return _this.onFirstRun(firstRun); } }); if (_this._options['-downloadInterval'] > 0) { return _this.updateProfile(); } }; })(this)); return this.ready; }; Options.prototype.toString = function() { return ""; }; /** * Return a localized, human-readable description of the given profile. * In base class, this method is not implemented and will always return null. * @param {?{}} profile The profile to print * @returns {string} Description of the profile with details */ Options.prototype.printProfile = function(profile) { return null; }; /** * Upgrade options from previous versions. * For now, this method only supports schemaVersion 1 and 2. If so, it upgrades * the options to version 2 (the latest version). Otherwise it rejects. * It is recommended for the derived classes to call super() two times in the * beginning and in the end of the implementation to check the schemaVersion * and to apply future upgrades, respectively. * Example: super(options).catch -> super(doCustomUpgrades(options), changes) * @param {?OmegaOptions} options The legacy options to upgrade * @param {{}={}} changes Previous pending changes to be applied. Default to * an empty dictionary. Please provide this argument when calling super(). * @returns {Promise<[OmegaOptions, {}]>} The new options and the changes. */ Options.prototype.upgrade = function(options, changes) { var autoDetectUsed, version; if (changes == null) { changes = {}; } version = options != null ? options['schemaVersion'] : void 0; if (version === 1) { autoDetectUsed = false; OmegaPac.Profiles.each(options, function(key, profile) { var refs; if (!autoDetectUsed) { refs = OmegaPac.Profiles.directReferenceSet(profile); if (refs['+auto_detect']) { return autoDetectUsed = true; } } }); if (autoDetectUsed) { options['+auto_detect'] = OmegaPac.Profiles.create({ name: 'auto_detect', profileType: 'PacProfile', pacUrl: 'http://wpad/wpad.dat', color: '#00cccc' }); } version = changes['schemaVersion'] = options['schemaVersion'] = 2; } if (version === 2) { return Promise.resolve([options, changes]); } else { return Promise.reject(new Error("Invalid schemaVerion " + version + "!")); } }; /** * Parse options in various formats (including JSON & base64). * @param {OmegaOptions|string} options The options to parse * @returns {Promise} The parsed options. */ Options.prototype.parseOptions = function(options) { var Buffer, _; if (typeof options === 'string') { if (options[0] !== '{') { try { Buffer = require('buffer').Buffer; options = new Buffer(options, 'base64').toString('utf8'); } catch (error) { _ = error; options = null; } } options = (function() { try { return JSON.parse(options); } catch (error) {} })(); } if (!options) { throw new Error('Invalid options!'); } return options; }; /** * Reset the options to the given options or initial options. * @param {?OmegaOptions} options The options to set. Defaults to initial. * @returns {Promise} The options just applied */ Options.prototype.reset = function(options) { this.log.method('Options#reset', this, arguments); if (options == null) { options = this.getDefaultOptions(); } return this.upgrade(this.parseOptions(options)).then((function(_this) { return function(arg) { var opt; opt = arg[0]; if (_this.sync != null) { _this.sync.enabled = false; } _this._state.remove(['syncOptions']); return _this._storage.remove().then(function() { return _this._storage.set(opt); }).then(function() { return _this.init(); }); }; })(this)); }; /** * Called on the first initialization of options. * @param {reason} reason The value of 'firstRun' in state. */ Options.prototype.onFirstRun = function(reason) { return null; }; /** * Return the default options used initially and on resets. * @returns {?OmegaOptions} The default options. */ Options.prototype.getDefaultOptions = function() { return require('./default_options')(); }; /** * Return all options. * @returns {?OmegaOptions} The options. */ Options.prototype.getAll = function() { return this._options; }; /** * Get profile by name. * @returns {?{}} The profile, or undefined if no such profile. */ Options.prototype.profile = function(name) { return OmegaPac.Profiles.byName(name, this._options); }; /** * Apply the patch to the current options. * @param {jsondiffpatch} patch The patch to apply * @returns {Promise} The updated options */ Options.prototype.patch = function(patch) { var changes, delta, key; if (!patch) { return; } this.log.method('Options#patch', this, arguments); this._options = jsondiffpatch.patch(this._options, patch); changes = {}; for (key in patch) { if (!hasProp.call(patch, key)) continue; delta = patch[key]; if (delta.length === 3 && delta[1] === 0 && delta[2] === 0) { changes[key] = void 0; } else { changes[key] = this._options[key]; } } return this._setOptions(changes); }; Options.prototype._setOptions = function(changes, args) { var checkRev, currentProfileAffected, j, key, len, profilesChanged, ref, ref1, ref2, ref3, removed, result, value; removed = []; checkRev = (ref = args != null ? args.checkRevision : void 0) != null ? ref : false; profilesChanged = false; currentProfileAffected = false; for (key in changes) { if (!hasProp.call(changes, key)) continue; value = changes[key]; if (typeof value === 'undefined') { delete this._options[key]; removed.push(key); if (key[0] === '+') { profilesChanged = true; if (key === '+' + this._currentProfileName) { currentProfileAffected = 'removed'; } } } else { if (key[0] === '+') { if (checkRev && this._options[key]) { result = OmegaPac.Revision.compare(this._options[key].revision, value.revision); if (result >= 0) { continue; } } profilesChanged = true; } this._options[key] = value; } if (!currentProfileAffected && this._watchingProfiles[key]) { currentProfileAffected = 'changed'; } } switch (currentProfileAffected) { case 'removed': this.applyProfile(this.fallbackProfileName); break; case 'changed': this.applyProfile(this._currentProfileName, { update: false }); break; default: if (profilesChanged) { this._setAvailableProfiles(); } } if ((ref1 = args != null ? args.persist : void 0) != null ? ref1 : true) { if ((ref2 = this.sync) != null ? ref2.enabled : void 0) { if ((ref3 = this.sync) != null) { ref3.requestPush(changes); } } for (j = 0, len = removed.length; j < len; j++) { key = removed[j]; delete changes[key]; } return this._storage.set(changes).then((function(_this) { return function() { _this._storage.remove(removed); return _this._options; }; })(this)); } }; Options.prototype._watch = function() { var handler; handler = (function(_this) { return function(changes) { var monitorWebRequests, quickSwitchProfiles, refresh, showExternal, showMenu; if (changes) { _this._setOptions(changes, { checkRevision: true, persist: false }); } else { changes = _this._options; } refresh = changes['-refreshOnProfileChange']; if (refresh != null) { _this._state.set({ 'refreshOnProfileChange': refresh }); } if (Object.prototype.hasOwnProperty.call(changes, '-showExternalProfile')) { showExternal = changes['-showExternalProfile']; if (showExternal == null) { showExternal = true; _this._setOptions({ '-showExternalProfile': true }, { persist: true }); } _this._state.set({ 'showExternalProfile': showExternal }); } quickSwitchProfiles = changes['-quickSwitchProfiles']; quickSwitchProfiles = _this._cleanUpQuickSwitchProfiles(quickSwitchProfiles); if ((changes['-enableQuickSwitch'] != null) || (quickSwitchProfiles != null)) { _this.reloadQuickSwitch(); } if (changes['-downloadInterval'] != null) { _this.schedule('updateProfile', _this._options['-downloadInterval'], function() { return _this.updateProfile(); }); } if ((changes['-showInspectMenu'] != null) || changes === _this._options) { showMenu = _this._options['-showInspectMenu']; if (showMenu == null) { showMenu = true; _this._setOptions({ '-showInspectMenu': true }, { persist: true }); } _this.setInspect({ showMenu: showMenu }); } if ((changes['-monitorWebRequests'] != null) || changes === _this._options) { monitorWebRequests = _this._options['-monitorWebRequests']; if (monitorWebRequests == null) { monitorWebRequests = true; _this._setOptions({ '-monitorWebRequests': true }, { persist: true }); } return _this.setMonitorWebRequests(monitorWebRequests); } }; })(this); handler(); return this._storage.watch(null, handler); }; Options.prototype._cleanUpQuickSwitchProfiles = function(quickSwitchProfiles) { var seenQuickSwitchProfile, validQuickSwitchProfiles; if (quickSwitchProfiles == null) { return; } seenQuickSwitchProfile = {}; validQuickSwitchProfiles = quickSwitchProfiles.filter((function(_this) { return function(name) { var key; if (!name) { return false; } key = OmegaPac.Profiles.nameAsKey(name); if (seenQuickSwitchProfile[key]) { return false; } if (!OmegaPac.Profiles.byName(name, _this._options)) { return false; } seenQuickSwitchProfile[key] = true; return true; }; })(this)); if (validQuickSwitchProfiles.length !== quickSwitchProfiles.length) { this._setOptions({ '-quickSwitchProfiles': validQuickSwitchProfiles }, { persist: true }); } return validQuickSwitchProfiles; }; /** * Reload the quick switch according to settings. * @returns {Promise} A promise which is fulfilled when the quick switch is set */ Options.prototype.reloadQuickSwitch = function() { var profiles; profiles = this._options['-quickSwitchProfiles']; if (profiles.length < 2) { profiles = null; } if (this._options['-enableQuickSwitch']) { return this.setQuickSwitch(profiles, !!profiles); } else { return this.setQuickSwitch(null, !!profiles); } }; /** * Apply the settings related to element proxy inspection. * In base class, this method is not implemented and will not do anything. * @param {{}} settings * @param {boolean} settings.showMenu Whether to show the menu or not * @returns {Promise} A promise which is fulfilled when the settings apply */ Options.prototype.setInspect = function() { return Promise.resolve(); }; /** * Apply the settings related to web request monitoring. * In base class, this method is not implemented and will not do anything. * @param {boolean} enabled Whether network shall be monitored or not * @returns {Promise} A promise which is fulfilled when the settings apply */ Options.prototype.setMonitorWebRequests = function() { return Promise.resolve(); }; /** * @callback watchCallback * @param {Object.} changes A map from keys to values. */ /** * Watch for any changes to the options * @param {watchCallback} callback Called everytime the value of a key changes * @returns {function} Calling the returned function will stop watching. */ Options.prototype.watch = function(callback) { return this._storage.watch(null, callback); }; Options.prototype._profileNotFound = function(name) { this.log.error("Profile " + name + " not found! Things may go very, very wrong."); return OmegaPac.Profiles.create({ name: name, profileType: 'VirtualProfile', defaultProfileName: 'direct' }); }; /** * Get PAC script for profile. * @param {?string|Object} profile The name of the profile, or the profile. * @param {bool=false} compress Compress the script if true. * @returns {string} The compiled */ Options.prototype.pacForProfile = function(profile, compress) { var ast; if (compress == null) { compress = false; } ast = OmegaPac.PacGenerator.script(this._options, profile, { profileNotFound: this._profileNotFound.bind(this) }); if (compress) { ast = OmegaPac.PacGenerator.compress(ast); } return Promise.resolve(OmegaPac.PacGenerator.ascii(ast.print_to_string())); }; Options.prototype._setAvailableProfiles = function() { var allReferenceSet, currentIncludable, profile, profiles, results; profile = this._currentProfileName ? this.currentProfile() : null; profiles = {}; currentIncludable = profile && OmegaPac.Profiles.isIncludable(profile); allReferenceSet = null; if (!profile || !OmegaPac.Profiles.isInclusive(profile)) { results = []; } OmegaPac.Profiles.each(this._options, (function(_this) { return function(key, p) { profiles[key] = { name: p.name, profileType: p.profileType, color: p.color, desc: _this.printProfile(p), builtin: p.builtin ? true : void 0 }; if (p.profileType === 'VirtualProfile') { profiles[key].defaultProfileName = p.defaultProfileName; if (allReferenceSet == null) { allReferenceSet = profile ? OmegaPac.Profiles.allReferenceSet(profile, _this._options, { profileNotFound: _this._profileNotFound.bind(_this) }) : {}; } if (allReferenceSet[key]) { profiles[key].validResultProfiles = OmegaPac.Profiles.validResultProfilesFor(p, _this._options).map(function(result) { return result.name; }); } } if (currentIncludable && OmegaPac.Profiles.isIncludable(p)) { return results != null ? results.push(p.name) : void 0; } }; })(this)); if (profile && OmegaPac.Profiles.isInclusive(profile)) { results = OmegaPac.Profiles.validResultProfilesFor(profile, this._options); results = results.map(function(profile) { return profile.name; }); } return this._state.set({ 'availableProfiles': profiles, 'validResultProfiles': results }); }; /** * Apply the profile by name. * @param {?string} name The name of the profile, or null for default. * @param {?{}} options Some options * @param {bool=true} options.proxy Set proxy for the applied profile if true * @param {bool=true} options.update Try to update this profile and referenced * profiles after the proxy is set. * @param {bool=false} options.system Whether options is in system mode. * @param {{}=undefined} options.reason will be passed to currentProfileChanged * @returns {Promise} A promise which is fulfilled when the profile is applied. */ Options.prototype.applyProfile = function(name, options) { var applyProxy, j, key, l, len, len1, list, profile, ref, removedKeys, rule; this.log.method('Options#applyProfile', this, arguments); profile = OmegaPac.Profiles.byName(name, this._options); if (!profile) { return Promise.reject(new ProfileNotExistError(name)); } this._currentProfileName = profile.name; this._isSystem = (options != null ? options.system : void 0) || (profile.profileType === 'SystemProfile'); this._watchingProfiles = OmegaPac.Profiles.allReferenceSet(profile, this._options, { profileNotFound: this._profileNotFound.bind(this) }); this._state.set({ 'currentProfileName': this._currentProfileName, 'isSystemProfile': this._isSystem, 'currentProfileCanAddRule': (profile.rules != null) && profile.profileType !== 'VirtualProfile' }); this._setAvailableProfiles(); this.currentProfileChanged(options != null ? options.reason : void 0); if ((options != null) && options.proxy === false) { return Promise.resolve(); } this._tempProfileActive = false; if ((this._tempProfile != null) && OmegaPac.Profiles.isIncludable(profile)) { this._tempProfileActive = true; if (this._tempProfile.defaultProfileName !== profile.name) { this._tempProfile.defaultProfileName = profile.name; this._tempProfile.color = profile.color; OmegaPac.Profiles.updateRevision(this._tempProfile); } removedKeys = []; ref = this._tempProfileRulesByProfile; for (key in ref) { if (!hasProp.call(ref, key)) continue; list = ref[key]; if (!OmegaPac.Profiles.byKey(key, this._options)) { removedKeys.push(key); for (j = 0, len = list.length; j < len; j++) { rule = list[j]; rule.profileName = null; this._tempProfile.rules.splice(this._tempProfile.rules.indexOf(rule), 1); } } } if (removedKeys.length > 0) { for (l = 0, len1 = removedKeys.length; l < len1; l++) { key = removedKeys[l]; delete this._tempProfileRulesByProfile[key]; } OmegaPac.Profiles.updateRevision(this._tempProfile); } this._watchingProfiles = OmegaPac.Profiles.allReferenceSet(this._tempProfile, this._options, { profileNotFound: this._profileNotFound.bind(this) }); applyProxy = this.proxyImpl.applyProfile(this._tempProfile, profile, this._options); } else { applyProxy = this.proxyImpl.applyProfile(profile, profile, this._options); } if ((options != null) && options.update === false) { return applyProxy; } applyProxy.then((function(_this) { return function() { var ref1, updateProfiles; if (!(_this._options['-downloadInterval'] > 0)) { return; } if (_this._currentProfileName !== profile.name) { return; } updateProfiles = []; ref1 = _this._watchingProfiles; for (key in ref1) { name = ref1[key]; updateProfiles.push(name); } if (updateProfiles.length > 0) { return _this.updateProfile(updateProfiles); } }; })(this)); return applyProxy; }; /** * Get the current applied profile. * @returns {{}} The current profile */ Options.prototype.currentProfile = function() { if (this._currentProfileName) { return OmegaPac.Profiles.byName(this._currentProfileName, this._options); } else { return this._externalProfile; } }; /** * Return true if in system mode. * @returns {boolean} True if system mode is activated */ Options.prototype.isSystem = function() { return this._isSystem; }; /** * Called when current profile has changed. * In base class, this method is not implemented and will not do anything. */ Options.prototype.currentProfileChanged = function() { return null; }; /** * Set or disable the quick switch profiles. * In base class, this method is not implemented and will not do anything. * @param {string[]|null} quickSwitch The profile names, or null to disable * @param {boolean} canEnable Whether user can enable quick switch or not. * @returns {Promise} A promise which is fulfilled when the quick switch is set */ Options.prototype.setQuickSwitch = function(quickSwitch, canEnable) { return Promise.resolve(); }; /** * Schedule a task that runs every periodInMinutes. * In base class, this method is not implemented and will not do anything. * @param {string} name The name of the schedule. If there is a previous * schedule with the same name, it will be replaced by the new one. * @param {number} periodInMinutes The interval of the schedule * @param {function} callback The callback to call when the task runs * @returns {Promise} A promise which is fulfilled when the schedule is set */ Options.prototype.schedule = function(name, periodInMinutes, callback) { return Promise.resolve(); }; /** * Return true if the match result of current profile does not change with URLs * @returns {bool} Whether @match always return the same result for requests */ Options.prototype.isCurrentProfileStatic = function() { var currentProfile; if (!this._currentProfileName) { return true; } if (this._tempProfileActive) { return false; } currentProfile = this.currentProfile(); if (OmegaPac.Profiles.isInclusive(currentProfile)) { return false; } return true; }; /** * Update the profile by name. * @param {(string|string[]|null)} name The name of the profiles, * or null for all. * @param {?bool} opt_bypass_cache Do not read from the cache if true * @returns {Promise>} A map from keys to updated * profiles or errors. * A value is an error if `value instanceof Error`. Otherwise the value is an * updated profile. */ Options.prototype.updateProfile = function(name, opt_bypass_cache) { var results; this.log.method('Options#updateProfile', this, arguments); results = {}; OmegaPac.Profiles.each(this._options, (function(_this) { return function(key, profile) { var fetchResult, type_hints, url; if (name != null) { if (Array.isArray(name)) { if (!(name.indexOf(profile.name) >= 0)) { return; } } else { if (profile.name !== name) { return; } } } url = OmegaPac.Profiles.updateUrl(profile); if (url) { type_hints = OmegaPac.Profiles.updateContentTypeHints(profile); fetchResult = _this.fetchUrl(url, opt_bypass_cache, type_hints); return results[key] = fetchResult.then(function(data) { var changes; if (!data) { return profile; } profile = OmegaPac.Profiles.byKey(key, _this._options); profile.lastUpdate = new Date().toISOString(); if (OmegaPac.Profiles.update(profile, data)) { OmegaPac.Profiles.dropCache(profile); changes = {}; changes[key] = profile; return _this._setOptions(changes)["return"](profile); } else { return profile; } })["catch"](function(reason) { if (reason instanceof Error) { return reason; } else { return new Error(reason); } }); } }; })(this)); return Promise.props(results); }; /** * Make an HTTP GET request to fetch the content of the url. * In base class, this method is not implemented and will always reject. * @param {string} url The name of the profiles, * @param {?bool} opt_bypass_cache Do not read from the cache if true * @param {?string} opt_type_hints MIME type hints for downloaded content. * @returns {Promise} The text content fetched from the url */ Options.prototype.fetchUrl = function(url, opt_bypass_cache, opt_type_hints) { return Promise.reject(new Error('not implemented')); }; Options.prototype._replaceRefChanges = function(fromName, toName, changes) { var i, j, quickSwitch, ref; if (changes == null) { changes = {}; } OmegaPac.Profiles.each(this._options, function(key, p) { if (p.name === fromName || p.name === toName) { return; } if (OmegaPac.Profiles.replaceRef(p, fromName, toName)) { OmegaPac.Profiles.updateRevision(p); return changes[OmegaPac.Profiles.nameAsKey(p)] = p; } }); if (this._options['-startupProfileName'] === fromName) { changes['-startupProfileName'] = toName; } quickSwitch = this._options['-quickSwitchProfiles']; if (quickSwitch.indexOf(toName) < 0) { for (i = j = 0, ref = quickSwitch.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) { if (quickSwitch[i] === fromName) { quickSwitch[i] = toName; changes['-quickSwitchProfiles'] = quickSwitch; } } } return changes; }; /** * Replace all references of profile fromName to toName. * @param {String} fromName The original profile name * @param {String} toname The target profile name * @returns {Promise} The updated options */ Options.prototype.replaceRef = function(fromName, toName) { var changes, fromKey, key, profile, value; this.log.method('Options#replaceRef', this, arguments); profile = OmegaPac.Profiles.byName(fromName, this._options); if (!profile) { return Promise.reject(new ProfileNotExistError(fromName)); } changes = this._replaceRefChanges(fromName, toName); for (key in changes) { if (!hasProp.call(changes, key)) continue; value = changes[key]; this._options[key] = value; } fromKey = OmegaPac.Profiles.nameAsKey(fromName); if (this._watchingProfiles[fromKey]) { if (this._currentProfileName === fromName) { this._currentProfileName = toName; } this.applyProfile(this._currentProfileName); } return this._setOptions(changes); }; /** * Rename a profile and update references and options * @param {String} fromName The original profile name * @param {String} toname The target profile name * @returns {Promise} The updated options */ Options.prototype.renameProfile = function(fromName, toName) { var changes, fromKey, key, profile, value; this.log.method('Options#renameProfile', this, arguments); if (OmegaPac.Profiles.byName(toName, this._options)) { return Promise.reject(new Error("Target name " + name + " already taken!")); } profile = OmegaPac.Profiles.byName(fromName, this._options); if (!profile) { return Promise.reject(new ProfileNotExistError(fromName)); } profile.name = toName; changes = {}; changes[OmegaPac.Profiles.nameAsKey(profile)] = profile; this._replaceRefChanges(fromName, toName, changes); for (key in changes) { if (!hasProp.call(changes, key)) continue; value = changes[key]; this._options[key] = value; } fromKey = OmegaPac.Profiles.nameAsKey(fromName); changes[fromKey] = void 0; delete this._options[fromKey]; if (this._watchingProfiles[fromKey]) { if (this._currentProfileName === fromName) { this._currentProfileName = toName; } this.applyProfile(this._currentProfileName); } return this._setOptions(changes); }; /** * Add a temp rule. * @param {String} domain The domain for the temp rule. * @param {String} profileName The profile to apply for the domain. * @returns {Promise} A promise which is fulfilled when the rule is applied. */ Options.prototype.addTempRule = function(domain, profileName) { var changed, currentProfile, key, list, profile, rule, rulesByProfile; this.log.method('Options#addTempRule', this, arguments); if (!this._currentProfileName) { return Promise.resolve(); } profile = OmegaPac.Profiles.byName(profileName, this._options); if (!profile) { return Promise.reject(new ProfileNotExistError(profileName)); } if (this._tempProfile == null) { this._tempProfile = OmegaPac.Profiles.create('', 'SwitchProfile'); currentProfile = this.currentProfile(); this._tempProfile.color = currentProfile.color; this._tempProfile.defaultProfileName = currentProfile.name; } changed = false; rule = this._tempProfileRules[domain]; if (rule && rule.profileName) { if (rule.profileName !== profileName) { key = OmegaPac.Profiles.nameAsKey(rule.profileName); list = this._tempProfileRulesByProfile[key]; list.splice(list.indexOf(rule), 1); rule.profileName = profileName; changed = true; } } else { rule = { condition: { conditionType: 'HostWildcardCondition', pattern: '*.' + domain }, profileName: profileName, isTempRule: true }; this._tempProfile.rules.push(rule); this._tempProfileRules[domain] = rule; changed = true; } key = OmegaPac.Profiles.nameAsKey(profileName); rulesByProfile = this._tempProfileRulesByProfile[key]; if (rulesByProfile == null) { rulesByProfile = this._tempProfileRulesByProfile[key] = []; } rulesByProfile.push(rule); if (changed) { OmegaPac.Profiles.updateRevision(this._tempProfile); return this.applyProfile(this._currentProfileName); } else { return Promise.resolve(); } }; /** * Find a temp rule by domain. * @param {String} domain The domain of the temp rule. * @returns {Promise} The profile name for the domain, or null if such * rule does not exist. */ Options.prototype.queryTempRule = function(domain) { var rule; rule = this._tempProfileRules[domain]; if (rule) { if (rule.profileName) { return rule.profileName; } else { delete this._tempProfileRules[domain]; } } return null; }; /** * Add a condition to the current active switch profile. * @param {Object.} cond The condition to add * @param {string>} profileName The name of the result profile of the rule. * @returns {Promise} A promise which is fulfilled when the condition is saved. */ Options.prototype.addCondition = function(condition, profileName) { var changes, cond, i, j, l, len, profile, ref, tag, target; this.log.method('Options#addCondition', this, arguments); if (!this._currentProfileName) { return Promise.resolve(); } profile = OmegaPac.Profiles.byName(this._currentProfileName, this._options); if ((profile != null ? profile.rules : void 0) == null) { return Promise.reject(new Error("Cannot add condition to Profile " + this.profile.name + " (" + profile.type + ")")); } target = OmegaPac.Profiles.byName(profileName, this._options); if (target == null) { return Promise.reject(new ProfileNotExistError(profileName)); } if (!Array.isArray(condition)) { condition = [condition]; } for (j = 0, len = condition.length; j < len; j++) { cond = condition[j]; tag = OmegaPac.Conditions.tag(cond); for (i = l = 0, ref = profile.rules.length; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) { if (OmegaPac.Conditions.tag(profile.rules[i].condition) === tag) { profile.rules.splice(i, 1); break; } } if (this._options['-addConditionsToBottom']) { profile.rules.push({ condition: cond, profileName: profileName }); } else { profile.rules.unshift({ condition: cond, profileName: profileName }); } } OmegaPac.Profiles.updateRevision(profile); changes = {}; changes[OmegaPac.Profiles.nameAsKey(profile)] = profile; return this._setOptions(changes); }; /** * Set the defaultProfileName of the profile. * @param {string>} profileName The name of the profile to modify. * @param {string>} defaultProfileName The defaultProfileName to set. * @returns {Promise} A promise which is fulfilled when the profile is saved. */ Options.prototype.setDefaultProfile = function(profileName, defaultProfileName) { var changes, profile, target; this.log.method('Options#setDefaultProfile', this, arguments); profile = OmegaPac.Profiles.byName(profileName, this._options); if (profile == null) { return Promise.reject(new ProfileNotExistError(profileName)); } else if (profile.defaultProfileName == null) { return Promise.reject(new Error(("Profile " + this.profile.name + " ") + "(@{profile.type}) does not have defaultProfileName!")); } target = OmegaPac.Profiles.byName(defaultProfileName, this._options); if (target == null) { return Promise.reject(new ProfileNotExistError(defaultProfileName)); } profile.defaultProfileName = defaultProfileName; OmegaPac.Profiles.updateRevision(profile); changes = {}; changes[OmegaPac.Profiles.nameAsKey(profile)] = profile; return this._setOptions(changes); }; /** * Add a profile to the options * @param {{}} profile The profile to create * @returns {Promise<{}>} The saved profile */ Options.prototype.addProfile = function(profile) { var changes; this.log.method('Options#addProfile', this, arguments); if (OmegaPac.Profiles.byName(profile.name, this._options)) { return Promise.reject(new Error("Target name " + profile.name + " already taken!")); } else { changes = {}; changes[OmegaPac.Profiles.nameAsKey(profile)] = profile; return this._setOptions(changes); } }; /** * Get the matching results of a request * @param {{}} request The request to test * @returns {Promise<{profile: {}, results: {}[]}>} The last matched profile * and the matching details */ Options.prototype.matchProfile = function(request) { var lastProfile, next, profile, result, results; if (!this._currentProfileName) { return Promise.resolve({ profile: this._externalProfile, results: [] }); } results = []; profile = this._tempProfileActive ? this._tempProfile : OmegaPac.Profiles.byName(this._currentProfileName, this._options); while (profile) { lastProfile = profile; result = OmegaPac.Profiles.match(profile, request); if (result == null) { break; } results.push(result); if (Array.isArray(result)) { next = result[0]; } else if (result.profileName) { next = OmegaPac.Profiles.nameAsKey(result.profileName); } else { break; } profile = OmegaPac.Profiles.byKey(next, this._options); } return Promise.resolve({ profile: lastProfile, results: results }); }; /** * Notify Options that the proxy settings are set externally. * @param {{}} profile The external profile * @param {?{}} args Extra arguments * @param {boolean=false} args.noRevert If true, do not revert changes. * @param {boolean=false} args.internal If true, treat the profile change as * caused by the options itself instead of external reasons. * @returns {Promise} A promise which is fulfilled when the profile is set */ Options.prototype.setExternalProfile = function(profile, args) { var p; if (this._options['-revertProxyChanges'] && !this._isSystem) { if (profile.name !== this._currentProfileName && this._currentProfileName) { if (!(args != null ? args.noRevert : void 0)) { this.applyProfile(this._revertToProfileName); this._revertToProfileName = null; return; } else { if (this._revertToProfileName == null) { this._revertToProfileName = this._currentProfileName; } } } } p = OmegaPac.Profiles.byName(profile.name, this._options); if (p) { if (args != null ? args.internal : void 0) { return this.applyProfile(p.name, { proxy: false }); } else { return this.applyProfile(p.name, { proxy: false, system: this._isSystem, reason: 'external' }); } } else { this._currentProfileName = null; this._externalProfile = profile; if (profile.color == null) { profile.color = '#49afcd'; } this._state.set({ 'currentProfileName': '', 'externalProfile': profile, 'validResultProfiles': [], 'currentProfileCanAddRule': false }); this.currentProfileChanged('external'); } }; /** * Switch options syncing on and off. * @param {boolean} enabled Whether to enable syncing * @param {?{}} args Extra arguments * @param {boolean=false} args.force If true, overwrite options when conflict * @returns {Promise} A promise which is fulfilled when the syncing is switched */ Options.prototype.setOptionsSync = function(enabled, args) { this.log.method('Options#setOptionsSync', this, arguments); if (this.sync == null) { return Promise.reject(new Error('Options syncing is unsupported.')); } return this._state.get({ 'syncOptions': '' }).then((function(_this) { return function(arg) { var syncOptions; syncOptions = arg.syncOptions; if (!enabled) { if (syncOptions === 'sync') { _this._state.set({ 'syncOptions': 'conflict' }); } _this.sync.enabled = false; if (typeof _this._syncWatchStop === "function") { _this._syncWatchStop(); } _this._syncWatchStop = null; return; } if (syncOptions === 'conflict') { if (!(args != null ? args.force : void 0)) { return Promise.reject(new Error('Syncing not enabled due to conflict. Retry with force to overwrite local options and enable syncing.')); } } if (syncOptions === 'sync') { return; } return _this._state.set({ 'syncOptions': 'sync' }).then(function() { if (syncOptions === 'conflict') { _this.sync.enabled = false; return _this._storage.remove().then(function() { _this.sync.enabled = true; return _this.init(); }); } else { _this.sync.enabled = true; if (typeof _this._syncWatchStop === "function") { _this._syncWatchStop(); } _this.sync.requestPush(_this._options); _this._syncWatchStop = _this.sync.watchAndPull(_this._storage); } }); }; })(this)); }; /** * Clear the sync storage, resetting syncing state to pristine. * @returns {Promise} A promise which is fulfilled when the syncing is reset. */ Options.prototype.resetOptionsSync = function() { this.log.method('Options#resetOptionsSync', this, arguments); if (this.sync == null) { return Promise.reject(new Error('Options syncing is unsupported.')); } this.sync.enabled = false; if (typeof this._syncWatchStop === "function") { this._syncWatchStop(); } this._syncWatchStop = null; this._state.set({ 'syncOptions': 'conflict' }); return this.sync.storage.remove().then((function(_this) { return function() { return _this._state.set({ 'syncOptions': 'pristine' }); }; })(this)); }; return Options; })(); module.exports = Options; },{"./default_options":29,"./log":31,"./storage":34,"bluebird":2,"buffer":3,"jsondiffpatch":19,"omega-pac":27}],33:[function(require,module,exports){ /* @module omega-target/options_sync */ var Log, OptionsSync, Promise, Revision, Storage, TokenBucket, jsondiffpatch, hasProp = {}.hasOwnProperty; Promise = require('bluebird'); Storage = require('./storage'); Log = require('./log'); Revision = require('omega-pac').Revision; jsondiffpatch = require('jsondiffpatch'); TokenBucket = require('limiter').TokenBucket; OptionsSync = (function() { OptionsSync.TokenBucket = TokenBucket; OptionsSync.prototype._timeout = null; OptionsSync.prototype._bucket = null; OptionsSync.prototype._waiting = false; /** * The debounce timeout (ms) for requestPush scheduling. See requestPush. * @type number */ OptionsSync.prototype.debounce = 1000; /** * The throttling timeout (ms) for watchAndPull. See watchAndPull. * @type number */ OptionsSync.prototype.pullThrottle = 1000; /** * The remote storage of syncing. * @type Storage */ OptionsSync.prototype.storage = null; function OptionsSync(storage, _bucket) { var base1; this.storage = storage; this._bucket = _bucket; this._pending = {}; if (this._bucket == null) { this._bucket = new TokenBucket(10, 10, 'minute', null); } if ((base1 = this._bucket).clear == null) { base1.clear = (function(_this) { return function() { return _this._bucket.tryRemoveTokens(_this._bucket.content); }; })(this); } } /** * Transform storage values for syncing. The default implementation applies no * transformation, but the behavior can be altered by assigning to this field. * Note: Transformation is applied before merging. * @param {{}} value The value to transform * @param {{}} key The key of the item * @returns {{}} The transformed value */ OptionsSync.prototype.transformValue = function(v) { return v; }; /** * Merge newVal and oldVal of a given key. The default implementation choose * between newVal and oldVal based on the following rules: * 1. Choose oldVal if syncOptions is 'disabled' in either oldVal or newVal. * 2. Choose oldVal if it has a revision newer than or equal to that of newVal. * 3. Choose oldVal if it deeply equals newVal. * 4. Otherwise, choose newVal. * * @param {string} key The key of the item * @param {} newVal The new value * @param {} oldVal The old value * @returns {} The merged result */ OptionsSync.prototype.merge = (function() { var diff; diff = jsondiffpatch.create({ objectHash: function(obj) { return JSON.stringify(obj); }, textDiff: { minLength: 1 / 0 } }); return function(key, newVal, oldVal) { var result; if (newVal === oldVal) { return oldVal; } if ((oldVal != null ? oldVal.syncOptions : void 0) === 'disabled' || (newVal != null ? newVal.syncOptions : void 0) === 'disabled') { return oldVal; } if (((oldVal != null ? oldVal.revision : void 0) != null) && ((newVal != null ? newVal.revision : void 0) != null)) { result = Revision.compare(oldVal.revision, newVal.revision); if (result >= 0) { return oldVal; } } if (diff.diff(oldVal, newVal) == null) { return oldVal; } return newVal; }; })(); /** * Whether syncing is enabled or not. See requestPush for the effect. * @type boolean */ OptionsSync.prototype.enabled = true; /** * Request pushing the changes to remote storage. The changes are cached first, * and then the actual write operations are scheduled if enabled is true. * The actual operation is delayed and debounced, combining continuous writes * in a short period into a single write operation. * @param {Object.} changes A map from keys to values. */ OptionsSync.prototype.requestPush = function(changes) { var key, value; if (this._timeout != null) { clearTimeout(this._timeout); } for (key in changes) { if (!hasProp.call(changes, key)) continue; value = changes[key]; if (typeof value !== 'undefined') { value = this.transformValue(value, key); if (typeof value === 'undefined') { continue; } } this._pending[key] = value; } if (!this.enabled) { return; } return this._timeout = setTimeout(this._doPush.bind(this), this.debounce); }; /** * Returning the pending changes not written to the remote storage. * @returns {Object.} The pending changes. */ OptionsSync.prototype.pendingChanges = function() { return this._pending; }; OptionsSync.prototype._doPush = function() { this._timeout = null; if (this._waiting) { return; } this._waiting = true; return this._bucket.removeTokens(1, (function(_this) { return function() { return _this.storage.get(null).then(function(base) { var changes; changes = _this._pending; _this._pending = {}; _this._waiting = false; return Storage.operationsForChanges(changes, { base: base, merge: _this.merge }); }).then(function(arg) { var doSet, remove, set; set = arg.set, remove = arg.remove; doSet = Object.keys(set).length === 0 ? Promise.resolve(0) : (Log.log('OptionsSync::set', set), _this.storage.set(set)["return"](1)); return doSet.then(function(cost) { set = {}; if (remove.length > 0) { if (_this._bucket.tryRemoveTokens(cost)) { Log.log('OptionsSync::remove', remove); return _this.storage.remove(remove); } else { return Promise.reject('bucket'); } } })["catch"](function(e) { var i, key, len, value, valuesAffected; for (key in set) { if (!hasProp.call(set, key)) continue; value = set[key]; if (!(key in _this._pending)) { _this._pending[key] = value; } } for (i = 0, len = remove.length; i < len; i++) { key = remove[i]; if (!(key in _this._pending)) { _this._pending[key] = void 0; } } if (e === 'bucket') { return _this._doPush(); } else if (e instanceof Storage.RateLimitExceededError) { Log.log('OptionsSync::rateLimitExceeded'); _this._bucket.clear(); _this.requestPush({}); } else if (e instanceof Storage.QuotaExceededError) { valuesAffected = 0; for (key in set) { if (!hasProp.call(set, key)) continue; value = set[key]; if (key[0] === '+' && value.syncOptions !== 'disabled') { value.syncOptions = 'disabled'; value.syncError = { reason: 'quotaPerItem' }; valuesAffected++; } } if (valuesAffected > 0) { _this.requestPush({}); } else { _this._pending = {}; } } else { return Promise.reject(e); } }); }); }; })(this)); }; OptionsSync.prototype._logOperations = function(text, operations) { if (Object.keys(operations.set).length) { Log.log(text + '::set', operations.set); } if (operations.remove.length) { return Log.log(text + '::remove', operations.remove); } }; /** * Pull the remote storage for changes, and write them to local. * @param {Storage} local The local storage to be written to * @returns {function} Calling the returned function will stop watching. */ OptionsSync.prototype.copyTo = function(local) { return Promise.join(local.get(null), this.storage.get(null), (function(_this) { return function(base, changes) { var key, ref; for (key in base) { if (!hasProp.call(base, key)) continue; if (!(key in changes)) { if (key[0] === '+' && !((ref = base[key]) != null ? ref.syncOptions : void 0) === 'disabled') { changes[key] = void 0; } } } return local.apply({ changes: changes, base: base, merge: _this.merge }).then(function(operations) { return _this._logOperations('OptionsSync::copyTo', operations); }); }; })(this)); }; /** * Watch the remote storage for changes, and write them to local. * The actual writing is throttled by pullThrottle with initial delay. * @param {Storage} local The local storage to be written to * @returns {function} Calling the returned function will stop watching. */ OptionsSync.prototype.watchAndPull = function(local) { var doPull, pull, pullScheduled; pullScheduled = null; pull = {}; doPull = (function(_this) { return function() { return local.get(null).then(function(base) { var changes; changes = pull; pull = {}; pullScheduled = null; return Storage.operationsForChanges(changes, { base: base, merge: _this.merge }); }).then(function(operations) { _this._logOperations('OptionsSync::pull', operations); return local.apply(operations); }); }; })(this); return this.storage.watch(null, (function(_this) { return function(changes) { var key, value; for (key in changes) { if (!hasProp.call(changes, key)) continue; value = changes[key]; pull[key] = value; } if (pullScheduled != null) { return; } return pullScheduled = setTimeout(doPull, _this.pullThrottle); }; })(this)); }; return OptionsSync; })(); module.exports = OptionsSync; },{"./log":31,"./storage":34,"bluebird":2,"jsondiffpatch":19,"limiter":22,"omega-pac":27}],34:[function(require,module,exports){ /* @module omega-target/storage */ var Log, Promise, Storage, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Promise = require('bluebird'); Log = require('./log'); Storage = (function() { var QuotaExceededError, RateLimitExceededError, StorageUnavailableError; function Storage() {} /** * Any operation that fails due to rate limiting should reject with an instance * of RateLimitExceededError, when implemented in derived classes of Storage. */ Storage.RateLimitExceededError = RateLimitExceededError = (function(superClass) { extend(RateLimitExceededError, superClass); function RateLimitExceededError() { RateLimitExceededError.__super__.constructor.apply(this, arguments); } return RateLimitExceededError; })(Error); /** * Any operation that fails due to storage quota should reject with an instance * of QuotaExceededError, when implemented in derived classes of Storage. */ Storage.QuotaExceededError = QuotaExceededError = (function(superClass) { extend(QuotaExceededError, superClass); function QuotaExceededError() { QuotaExceededError.__super__.constructor.apply(this, arguments); } return QuotaExceededError; })(Error); /** * If this storage is not available for some reason, all operations should * reject with an instance of StorageUnavailableError, when implemented in * derived classes of Storage. * This error is considered fatal and unrecoverable in the current environment. * Further access to this storage should be avoided until restart. */ Storage.StorageUnavailableError = StorageUnavailableError = (function(superClass) { extend(StorageUnavailableError, superClass); function StorageUnavailableError() { StorageUnavailableError.__super__.constructor.apply(this, arguments); } return StorageUnavailableError; })(Error); /** * A set of operations to be performed on a Storage. * @typedef WriteOperations * @type {object} * @property {Object.} set - A map from keys to new values of the * items to set * @property {{}[]} remove - An array of keys to remove */ /** * Calculate the actual operations against storage that should be performed to * replay the changes on a storage. * @param {Object.} changes The changes to apply * @param {?{}} args Extra arguments * @param {Object.?} args.base The original items in the storage. * @param {function(key, newVal, oldVal)} args.merge A function that merges * the newVal and oldVal. oldVal is provided only if args.base is present. * Otherwise it will be equal to newVal (i.e. merge(key, newVal, newVal)). * @returns {WriteOperations} The operations that should be performed. */ Storage.operationsForChanges = function(changes, arg) { var base, key, merge, newVal, oldVal, ref, remove, set; ref = arg != null ? arg : {}, base = ref.base, merge = ref.merge; set = {}; remove = []; for (key in changes) { newVal = changes[key]; oldVal = base != null ? base[key] : newVal; if (merge) { newVal = merge(key, newVal, oldVal); } if ((base != null) && newVal === oldVal) { continue; } if (typeof newVal === 'undefined') { if (typeof oldVal !== 'undefined' || (base == null)) { remove.push(key); } } else { set[key] = newVal; } } return { set: set, remove: remove }; }; /** * Get the requested values by keys from the storage. * @param {(string|string[]|null|Object.)} keys The keys to retrive, * or null for all. * @returns {Promise<(Object.)>} A map from keys to values */ Storage.prototype.get = function(keys) { var i, key, len, map, ref, value; Log.method('Storage#get', this, arguments); if (!this._items) { return Promise.resolve({}); } if (keys == null) { keys = this._items; } map = {}; if (typeof keys === 'string') { map[keys] = this._items[keys]; } else if (Array.isArray(keys)) { for (i = 0, len = keys.length; i < len; i++) { key = keys[i]; map[key] = this._items[key]; } } else if (typeof keys === 'object') { for (key in keys) { value = keys[key]; map[key] = (ref = this._items[key]) != null ? ref : value; } } return Promise.resolve(map); }; /** * Set multiple values by keys in the storage. * @param {(string|Object.)} items A map from key to value to set. * @returns {Promise<(Object.)>} A map of key-value pairs just set. */ Storage.prototype.set = function(items) { var key, value; Log.method('Storage#set', this, arguments); if (this._items == null) { this._items = {}; } for (key in items) { value = items[key]; this._items[key] = value; } return Promise.resolve(items); }; /** * Remove items by keys from the storage. * @param {(string|string[]|null)} keys The keys to remove, or null for all. * @returns {Promise} A promise that fulfills on successful removal. */ Storage.prototype.remove = function(keys) { var i, key, len; Log.method('Storage#remove', this, arguments); if (this._items != null) { if (keys == null) { this._items = {}; } else if (Array.isArray(keys)) { for (i = 0, len = keys.length; i < len; i++) { key = keys[i]; delete this._items[key]; } } else { delete this._items[keys]; } } return Promise.resolve(); }; /** * @callback watchCallback * @param {Object.} map A map of key-value pairs just changed. */ /** * Watch for any changes to the storage. * @param {(string|string[]|null)} keys The keys to watch, or null for all. * @param {watchCallback} callback Called everytime something changes. * @returns {function} Calling the returned function will stop watching. */ Storage.prototype.watch = function(keys, callback) { Log.method('Storage#watch', this, arguments); return (function() { return null; }); }; /** * Apply WriteOperations to the storage. * @param {WriteOperations|{changes: Object.}} operations The * operations to apply, or the changes to be applied. If changes is provided, * the operations are calculated by Storage.operationsForChanges, with extra * fields passed through as the second argument. * @returns {Promise} A promise that fulfills on operation success. */ Storage.prototype.apply = function(operations) { if ('changes' in operations) { operations = Storage.operationsForChanges(operations.changes, operations); } return this.set(operations.set).then((function(_this) { return function() { return _this.remove(operations.remove); }; })(this))["return"](operations); }; return Storage; })(); module.exports = Storage; },{"./log":31,"bluebird":2}],35:[function(require,module,exports){ exports.Promise = require('bluebird'); },{"bluebird":2}],"OmegaTarget":[function(require,module,exports){ var name, ref, ref1, value; module.exports = { Log: require('./src/log'), Storage: require('./src/storage'), BrowserStorage: require('./src/browser_storage'), Options: require('./src/options'), OptionsSync: require('./src/options_sync'), OmegaPac: require('omega-pac') }; ref = require('./src/utils.coffee'); for (name in ref) { value = ref[name]; module.exports[name] = value; } ref1 = require('./src/errors.coffee'); for (name in ref1) { value = ref1[name]; module.exports[name] = value; } },{"./src/browser_storage":28,"./src/errors.coffee":30,"./src/log":31,"./src/options":32,"./src/options_sync":33,"./src/storage":34,"./src/utils.coffee":35,"omega-pac":27}]},{},["OmegaTarget"])("OmegaTarget") });