@wiz-code/async-fsm
Version:
Finite StateMachine JavaScript Library
1,423 lines (1,235 loc) • 1.68 MB
JavaScript
(function(){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<r.length;o++)s(r[o]);return s}return e})()({1:[function(require,module,exports){
(function (global){
(function (root, factory) {
"use strict";
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["samsam"], factory);
} else if (typeof module === "object" && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("samsam"));
} else {
// Browser globals (root is window)
root.formatio = factory(root.samsam);
}
}(typeof self !== "undefined" ? self : this, function (samsam) {
"use strict";
var formatio = {
excludeConstructors: ["Object", /^.$/],
quoteStrings: true,
limitChildrenCount: 0
};
var specialObjects = [];
if (typeof global !== "undefined") {
specialObjects.push({ object: global, value: "[object global]" });
}
if (typeof document !== "undefined") {
specialObjects.push({
object: document,
value: "[object HTMLDocument]"
});
}
if (typeof window !== "undefined") {
specialObjects.push({ object: window, value: "[object Window]" });
}
function functionName(func) {
if (!func) { return ""; }
if (func.displayName) { return func.displayName; }
if (func.name) { return func.name; }
var matches = func.toString().match(/function\s+([^\(]+)/m);
return (matches && matches[1]) || "";
}
function constructorName(f, object) {
var name = functionName(object && object.constructor);
var excludes = f.excludeConstructors ||
formatio.excludeConstructors || [];
var i, l;
for (i = 0, l = excludes.length; i < l; ++i) {
if (typeof excludes[i] === "string" && excludes[i] === name) {
return "";
} else if (excludes[i].test && excludes[i].test(name)) {
return "";
}
}
return name;
}
function isCircular(object, objects) {
if (typeof object !== "object") { return false; }
var i, l;
for (i = 0, l = objects.length; i < l; ++i) {
if (objects[i] === object) { return true; }
}
return false;
}
function ascii(f, object, processed, indent) {
if (typeof object === "string") {
if (object.length === 0) { return "(empty string)"; }
var qs = f.quoteStrings;
var quote = typeof qs !== "boolean" || qs;
return processed || quote ? "\"" + object + "\"" : object;
}
if (typeof object === "function" && !(object instanceof RegExp)) {
return ascii.func(object);
}
processed = processed || [];
if (isCircular(object, processed)) { return "[Circular]"; }
if (Object.prototype.toString.call(object) === "[object Array]") {
return ascii.array.call(f, object, processed);
}
if (!object) { return String((1 / object) === -Infinity ? "-0" : object); }
if (samsam.isElement(object)) { return ascii.element(object); }
if (typeof object.toString === "function" &&
object.toString !== Object.prototype.toString) {
return object.toString();
}
var i, l;
for (i = 0, l = specialObjects.length; i < l; i++) {
if (object === specialObjects[i].object) {
return specialObjects[i].value;
}
}
if (typeof Set !== "undefined" && object instanceof Set) {
return ascii.set.call(f, object, processed);
}
return ascii.object.call(f, object, processed, indent);
}
ascii.func = function (func) {
return "function " + functionName(func) + "() {}";
};
function delimit(str, delimiters) {
delimiters = delimiters || ["[", "]"];
return delimiters[0] + str + delimiters[1];
}
ascii.array = function (array, processed, delimiters) {
processed = processed || [];
processed.push(array);
var pieces = [];
var i, l;
l = (this.limitChildrenCount > 0) ?
Math.min(this.limitChildrenCount, array.length) : array.length;
for (i = 0; i < l; ++i) {
pieces.push(ascii(this, array[i], processed));
}
if (l < array.length) {
pieces.push("[... " + (array.length - l) + " more elements]");
}
return delimit(pieces.join(", "), delimiters);
};
ascii.set = function (set, processed) {
return ascii.array.call(this, Array.from(set), processed, ["Set {", "}"]);
};
ascii.object = function (object, processed, indent) {
processed = processed || [];
processed.push(object);
indent = indent || 0;
var pieces = [];
var properties = samsam.keys(object).sort();
var length = 3;
var prop, str, obj, i, k, l;
l = (this.limitChildrenCount > 0) ?
Math.min(this.limitChildrenCount, properties.length) : properties.length;
for (i = 0; i < l; ++i) {
prop = properties[i];
obj = object[prop];
if (isCircular(obj, processed)) {
str = "[Circular]";
} else {
str = ascii(this, obj, processed, indent + 2);
}
str = (/\s/.test(prop) ? "\"" + prop + "\"" : prop) + ": " + str;
length += str.length;
pieces.push(str);
}
var cons = constructorName(this, object);
var prefix = cons ? "[" + cons + "] " : "";
var is = "";
for (i = 0, k = indent; i < k; ++i) { is += " "; }
if (l < properties.length)
{pieces.push("[... " + (properties.length - l) + " more elements]");}
if (length + indent > 80) {
return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" +
is + "}";
}
return prefix + "{ " + pieces.join(", ") + " }";
};
ascii.element = function (element) {
var tagName = element.tagName.toLowerCase();
var attrs = element.attributes;
var pairs = [];
var attr, attrName, i, l, val;
for (i = 0, l = attrs.length; i < l; ++i) {
attr = attrs.item(i);
attrName = attr.nodeName.toLowerCase().replace("html:", "");
val = attr.nodeValue;
if (attrName !== "contenteditable" || val !== "inherit") {
if (val) { pairs.push(attrName + "=\"" + val + "\""); }
}
}
var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
// SVG elements have undefined innerHTML
var content = element.innerHTML || "";
if (content.length > 20) {
content = content.substr(0, 20) + "[...]";
}
var res = formatted + pairs.join(" ") + ">" + content +
"</" + tagName + ">";
return res.replace(/ contentEditable="inherit"/, "");
};
function Formatio(options) {
// eslint-disable-next-line guard-for-in
for (var opt in options) {
this[opt] = options[opt];
}
}
Formatio.prototype = {
functionName: functionName,
configure: function (options) {
return new Formatio(options);
},
constructorName: function (object) {
return constructorName(this, object);
},
ascii: function (object, processed, indent) {
return ascii(this, object, processed, indent);
}
};
return Formatio.prototype;
}));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"samsam":146}],2:[function(require,module,exports){
module.exports = function(acorn) {
switch (parseInt(acorn.version)) {
case 2:
case 3:
acorn.plugins.asyncawait = require('./acorn-v3') ;
break ;
case 4:
acorn.plugins.asyncawait = require('./acorn-v4') ;
break ;
case 5:
acorn.plugins.asyncawait = require('./acorn-v4') ;
break ;
default:
throw new Error("acorn-es7-plugin requires Acorn v2, 3, 4 or 5") ;
}
return acorn
}
},{"./acorn-v3":3,"./acorn-v4":4}],3:[function(require,module,exports){
var NotAsync = {} ;
var asyncExit = /^async[\t ]+(return|throw)/ ;
var asyncFunction = /^async[\t ]+function/ ;
var atomOrPropertyOrLabel = /^\s*[():;]/ ;
var removeComments = /([^\n])\/\*(\*(?!\/)|[^\n*])*\*\/([^\n])/g ;
var matchAsyncGet = /\s*(get|set)\s*\(/ ;
function hasLineTerminatorBeforeNext(st, since) {
return st.lineStart >= since;
}
function test(regex,st,noComment) {
var src = st.input.slice(st.start) ;
if (noComment) {
src = src.replace(removeComments,"$1 $3") ;
}
return regex.test(src);
}
/* Create a new parser derived from the specified parser, so that in the
* event of an error we can back out and try again */
function subParse(parser, pos, extensions,parens) {
var p = new parser.constructor(parser.options, parser.input, pos);
if (extensions)
for (var k in extensions)
p[k] = extensions[k] ;
var src = parser ;
var dest = p ;
['inFunction','inAsyncFunction','inAsync','inGenerator','inModule'].forEach(function(k){
if (k in src)
dest[k] = src[k] ;
}) ;
if (parens)
p.options.preserveParens = true ;
p.nextToken();
return p;
}
//TODO: Implement option noAsyncGetters
function asyncAwaitPlugin (parser,options){
var es7check = function(){} ;
parser.extend("initialContext",function(base){
return function(){
if (this.options.ecmaVersion < 7) {
es7check = function(node) {
parser.raise(node.start,"async/await keywords only available when ecmaVersion>=7") ;
} ;
}
this.reservedWords = new RegExp(this.reservedWords.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")) ;
this.reservedWordsStrict = new RegExp(this.reservedWordsStrict.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")) ;
this.reservedWordsStrictBind = new RegExp(this.reservedWordsStrictBind.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")) ;
this.inAsyncFunction = options.inAsyncFunction ;
if (options.awaitAnywhere && options.inAsyncFunction)
parser.raise(node.start,"The options awaitAnywhere and inAsyncFunction are mutually exclusive") ;
return base.apply(this,arguments);
}
}) ;
parser.extend("shouldParseExportStatement",function(base){
return function(){
if (this.type.label==='name' && this.value==='async' && test(asyncFunction,this)) {
return true ;
}
return base.apply(this,arguments) ;
}
}) ;
parser.extend("parseStatement",function(base){
return function (declaration, topLevel) {
var start = this.start;
var startLoc = this.startLoc;
if (this.type.label==='name') {
if (test(asyncFunction,this,true)) {
var wasAsync = this.inAsyncFunction ;
try {
this.inAsyncFunction = true ;
this.next() ;
var r = this.parseStatement(declaration, topLevel) ;
r.async = true ;
r.start = start;
r.loc && (r.loc.start = startLoc);
r.range && (r.range[0] = start);
return r ;
} finally {
this.inAsyncFunction = wasAsync ;
}
} else if ((typeof options==="object" && options.asyncExits) && test(asyncExit,this)) {
// NON-STANDARD EXTENSION iff. options.asyncExits is set, the
// extensions 'async return <expr>?' and 'async throw <expr>?'
// are enabled. In each case they are the standard ESTree nodes
// with the flag 'async:true'
this.next() ;
var r = this.parseStatement(declaration, topLevel) ;
r.async = true ;
r.start = start;
r.loc && (r.loc.start = startLoc);
r.range && (r.range[0] = start);
return r ;
}
}
return base.apply(this,arguments);
}
}) ;
parser.extend("parseIdent",function(base){
return function(liberal){
var id = base.apply(this,arguments);
if (this.inAsyncFunction && id.name==='await') {
if (arguments.length===0) {
this.raise(id.start,"'await' is reserved within async functions") ;
}
}
return id ;
}
}) ;
parser.extend("parseExprAtom",function(base){
return function(refShorthandDefaultPos){
var start = this.start ;
var startLoc = this.startLoc;
var rhs,r = base.apply(this,arguments);
if (r.type==='Identifier') {
if (r.name==='async' && !hasLineTerminatorBeforeNext(this, r.end)) {
// Is this really an async function?
var isAsync = this.inAsyncFunction ;
try {
this.inAsyncFunction = true ;
var pp = this ;
var inBody = false ;
var parseHooks = {
parseFunctionBody:function(node,isArrowFunction){
try {
var wasInBody = inBody ;
inBody = true ;
return pp.parseFunctionBody.apply(this,arguments) ;
} finally {
inBody = wasInBody ;
}
},
raise:function(){
try {
return pp.raise.apply(this,arguments) ;
} catch(ex) {
throw inBody?ex:NotAsync ;
}
}
} ;
rhs = subParse(this,this.start,parseHooks,true).parseExpression() ;
if (rhs.type==='SequenceExpression')
rhs = rhs.expressions[0] ;
if (rhs.type === 'CallExpression')
rhs = rhs.callee ;
if (rhs.type==='FunctionExpression' || rhs.type==='FunctionDeclaration' || rhs.type==='ArrowFunctionExpression') {
// Because we don't know if the top level parser supprts preserveParens, we have to re-parse
// without it set
rhs = subParse(this,this.start,parseHooks).parseExpression() ;
if (rhs.type==='SequenceExpression')
rhs = rhs.expressions[0] ;
if (rhs.type === 'CallExpression')
rhs = rhs.callee ;
rhs.async = true ;
rhs.start = start;
rhs.loc && (rhs.loc.start = startLoc);
rhs.range && (rhs.range[0] = start);
this.pos = rhs.end;
this.end = rhs.end ;
this.endLoc = rhs.endLoc ;
this.next();
es7check(rhs) ;
return rhs ;
}
} catch (ex) {
if (ex!==NotAsync)
throw ex ;
}
finally {
this.inAsyncFunction = isAsync ;
}
}
else if (r.name==='await') {
var n = this.startNodeAt(r.start, r.loc && r.loc.start);
if (this.inAsyncFunction) {
rhs = this.parseExprSubscripts() ;
n.operator = 'await' ;
n.argument = rhs ;
n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc && rhs.loc.end) ;
es7check(n) ;
return n ;
}
// NON-STANDARD EXTENSION iff. options.awaitAnywhere is true,
// an 'AwaitExpression' is allowed anywhere the token 'await'
// could not be an identifier with the name 'await'.
// Look-ahead to see if this is really a property or label called async or await
if (this.input.slice(r.end).match(atomOrPropertyOrLabel)) {
if (!options.awaitAnywhere && this.options.sourceType === 'module')
return this.raise(r.start,"'await' is reserved within modules") ;
return r ; // This is a valid property name or label
}
if (typeof options==="object" && options.awaitAnywhere) {
start = this.start ;
rhs = subParse(this,start-4).parseExprSubscripts() ;
if (rhs.end<=start) {
rhs = subParse(this,start).parseExprSubscripts() ;
n.operator = 'await' ;
n.argument = rhs ;
n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc && rhs.loc.end) ;
this.pos = rhs.end;
this.end = rhs.end ;
this.endLoc = rhs.endLoc ;
this.next();
es7check(n) ;
return n ;
}
}
if (!options.awaitAnywhere && this.options.sourceType === 'module')
return this.raise(r.start,"'await' is reserved within modules") ;
}
}
return r ;
}
}) ;
parser.extend('finishNodeAt',function(base){
return function(node,type,pos,loc) {
if (node.__asyncValue) {
delete node.__asyncValue ;
node.value.async = true ;
}
return base.apply(this,arguments) ;
}
}) ;
parser.extend('finishNode',function(base){
return function(node,type) {
if (node.__asyncValue) {
delete node.__asyncValue ;
node.value.async = true ;
}
return base.apply(this,arguments) ;
}
}) ;
var allowedPropSpecifiers = {
get:true,
set:true,
async:true
};
parser.extend("parsePropertyName",function(base){
return function (prop) {
var prevName = prop.key && prop.key.name ;
var key = base.apply(this,arguments) ;
if (key.type === "Identifier" && (key.name === "async") && !hasLineTerminatorBeforeNext(this, key.end)) {
// Look-ahead to see if this is really a property or label called async or await
if (!this.input.slice(key.end).match(atomOrPropertyOrLabel)){
// Cheese - eliminate the cases 'async get(){}' and async set(){}'
if (matchAsyncGet.test(this.input.slice(key.end))) {
key = base.apply(this,arguments) ;
prop.__asyncValue = true ;
} else {
es7check(prop) ;
if (prop.kind === 'set')
this.raise(key.start,"'set <member>(value)' cannot be be async") ;
key = base.apply(this,arguments) ;
if (key.type==='Identifier') {
if (key.name==='set')
this.raise(key.start,"'set <member>(value)' cannot be be async") ;
}
prop.__asyncValue = true ;
}
}
}
return key;
};
}) ;
parser.extend("parseClassMethod",function(base){
return function (classBody, method, isGenerator) {
var wasAsync ;
if (method.__asyncValue) {
if (method.kind==='constructor')
this.raise(method.start,"class constructor() cannot be be async") ;
wasAsync = this.inAsyncFunction ;
this.inAsyncFunction = true ;
}
var r = base.apply(this,arguments) ;
this.inAsyncFunction = wasAsync ;
return r ;
}
}) ;
parser.extend("parseMethod",function(base){
return function (isGenerator) {
var wasAsync ;
if (this.__currentProperty && this.__currentProperty.__asyncValue) {
wasAsync = this.inAsyncFunction ;
this.inAsyncFunction = true ;
}
var r = base.apply(this,arguments) ;
this.inAsyncFunction = wasAsync ;
return r ;
}
}) ;
parser.extend("parsePropertyValue",function(base){
return function (prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors) {
var prevProp = this.__currentProperty ;
this.__currentProperty = prop ;
var wasAsync ;
if (prop.__asyncValue) {
wasAsync = this.inAsyncFunction ;
this.inAsyncFunction = true ;
}
var r = base.apply(this,arguments) ;
this.inAsyncFunction = wasAsync ;
this.__currentProperty = prevProp ;
return r ;
}
}) ;
}
module.exports = asyncAwaitPlugin ;
},{}],4:[function(require,module,exports){
var asyncExit = /^async[\t ]+(return|throw)/ ;
var atomOrPropertyOrLabel = /^\s*[):;]/ ;
var removeComments = /([^\n])\/\*(\*(?!\/)|[^\n*])*\*\/([^\n])/g ;
function hasLineTerminatorBeforeNext(st, since) {
return st.lineStart >= since;
}
function test(regex,st,noComment) {
var src = st.input.slice(st.start) ;
if (noComment) {
src = src.replace(removeComments,"$1 $3") ;
}
return regex.test(src);
}
/* Create a new parser derived from the specified parser, so that in the
* event of an error we can back out and try again */
function subParse(parser, pos, extensions) {
var p = new parser.constructor(parser.options, parser.input, pos);
if (extensions)
for (var k in extensions)
p[k] = extensions[k] ;
var src = parser ;
var dest = p ;
['inFunction','inAsync','inGenerator','inModule'].forEach(function(k){
if (k in src)
dest[k] = src[k] ;
}) ;
p.nextToken();
return p;
}
function asyncAwaitPlugin (parser,options){
if (!options || typeof options !== "object")
options = {} ;
parser.extend("parse",function(base){
return function(){
this.inAsync = options.inAsyncFunction ;
if (options.awaitAnywhere && options.inAsyncFunction)
parser.raise(node.start,"The options awaitAnywhere and inAsyncFunction are mutually exclusive") ;
return base.apply(this,arguments);
}
}) ;
parser.extend("parseStatement",function(base){
return function (declaration, topLevel) {
var start = this.start;
var startLoc = this.startLoc;
if (this.type.label==='name') {
if ((options.asyncExits) && test(asyncExit,this)) {
// TODO: Ensure this function is itself nested in an async function or Method
this.next() ;
var r = this.parseStatement(declaration, topLevel) ;
r.async = true ;
r.start = start;
r.loc && (r.loc.start = startLoc);
r.range && (r.range[0] = start);
return r ;
}
}
return base.apply(this,arguments);
}
}) ;
parser.extend("parseIdent",function(base){
return function(liberal) {
if (this.options.sourceType==='module' && this.options.ecmaVersion >= 8 && options.awaitAnywhere)
return base.call(this,true) ; // Force liberal mode if awaitAnywhere is set
return base.apply(this,arguments) ;
}
}) ;
parser.extend("parseExprAtom",function(base){
var NotAsync = {};
return function(refShorthandDefaultPos){
var start = this.start ;
var startLoc = this.startLoc;
var rhs,r = base.apply(this,arguments);
if (r.type==='Identifier') {
if (r.name==='await' && !this.inAsync) {
if (options.awaitAnywhere) {
var n = this.startNodeAt(r.start, r.loc && r.loc.start);
start = this.start ;
var parseHooks = {
raise:function(){
try {
return pp.raise.apply(this,arguments) ;
} catch(ex) {
throw /*inBody?ex:*/NotAsync ;
}
}
} ;
try {
rhs = subParse(this,start-4,parseHooks).parseExprSubscripts() ;
if (rhs.end<=start) {
rhs = subParse(this,start,parseHooks).parseExprSubscripts() ;
n.argument = rhs ;
n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc && rhs.loc.end) ;
this.pos = rhs.end;
this.end = rhs.end ;
this.endLoc = rhs.endLoc ;
this.next();
return n ;
}
} catch (ex) {
if (ex===NotAsync)
return r ;
throw ex ;
}
}
}
}
return r ;
}
}) ;
var allowedPropValues = {
undefined:true,
get:true,
set:true,
static:true,
async:true,
constructor:true
};
parser.extend("parsePropertyName",function(base){
return function (prop) {
var prevName = prop.key && prop.key.name ;
var key = base.apply(this,arguments) ;
if (this.value==='get') {
prop.__maybeStaticAsyncGetter = true ;
}
var next ;
if (allowedPropValues[this.value])
return key ;
if (key.type === "Identifier" && (key.name === "async" || prevName === "async") && !hasLineTerminatorBeforeNext(this, key.end)
// Look-ahead to see if this is really a property or label called async or await
&& !this.input.slice(key.end).match(atomOrPropertyOrLabel)) {
if (prop.kind === 'set' || key.name === 'set')
this.raise(key.start,"'set <member>(value)' cannot be be async") ;
else {
this.__isAsyncProp = true ;
key = base.apply(this,arguments) ;
if (key.type==='Identifier') {
if (key.name==='set')
this.raise(key.start,"'set <member>(value)' cannot be be async") ;
}
}
} else {
delete prop.__maybeStaticAsyncGetter ;
}
return key;
};
}) ;
parser.extend("parseClassMethod",function(base){
return function (classBody, method, isGenerator) {
var r = base.apply(this,arguments) ;
if (method.__maybeStaticAsyncGetter) {
delete method.__maybeStaticAsyncGetter ;
if (method.key.name!=='get')
method.kind = "get" ;
}
return r ;
}
}) ;
parser.extend("parseFunctionBody",function(base){
return function (node, isArrowFunction) {
var wasAsync = this.inAsync ;
if (this.__isAsyncProp) {
node.async = true ;
this.inAsync = true ;
delete this.__isAsyncProp ;
}
var r = base.apply(this,arguments) ;
this.inAsync = wasAsync ;
return r ;
}
}) ;
}
module.exports = asyncAwaitPlugin ;
},{}],5:[function(require,module,exports){
/**
* Array#filter.
*
* @param {Array} arr
* @param {Function} fn
* @param {Object=} self
* @return {Array}
* @throw TypeError
*/
module.exports = function (arr, fn, self) {
if (arr.filter) return arr.filter(fn, self);
if (void 0 === arr || null === arr) throw new TypeError;
if ('function' != typeof fn) throw new TypeError;
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (!hasOwn.call(arr, i)) continue;
var val = arr[i];
if (fn.call(self, val, i, arr)) ret.push(val);
}
return ret;
};
var hasOwn = Object.prototype.hasOwnProperty;
},{}],6:[function(require,module,exports){
(function (global){
'use strict';
// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
function compare(a, b) {
if (a === b) {
return 0;
}
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) {
return -1;
}
if (y < x) {
return 1;
}
return 0;
}
function isBuffer(b) {
if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
return global.Buffer.isBuffer(b);
}
return !!(b != null && b._isBuffer);
}
// based on node assert, original notice:
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
var util = require('util/');
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
return function foo() {}.name === 'foo';
}());
function pToString (obj) {
return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
if (isBuffer(arrbuf)) {
return false;
}
if (typeof global.ArrayBuffer !== 'function') {
return false;
}
if (typeof ArrayBuffer.isView === 'function') {
return ArrayBuffer.isView(arrbuf);
}
if (!arrbuf) {
return false;
}
if (arrbuf instanceof DataView) {
return true;
}
if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
return true;
}
return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
if (!util.isFunction(func)) {
return;
}
if (functionsHaveNames) {
return func.name;
}
var str = func.toString();
var match = str.match(regex);
return match && match[1];
}
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
} else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = getName(stackStartFunction);
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function truncate(s, n) {
if (typeof s === 'string') {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function inspect(something) {
if (functionsHaveNames || !util.isFunction(something)) {
return util.inspect(something);
}
var rawname = getName(something);
var name = rawname ? ': ' + rawname : '';
return '[Function' + name + ']';
}
function getMessage(self) {
return truncate(inspect(self.actual), 128) + ' ' +
self.operator + ' ' +
truncate(inspect(self.expected), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
}
};
function _deepEqual(actual, expected, strict, memos) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (isBuffer(actual) && isBuffer(expected)) {
return compare(actual, expected) === 0;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if ((actual === null || typeof actual !== 'object') &&
(expected === null || typeof expected !== 'object')) {
return strict ? actual === expected : actual == expected;
// If both values are instances of typed arrays, wrap their underlying
// ArrayBuffers in a Buffer each to increase performance
// This optimization requires the arrays to have the same type as checked by
// Object.prototype.toString (aka pToString). Never perform binary
// comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
// bit patterns are not identical.
} else if (isView(actual) && isView(expected) &&
pToString(actual) === pToString(expected) &&
!(actual instanceof Float32Array ||
actual instanceof Float64Array)) {
return compare(new Uint8Array(actual.buffer),
new Uint8Array(expected.buffer)) === 0;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else if (isBuffer(actual) !== isBuffer(expected)) {
return false;
} else {
memos = memos || {actual: [], expected: []};
var actualIndex = memos.actual.indexOf(actual);
if (actualIndex !== -1) {
if (actualIndex === memos.expected.indexOf(expected)) {
return true;
}
}
memos.actual.push(actual);
memos.expected.push(expected);
return objEquiv(actual, expected, strict, memos);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b, strict, actualVisitedObjects) {
if (a === null || a === undefined || b === null || b === undefined)
return false;
// if one is a primitive, the other must be same
if (util.isPrimitive(a) || util.isPrimitive(b))
return a === b;
if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
return false;
var aIsArgs = isArguments(a);
var bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b, strict);
}
var ka = objectKeys(a);
var kb = objectKeys(b);
var key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length !== kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] !== kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
if (_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
}
}
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
}
try {
if (actual instanceof expected) {
return true;
}
} catch (e) {
// Ignore. The instanceof check doesn't work for arrow functions.
}
if (Error.isPrototypeOf(expected)) {
return false;
}
return expected.call({}, actual) === true;
}
function _tryBlock(block) {
var error;
try {
block();
} catch (e) {
error = e;
}
return error;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (typeof block !== 'function') {
throw new TypeError('"block" argument must be a function');
}
if (typeof expected === 'string') {
message = expected;
expected = null;
}
actual = _tryBlock(block);
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
var userProvidedMessage = typeof message === 'string';
var isUnwantedException = !shouldThrow && util.isError(actual);
var isUnexpectedException = !shouldThrow && actual && !expected;
if ((isUnwantedException &&
userProvidedMessage &&
expectedException(actual, expected)) ||
isUnexpectedException) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws(true, block, error, message);
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
_throws(false, block, error, message);
};
assert.ifError = function(err) { if (err) throw err; };
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"util/":196}],7:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 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
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return (b64.length * 3 / 4) - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr((len * 3 / 4) - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0; i < l; i += 4) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len