.'
+ );
+ }
+ }
+ addAttr(el, name, JSON.stringify(value));
+ }
+ }
+}
+
+function checkInFor (el) {
+ var parent = el;
+ while (parent) {
+ if (parent.for !== undefined) {
+ return true
+ }
+ parent = parent.parent;
+ }
+ return false
+}
+
+function parseModifiers (name) {
+ var match = name.match(modifierRE);
+ if (match) {
+ var ret = {};
+ match.forEach(function (m) { ret[m.slice(1)] = true; });
+ return ret
+ }
+}
+
+function makeAttrsMap (attrs) {
+ var map = {};
+ for (var i = 0, l = attrs.length; i < l; i++) {
+ if (process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE) {
+ warn$2('duplicate attribute: ' + attrs[i].name);
+ }
+ map[attrs[i].name] = attrs[i].value;
+ }
+ return map
+}
+
+function isForbiddenTag (el) {
+ return (
+ el.tag === 'style' ||
+ (el.tag === 'script' && (
+ !el.attrsMap.type ||
+ el.attrsMap.type === 'text/javascript'
+ ))
+ )
+}
+
+var ieNSBug = /^xmlns:NS\d+/;
+var ieNSPrefix = /^NS\d+:/;
+
+/* istanbul ignore next */
+function guardIESVGBug (attrs) {
+ var res = [];
+ for (var i = 0; i < attrs.length; i++) {
+ var attr = attrs[i];
+ if (!ieNSBug.test(attr.name)) {
+ attr.name = attr.name.replace(ieNSPrefix, '');
+ res.push(attr);
+ }
+ }
+ return res
+}
+
+function checkForAliasModel (el, value) {
+ var _el = el;
+ while (_el) {
+ if (_el.for && _el.alias === value) {
+ warn$2(
+ "<" + (el.tag) + " v-model=\"" + value + "\">: " +
+ "You are binding v-model directly to a v-for iteration alias. " +
+ "This will not be able to modify the v-for source array because " +
+ "writing to the alias is like modifying a function local variable. " +
+ "Consider using an array of objects and use v-model on an object property instead."
+ );
+ }
+ _el = _el.parent;
+ }
+}
+
+/* */
+
+var isStaticKey;
+var isPlatformReservedTag;
+
+var genStaticKeysCached = cached(genStaticKeys$1);
+
+/**
+ * Goal of the optimizer: walk the generated template AST tree
+ * and detect sub-trees that are purely static, i.e. parts of
+ * the DOM that never needs to change.
+ *
+ * Once we detect these sub-trees, we can:
+ *
+ * 1. Hoist them into constants, so that we no longer need to
+ * create fresh nodes for them on each re-render;
+ * 2. Completely skip them in the patching process.
+ */
+function optimize (root, options) {
+ if (!root) { return }
+ isStaticKey = genStaticKeysCached(options.staticKeys || '');
+ isPlatformReservedTag = options.isReservedTag || no;
+ // first pass: mark all non-static nodes.
+ markStatic$1(root);
+ // second pass: mark static roots.
+ markStaticRoots(root, false);
+}
+
+function genStaticKeys$1 (keys) {
+ return makeMap(
+ 'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +
+ (keys ? ',' + keys : '')
+ )
+}
+
+function markStatic$1 (node) {
+ node.static = isStatic(node);
+ if (node.type === 1) {
+ // do not make component slot content static. this avoids
+ // 1. components not able to mutate slot nodes
+ // 2. static slot content fails for hot-reloading
+ if (
+ !isPlatformReservedTag(node.tag) &&
+ node.tag !== 'slot' &&
+ node.attrsMap['inline-template'] == null
+ ) {
+ return
+ }
+ for (var i = 0, l = node.children.length; i < l; i++) {
+ var child = node.children[i];
+ markStatic$1(child);
+ if (!child.static) {
+ node.static = false;
+ }
+ }
+ }
+}
+
+function markStaticRoots (node, isInFor) {
+ if (node.type === 1) {
+ if (node.static || node.once) {
+ node.staticInFor = isInFor;
+ }
+ // For a node to qualify as a static root, it should have children that
+ // are not just static text. Otherwise the cost of hoisting out will
+ // outweigh the benefits and it's better off to just always render it fresh.
+ if (node.static && node.children.length && !(
+ node.children.length === 1 &&
+ node.children[0].type === 3
+ )) {
+ node.staticRoot = true;
+ return
+ } else {
+ node.staticRoot = false;
+ }
+ if (node.children) {
+ for (var i = 0, l = node.children.length; i < l; i++) {
+ markStaticRoots(node.children[i], isInFor || !!node.for);
+ }
+ }
+ if (node.ifConditions) {
+ walkThroughConditionsBlocks(node.ifConditions, isInFor);
+ }
+ }
+}
+
+function walkThroughConditionsBlocks (conditionBlocks, isInFor) {
+ for (var i = 1, len = conditionBlocks.length; i < len; i++) {
+ markStaticRoots(conditionBlocks[i].block, isInFor);
+ }
+}
+
+function isStatic (node) {
+ if (node.type === 2) { // expression
+ return false
+ }
+ if (node.type === 3) { // text
+ return true
+ }
+ return !!(node.pre || (
+ !node.hasBindings && // no dynamic bindings
+ !node.if && !node.for && // not v-if or v-for or v-else
+ !isBuiltInTag(node.tag) && // not a built-in
+ isPlatformReservedTag(node.tag) && // not a component
+ !isDirectChildOfTemplateFor(node) &&
+ Object.keys(node).every(isStaticKey)
+ ))
+}
+
+function isDirectChildOfTemplateFor (node) {
+ while (node.parent) {
+ node = node.parent;
+ if (node.tag !== 'template') {
+ return false
+ }
+ if (node.for) {
+ return true
+ }
+ }
+ return false
+}
+
+/* */
+
+var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
+var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/;
+
+// keyCode aliases
+var keyCodes = {
+ esc: 27,
+ tab: 9,
+ enter: 13,
+ space: 32,
+ up: 38,
+ left: 37,
+ right: 39,
+ down: 40,
+ 'delete': [8, 46]
+};
+
+// #4868: modifiers that prevent the execution of the listener
+// need to explicitly return null so that we can determine whether to remove
+// the listener for .once
+var genGuard = function (condition) { return ("if(" + condition + ")return null;"); };
+
+var modifierCode = {
+ stop: '$event.stopPropagation();',
+ prevent: '$event.preventDefault();',
+ self: genGuard("$event.target !== $event.currentTarget"),
+ ctrl: genGuard("!$event.ctrlKey"),
+ shift: genGuard("!$event.shiftKey"),
+ alt: genGuard("!$event.altKey"),
+ meta: genGuard("!$event.metaKey"),
+ left: genGuard("'button' in $event && $event.button !== 0"),
+ middle: genGuard("'button' in $event && $event.button !== 1"),
+ right: genGuard("'button' in $event && $event.button !== 2")
+};
+
+function genHandlers (events, native) {
+ var res = native ? 'nativeOn:{' : 'on:{';
+ for (var name in events) {
+ res += "\"" + name + "\":" + (genHandler(name, events[name])) + ",";
+ }
+ return res.slice(0, -1) + '}'
+}
+
+function genHandler (
+ name,
+ handler
+) {
+ if (!handler) {
+ return 'function(){}'
+ }
+
+ if (Array.isArray(handler)) {
+ return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
+ }
+
+ var isMethodPath = simplePathRE.test(handler.value);
+ var isFunctionExpression = fnExpRE.test(handler.value);
+
+ if (!handler.modifiers) {
+ return isMethodPath || isFunctionExpression
+ ? handler.value
+ : ("function($event){" + (handler.value) + "}") // inline statement
+ } else {
+ var code = '';
+ var genModifierCode = '';
+ var keys = [];
+ for (var key in handler.modifiers) {
+ if (modifierCode[key]) {
+ genModifierCode += modifierCode[key];
+ // left/right
+ if (keyCodes[key]) {
+ keys.push(key);
+ }
+ } else {
+ keys.push(key);
+ }
+ }
+ if (keys.length) {
+ code += genKeyFilter(keys);
+ }
+ // Make sure modifiers like prevent and stop get executed after key filtering
+ if (genModifierCode) {
+ code += genModifierCode;
+ }
+ var handlerCode = isMethodPath
+ ? handler.value + '($event)'
+ : isFunctionExpression
+ ? ("(" + (handler.value) + ")($event)")
+ : handler.value;
+ return ("function($event){" + code + handlerCode + "}")
+ }
+}
+
+function genKeyFilter (keys) {
+ return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;")
+}
+
+function genFilterCode (key) {
+ var keyVal = parseInt(key, 10);
+ if (keyVal) {
+ return ("$event.keyCode!==" + keyVal)
+ }
+ var alias = keyCodes[key];
+ return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")")
+}
+
+/* */
+
+function bind$1 (el, dir) {
+ el.wrapData = function (code) {
+ return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")")
+ };
+}
+
+/* */
+
+var baseDirectives = {
+ bind: bind$1,
+ cloak: noop
+};
+
+/* */
+
+// configurable state
+var warn$3;
+var transforms$1;
+var dataGenFns;
+var platformDirectives$1;
+var isPlatformReservedTag$1;
+var staticRenderFns;
+var onceCount;
+var currentOptions;
+
+function generate (
+ ast,
+ options
+) {
+ // save previous staticRenderFns so generate calls can be nested
+ var prevStaticRenderFns = staticRenderFns;
+ var currentStaticRenderFns = staticRenderFns = [];
+ var prevOnceCount = onceCount;
+ onceCount = 0;
+ currentOptions = options;
+ warn$3 = options.warn || baseWarn;
+ transforms$1 = pluckModuleFunction(options.modules, 'transformCode');
+ dataGenFns = pluckModuleFunction(options.modules, 'genData');
+ platformDirectives$1 = options.directives || {};
+ isPlatformReservedTag$1 = options.isReservedTag || no;
+ var code = ast ? genElement(ast) : '_c("div")';
+ staticRenderFns = prevStaticRenderFns;
+ onceCount = prevOnceCount;
+ return {
+ render: ("with(this){return " + code + "}"),
+ staticRenderFns: currentStaticRenderFns
+ }
+}
+
+function genElement (el) {
+ if (el.staticRoot && !el.staticProcessed) {
+ return genStatic(el)
+ } else if (el.once && !el.onceProcessed) {
+ return genOnce(el)
+ } else if (el.for && !el.forProcessed) {
+ return genFor(el)
+ } else if (el.if && !el.ifProcessed) {
+ return genIf(el)
+ } else if (el.tag === 'template' && !el.slotTarget) {
+ return genChildren(el) || 'void 0'
+ } else if (el.tag === 'slot') {
+ return genSlot(el)
+ } else {
+ // component or element
+ var code;
+ if (el.component) {
+ code = genComponent(el.component, el);
+ } else {
+ var data = el.plain ? undefined : genData(el);
+
+ var children = el.inlineTemplate ? null : genChildren(el, true);
+ code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")";
+ }
+ // module transforms
+ for (var i = 0; i < transforms$1.length; i++) {
+ code = transforms$1[i](el, code);
+ }
+ return code
+ }
+}
+
+// hoist static sub-trees out
+function genStatic (el) {
+ el.staticProcessed = true;
+ staticRenderFns.push(("with(this){return " + (genElement(el)) + "}"));
+ return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")")
+}
+
+// v-once
+function genOnce (el) {
+ el.onceProcessed = true;
+ if (el.if && !el.ifProcessed) {
+ return genIf(el)
+ } else if (el.staticInFor) {
+ var key = '';
+ var parent = el.parent;
+ while (parent) {
+ if (parent.for) {
+ key = parent.key;
+ break
+ }
+ parent = parent.parent;
+ }
+ if (!key) {
+ process.env.NODE_ENV !== 'production' && warn$3(
+ "v-once can only be used inside v-for that is keyed. "
+ );
+ return genElement(el)
+ }
+ return ("_o(" + (genElement(el)) + "," + (onceCount++) + (key ? ("," + key) : "") + ")")
+ } else {
+ return genStatic(el)
+ }
+}
+
+function genIf (el) {
+ el.ifProcessed = true; // avoid recursion
+ return genIfConditions(el.ifConditions.slice())
+}
+
+function genIfConditions (conditions) {
+ if (!conditions.length) {
+ return '_e()'
+ }
+
+ var condition = conditions.shift();
+ if (condition.exp) {
+ return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions)))
+ } else {
+ return ("" + (genTernaryExp(condition.block)))
+ }
+
+ // v-if with v-once should generate code like (a)?_m(0):_m(1)
+ function genTernaryExp (el) {
+ return el.once ? genOnce(el) : genElement(el)
+ }
+}
+
+function genFor (el) {
+ var exp = el.for;
+ var alias = el.alias;
+ var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
+ var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
+
+ if (
+ process.env.NODE_ENV !== 'production' &&
+ maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key
+ ) {
+ warn$3(
+ "<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " +
+ "v-for should have explicit keys. " +
+ "See https://vuejs.org/guide/list.html#key for more info.",
+ true /* tip */
+ );
+ }
+
+ el.forProcessed = true; // avoid recursion
+ return "_l((" + exp + ")," +
+ "function(" + alias + iterator1 + iterator2 + "){" +
+ "return " + (genElement(el)) +
+ '})'
+}
+
+function genData (el) {
+ var data = '{';
+
+ // directives first.
+ // directives may mutate the el's other properties before they are generated.
+ var dirs = genDirectives(el);
+ if (dirs) { data += dirs + ','; }
+
+ // key
+ if (el.key) {
+ data += "key:" + (el.key) + ",";
+ }
+ // ref
+ if (el.ref) {
+ data += "ref:" + (el.ref) + ",";
+ }
+ if (el.refInFor) {
+ data += "refInFor:true,";
+ }
+ // pre
+ if (el.pre) {
+ data += "pre:true,";
+ }
+ // record original tag name for components using "is" attribute
+ if (el.component) {
+ data += "tag:\"" + (el.tag) + "\",";
+ }
+ // module data generation functions
+ for (var i = 0; i < dataGenFns.length; i++) {
+ data += dataGenFns[i](el);
+ }
+ // attributes
+ if (el.attrs) {
+ data += "attrs:{" + (genProps(el.attrs)) + "},";
+ }
+ // DOM props
+ if (el.props) {
+ data += "domProps:{" + (genProps(el.props)) + "},";
+ }
+ // event handlers
+ if (el.events) {
+ data += (genHandlers(el.events)) + ",";
+ }
+ if (el.nativeEvents) {
+ data += (genHandlers(el.nativeEvents, true)) + ",";
+ }
+ // slot target
+ if (el.slotTarget) {
+ data += "slot:" + (el.slotTarget) + ",";
+ }
+ // scoped slots
+ if (el.scopedSlots) {
+ data += (genScopedSlots(el.scopedSlots)) + ",";
+ }
+ // component v-model
+ if (el.model) {
+ data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},";
+ }
+ // inline-template
+ if (el.inlineTemplate) {
+ var inlineTemplate = genInlineTemplate(el);
+ if (inlineTemplate) {
+ data += inlineTemplate + ",";
+ }
+ }
+ data = data.replace(/,$/, '') + '}';
+ // v-bind data wrap
+ if (el.wrapData) {
+ data = el.wrapData(data);
+ }
+ return data
+}
+
+function genDirectives (el) {
+ var dirs = el.directives;
+ if (!dirs) { return }
+ var res = 'directives:[';
+ var hasRuntime = false;
+ var i, l, dir, needRuntime;
+ for (i = 0, l = dirs.length; i < l; i++) {
+ dir = dirs[i];
+ needRuntime = true;
+ var gen = platformDirectives$1[dir.name] || baseDirectives[dir.name];
+ if (gen) {
+ // compile-time directive that manipulates AST.
+ // returns true if it also needs a runtime counterpart.
+ needRuntime = !!gen(el, dir, warn$3);
+ }
+ if (needRuntime) {
+ hasRuntime = true;
+ res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},";
+ }
+ }
+ if (hasRuntime) {
+ return res.slice(0, -1) + ']'
+ }
+}
+
+function genInlineTemplate (el) {
+ var ast = el.children[0];
+ if (process.env.NODE_ENV !== 'production' && (
+ el.children.length > 1 || ast.type !== 1
+ )) {
+ warn$3('Inline-template components must have exactly one child element.');
+ }
+ if (ast.type === 1) {
+ var inlineRenderFns = generate(ast, currentOptions);
+ return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}")
+ }
+}
+
+function genScopedSlots (slots) {
+ return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + "])")
+}
+
+function genScopedSlot (key, el) {
+ return "[" + key + ",function(" + (String(el.attrsMap.scope)) + "){" +
+ "return " + (el.tag === 'template'
+ ? genChildren(el) || 'void 0'
+ : genElement(el)) + "}]"
+}
+
+function genChildren (el, checkSkip) {
+ var children = el.children;
+ if (children.length) {
+ var el$1 = children[0];
+ // optimize single v-for
+ if (children.length === 1 &&
+ el$1.for &&
+ el$1.tag !== 'template' &&
+ el$1.tag !== 'slot') {
+ return genElement(el$1)
+ }
+ var normalizationType = checkSkip ? getNormalizationType(children) : 0;
+ return ("[" + (children.map(genNode).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : ''))
+ }
+}
+
+// determine the normalization needed for the children array.
+// 0: no normalization needed
+// 1: simple normalization needed (possible 1-level deep nested array)
+// 2: full normalization needed
+function getNormalizationType (children) {
+ var res = 0;
+ for (var i = 0; i < children.length; i++) {
+ var el = children[i];
+ if (el.type !== 1) {
+ continue
+ }
+ if (needsNormalization(el) ||
+ (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) {
+ res = 2;
+ break
+ }
+ if (maybeComponent(el) ||
+ (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) {
+ res = 1;
+ }
+ }
+ return res
+}
+
+function needsNormalization (el) {
+ return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'
+}
+
+function maybeComponent (el) {
+ return !isPlatformReservedTag$1(el.tag)
+}
+
+function genNode (node) {
+ if (node.type === 1) {
+ return genElement(node)
+ } else {
+ return genText(node)
+ }
+}
+
+function genText (text) {
+ return ("_v(" + (text.type === 2
+ ? text.expression // no need for () because already wrapped in _s()
+ : transformSpecialNewlines(JSON.stringify(text.text))) + ")")
+}
+
+function genSlot (el) {
+ var slotName = el.slotName || '"default"';
+ var children = genChildren(el);
+ var res = "_t(" + slotName + (children ? ("," + children) : '');
+ var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}");
+ var bind$$1 = el.attrsMap['v-bind'];
+ if ((attrs || bind$$1) && !children) {
+ res += ",null";
+ }
+ if (attrs) {
+ res += "," + attrs;
+ }
+ if (bind$$1) {
+ res += (attrs ? '' : ',null') + "," + bind$$1;
+ }
+ return res + ')'
+}
+
+// componentName is el.component, take it as argument to shun flow's pessimistic refinement
+function genComponent (componentName, el) {
+ var children = el.inlineTemplate ? null : genChildren(el, true);
+ return ("_c(" + componentName + "," + (genData(el)) + (children ? ("," + children) : '') + ")")
+}
+
+function genProps (props) {
+ var res = '';
+ for (var i = 0; i < props.length; i++) {
+ var prop = props[i];
+ res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ",";
+ }
+ return res.slice(0, -1)
+}
+
+// #3895, #4268
+function transformSpecialNewlines (text) {
+ return text
+ .replace(/\u2028/g, '\\u2028')
+ .replace(/\u2029/g, '\\u2029')
+}
+
+/* */
+
+// these keywords should not appear inside expressions, but operators like
+// typeof, instanceof and in are allowed
+var prohibitedKeywordRE = new RegExp('\\b' + (
+ 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
+ 'super,throw,while,yield,delete,export,import,return,switch,default,' +
+ 'extends,finally,continue,debugger,function,arguments'
+).split(',').join('\\b|\\b') + '\\b');
+
+// these unary operators should not be used as property/method names
+var unaryOperatorsRE = new RegExp('\\b' + (
+ 'delete,typeof,void'
+).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)');
+
+// check valid identifier for v-for
+var identRE = /[A-Za-z_$][\w$]*/;
+
+// strip strings in expressions
+var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
+
+// detect problematic expressions in a template
+function detectErrors (ast) {
+ var errors = [];
+ if (ast) {
+ checkNode(ast, errors);
+ }
+ return errors
+}
+
+function checkNode (node, errors) {
+ if (node.type === 1) {
+ for (var name in node.attrsMap) {
+ if (dirRE.test(name)) {
+ var value = node.attrsMap[name];
+ if (value) {
+ if (name === 'v-for') {
+ checkFor(node, ("v-for=\"" + value + "\""), errors);
+ } else if (onRE.test(name)) {
+ checkEvent(value, (name + "=\"" + value + "\""), errors);
+ } else {
+ checkExpression(value, (name + "=\"" + value + "\""), errors);
+ }
+ }
+ }
+ }
+ if (node.children) {
+ for (var i = 0; i < node.children.length; i++) {
+ checkNode(node.children[i], errors);
+ }
+ }
+ } else if (node.type === 2) {
+ checkExpression(node.expression, node.text, errors);
+ }
+}
+
+function checkEvent (exp, text, errors) {
+ var keywordMatch = exp.replace(stripStringRE, '').match(unaryOperatorsRE);
+ if (keywordMatch) {
+ errors.push(
+ "avoid using JavaScript unary operator as property name: " +
+ "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
+ );
+ }
+ checkExpression(exp, text, errors);
+}
+
+function checkFor (node, text, errors) {
+ checkExpression(node.for || '', text, errors);
+ checkIdentifier(node.alias, 'v-for alias', text, errors);
+ checkIdentifier(node.iterator1, 'v-for iterator', text, errors);
+ checkIdentifier(node.iterator2, 'v-for iterator', text, errors);
+}
+
+function checkIdentifier (ident, type, text, errors) {
+ if (typeof ident === 'string' && !identRE.test(ident)) {
+ errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())));
+ }
+}
+
+function checkExpression (exp, text, errors) {
+ try {
+ new Function(("return " + exp));
+ } catch (e) {
+ var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
+ if (keywordMatch) {
+ errors.push(
+ "avoid using JavaScript keyword as property name: " +
+ "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
+ );
+ } else {
+ errors.push(("invalid expression: " + (text.trim())));
+ }
+ }
+}
+
+/* */
+
+function baseCompile (
+ template,
+ options
+) {
+ var ast = parse(template.trim(), options);
+ optimize(ast, options);
+ var code = generate(ast, options);
+ return {
+ ast: ast,
+ render: code.render,
+ staticRenderFns: code.staticRenderFns
+ }
+}
+
+function makeFunction (code, errors) {
+ try {
+ return new Function(code)
+ } catch (err) {
+ errors.push({ err: err, code: code });
+ return noop
+ }
+}
+
+function createCompiler (baseOptions) {
+ var functionCompileCache = Object.create(null);
+
+ function compile (
+ template,
+ options
+ ) {
+ var finalOptions = Object.create(baseOptions);
+ var errors = [];
+ var tips = [];
+ finalOptions.warn = function (msg, tip$$1) {
+ (tip$$1 ? tips : errors).push(msg);
+ };
+
+ if (options) {
+ // merge custom modules
+ if (options.modules) {
+ finalOptions.modules = (baseOptions.modules || []).concat(options.modules);
+ }
+ // merge custom directives
+ if (options.directives) {
+ finalOptions.directives = extend(
+ Object.create(baseOptions.directives),
+ options.directives
+ );
+ }
+ // copy other options
+ for (var key in options) {
+ if (key !== 'modules' && key !== 'directives') {
+ finalOptions[key] = options[key];
+ }
+ }
+ }
+
+ var compiled = baseCompile(template, finalOptions);
+ if (process.env.NODE_ENV !== 'production') {
+ errors.push.apply(errors, detectErrors(compiled.ast));
+ }
+ compiled.errors = errors;
+ compiled.tips = tips;
+ return compiled
+ }
+
+ function compileToFunctions (
+ template,
+ options,
+ vm
+ ) {
+ options = options || {};
+
+ /* istanbul ignore if */
+ if (process.env.NODE_ENV !== 'production') {
+ // detect possible CSP restriction
+ try {
+ new Function('return 1');
+ } catch (e) {
+ if (e.toString().match(/unsafe-eval|CSP/)) {
+ warn(
+ 'It seems you are using the standalone build of Vue.js in an ' +
+ 'environment with Content Security Policy that prohibits unsafe-eval. ' +
+ 'The template compiler cannot work in this environment. Consider ' +
+ 'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
+ 'templates into render functions.'
+ );
+ }
+ }
+ }
+
+ // check cache
+ var key = options.delimiters
+ ? String(options.delimiters) + template
+ : template;
+ if (functionCompileCache[key]) {
+ return functionCompileCache[key]
+ }
+
+ // compile
+ var compiled = compile(template, options);
+
+ // check compilation errors/tips
+ if (process.env.NODE_ENV !== 'production') {
+ if (compiled.errors && compiled.errors.length) {
+ warn(
+ "Error compiling template:\n\n" + template + "\n\n" +
+ compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n',
+ vm
+ );
+ }
+ if (compiled.tips && compiled.tips.length) {
+ compiled.tips.forEach(function (msg) { return tip(msg, vm); });
+ }
+ }
+
+ // turn code into functions
+ var res = {};
+ var fnGenErrors = [];
+ res.render = makeFunction(compiled.render, fnGenErrors);
+ var l = compiled.staticRenderFns.length;
+ res.staticRenderFns = new Array(l);
+ for (var i = 0; i < l; i++) {
+ res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i], fnGenErrors);
+ }
+
+ // check function generation errors.
+ // this should only happen if there is a bug in the compiler itself.
+ // mostly for codegen development use
+ /* istanbul ignore if */
+ if (process.env.NODE_ENV !== 'production') {
+ if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
+ warn(
+ "Failed to generate render function:\n\n" +
+ fnGenErrors.map(function (ref) {
+ var err = ref.err;
+ var code = ref.code;
+
+ return ((err.toString()) + " in\n\n" + code + "\n");
+ }).join('\n'),
+ vm
+ );
+ }
+ }
+
+ return (functionCompileCache[key] = res)
+ }
+
+ return {
+ compile: compile,
+ compileToFunctions: compileToFunctions
+ }
+}
+
+/* */
+
+function transformNode (el, options) {
+ var warn = options.warn || baseWarn;
+ var staticClass = getAndRemoveAttr(el, 'class');
+ if (process.env.NODE_ENV !== 'production' && staticClass) {
+ var expression = parseText(staticClass, options.delimiters);
+ if (expression) {
+ warn(
+ "class=\"" + staticClass + "\": " +
+ 'Interpolation inside attributes has been removed. ' +
+ 'Use v-bind or the colon shorthand instead. For example, ' +
+ 'instead of
, use
.'
+ );
+ }
+ }
+ if (staticClass) {
+ el.staticClass = JSON.stringify(staticClass);
+ }
+ var classBinding = getBindingAttr(el, 'class', false /* getStatic */);
+ if (classBinding) {
+ el.classBinding = classBinding;
+ }
+}
+
+function genData$1 (el) {
+ var data = '';
+ if (el.staticClass) {
+ data += "staticClass:" + (el.staticClass) + ",";
+ }
+ if (el.classBinding) {
+ data += "class:" + (el.classBinding) + ",";
+ }
+ return data
+}
+
+var klass$1 = {
+ staticKeys: ['staticClass'],
+ transformNode: transformNode,
+ genData: genData$1
+};
+
+/* */
+
+function transformNode$1 (el, options) {
+ var warn = options.warn || baseWarn;
+ var staticStyle = getAndRemoveAttr(el, 'style');
+ if (staticStyle) {
+ /* istanbul ignore if */
+ if (process.env.NODE_ENV !== 'production') {
+ var expression = parseText(staticStyle, options.delimiters);
+ if (expression) {
+ warn(
+ "style=\"" + staticStyle + "\": " +
+ 'Interpolation inside attributes has been removed. ' +
+ 'Use v-bind or the colon shorthand instead. For example, ' +
+ 'instead of
, use
.'
+ );
+ }
+ }
+ el.staticStyle = JSON.stringify(parseStyleText(staticStyle));
+ }
+
+ var styleBinding = getBindingAttr(el, 'style', false /* getStatic */);
+ if (styleBinding) {
+ el.styleBinding = styleBinding;
+ }
+}
+
+function genData$2 (el) {
+ var data = '';
+ if (el.staticStyle) {
+ data += "staticStyle:" + (el.staticStyle) + ",";
+ }
+ if (el.styleBinding) {
+ data += "style:(" + (el.styleBinding) + "),";
+ }
+ return data
+}
+
+var style$1 = {
+ staticKeys: ['staticStyle'],
+ transformNode: transformNode$1,
+ genData: genData$2
+};
+
+var modules$1 = [
+ klass$1,
+ style$1
+];
+
+/* */
+
+function text (el, dir) {
+ if (dir.value) {
+ addProp(el, 'textContent', ("_s(" + (dir.value) + ")"));
+ }
+}
+
+/* */
+
+function html (el, dir) {
+ if (dir.value) {
+ addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"));
+ }
+}
+
+var directives$1 = {
+ model: model,
+ text: text,
+ html: html
+};
+
+/* */
+
+var baseOptions = {
+ expectHTML: true,
+ modules: modules$1,
+ directives: directives$1,
+ isPreTag: isPreTag,
+ isUnaryTag: isUnaryTag,
+ mustUseProp: mustUseProp,
+ canBeLeftOpenTag: canBeLeftOpenTag,
+ isReservedTag: isReservedTag,
+ getTagNamespace: getTagNamespace,
+ staticKeys: genStaticKeys(modules$1)
+};
+
+var ref$1 = createCompiler(baseOptions);
+var compileToFunctions = ref$1.compileToFunctions;
+
+/* */
+
+var idToTemplate = cached(function (id) {
+ var el = query(id);
+ return el && el.innerHTML
+});
+
+var mount = Vue$3.prototype.$mount;
+Vue$3.prototype.$mount = function (
+ el,
+ hydrating
+) {
+ el = el && query(el);
+
+ /* istanbul ignore if */
+ if (el === document.body || el === document.documentElement) {
+ process.env.NODE_ENV !== 'production' && warn(
+ "Do not mount Vue to or - mount to normal elements instead."
+ );
+ return this
+ }
+
+ var options = this.$options;
+ // resolve template/el and convert to render function
+ if (!options.render) {
+ var template = options.template;
+ if (template) {
+ if (typeof template === 'string') {
+ if (template.charAt(0) === '#') {
+ template = idToTemplate(template);
+ /* istanbul ignore if */
+ if (process.env.NODE_ENV !== 'production' && !template) {
+ warn(
+ ("Template element not found or is empty: " + (options.template)),
+ this
+ );
+ }
+ }
+ } else if (template.nodeType) {
+ template = template.innerHTML;
+ } else {
+ if (process.env.NODE_ENV !== 'production') {
+ warn('invalid template option:' + template, this);
+ }
+ return this
+ }
+ } else if (el) {
+ template = getOuterHTML(el);
+ }
+ if (template) {
+ /* istanbul ignore if */
+ if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
+ mark('compile');
+ }
+
+ var ref = compileToFunctions(template, {
+ shouldDecodeNewlines: shouldDecodeNewlines,
+ delimiters: options.delimiters
+ }, this);
+ var render = ref.render;
+ var staticRenderFns = ref.staticRenderFns;
+ options.render = render;
+ options.staticRenderFns = staticRenderFns;
+
+ /* istanbul ignore if */
+ if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
+ mark('compile end');
+ measure(((this._name) + " compile"), 'compile', 'compile end');
+ }
+ }
+ }
+ return mount.call(this, el, hydrating)
+};
+
+/**
+ * Get outerHTML of elements, taking care
+ * of SVG elements in IE as well.
+ */
+function getOuterHTML (el) {
+ if (el.outerHTML) {
+ return el.outerHTML
+ } else {
+ var container = document.createElement('div');
+ container.appendChild(el.cloneNode(true));
+ return container.innerHTML
+ }
+}
+
+Vue$3.compile = compileToFunctions;
+
+module.exports = Vue$3;
+
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3)))
+
+/***/ }),
+/* 5 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__promise_js__ = __webpack_require__(1);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_js__ = __webpack_require__(0);
+
+
+
+/**
+ * OAuth2 popup management class
+ *
+ * @author Sahat Yalkabov
+ * @copyright Class mostly taken from https://github.com/sahat/satellizer
+ * and adjusted to fit vue-authenticate library
+ */
+class OAuthPopup {
+ constructor(url, name, popupOptions) {
+ this.popup = null;
+ this.url = url;
+ this.name = name;
+ this.popupOptions = popupOptions;
+ }
+
+ open(redirectUri, skipPooling) {
+ try {
+ this.popup = window.open(this.url, this.name, this._stringifyOptions());
+ if (this.popup && this.popup.focus) {
+ this.popup.focus();
+ }
+
+ if (skipPooling) {
+ return __WEBPACK_IMPORTED_MODULE_0__promise_js__["a" /* default */].resolve();
+ } else {
+ return this.pooling(redirectUri);
+ }
+ } catch (e) {
+ return __WEBPACK_IMPORTED_MODULE_0__promise_js__["a" /* default */].reject(new Error('OAuth popup error occurred'));
+ }
+ }
+
+ pooling(redirectUri) {
+ return new __WEBPACK_IMPORTED_MODULE_0__promise_js__["a" /* default */]((resolve, reject) => {
+ const redirectUriParser = document.createElement('a');
+ redirectUriParser.href = redirectUri;
+ const redirectUriPath = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["h" /* getFullUrlPath */])(redirectUriParser);
+
+ let poolingInterval = setInterval(() => {
+ if (!this.popup || this.popup.closed || this.popup.closed === undefined) {
+ clearInterval(poolingInterval);
+ poolingInterval = null;
+ reject(new Error('Auth popup window closed'));
+ }
+
+ try {
+ const popupWindowPath = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["h" /* getFullUrlPath */])(this.popup.location);
+
+ if (popupWindowPath === redirectUriPath) {
+ if (this.popup.location.search || this.popup.location.hash) {
+ const query = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["i" /* parseQueryString */])(this.popup.location.search.substring(1).replace(/\/$/, ''));
+ const hash = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["i" /* parseQueryString */])(this.popup.location.hash.substring(1).replace(/[\/$]/, ''));
+ let params = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["a" /* objectExtend */])({}, query);
+ params = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["a" /* objectExtend */])(params, hash);
+
+ if (params.error) {
+ reject(new Error(params.error));
+ } else {
+ resolve(params);
+ }
+ } else {
+ reject(new Error('OAuth redirect has occurred but no query or hash parameters were found.'));
+ }
+
+ clearInterval(poolingInterval);
+ poolingInterval = null;
+ this.popup.close();
+ }
+ } catch (e) {
+ // Ignore DOMException: Blocked a frame with origin from accessing a cross-origin frame.
+ }
+ }, 250);
+ });
+ }
+
+ _stringifyOptions() {
+ let options = [];
+ for (var optionKey in this.popupOptions) {
+ options.push(`${optionKey}=${this.popupOptions[optionKey]}`);
+ }
+ return options.join(',');
+ }
+}
+/* harmony export (immutable) */ __webpack_exports__["a"] = OAuthPopup;
+
+
+/***/ }),
+/* 6 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_js__ = __webpack_require__(0);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__promise_js__ = __webpack_require__(1);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__auth_js__ = __webpack_require__(9);
+
+
+
+
+/**
+ * VueAuthenticate plugin
+ * @param {Object} Vue
+ */
+function plugin(Vue, options) {
+ if (plugin.installed) {
+ return;
+ }
+
+ Object.defineProperties(Vue.prototype, {
+ $auth: {
+ get() {
+ // vue-resource module not found, throw error
+ if (!this.$http) {
+ throw new Error('vue-resource instance not found');
+ }
+
+ return new __WEBPACK_IMPORTED_MODULE_2__auth_js__["a" /* default */](this.$http, options);
+ }
+ }
+ });
+}
+
+/* harmony default export */ __webpack_exports__["a"] = (plugin);
+
+/***/ }),
+/* 7 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+/*!
+ * vue-resource v1.2.1
+ * https://github.com/pagekit/vue-resource
+ * Released under the MIT License.
+ */
+
+
+
+/**
+ * Promises/A+ polyfill v1.1.4 (https://github.com/bramstein/promis)
+ */
+
+var RESOLVED = 0;
+var REJECTED = 1;
+var PENDING = 2;
+
+function Promise$1(executor) {
+
+ this.state = PENDING;
+ this.value = undefined;
+ this.deferred = [];
+
+ var promise = this;
+
+ try {
+ executor(function (x) {
+ promise.resolve(x);
+ }, function (r) {
+ promise.reject(r);
+ });
+ } catch (e) {
+ promise.reject(e);
+ }
+}
+
+Promise$1.reject = function (r) {
+ return new Promise$1(function (resolve, reject) {
+ reject(r);
+ });
+};
+
+Promise$1.resolve = function (x) {
+ return new Promise$1(function (resolve, reject) {
+ resolve(x);
+ });
+};
+
+Promise$1.all = function all(iterable) {
+ return new Promise$1(function (resolve, reject) {
+ var count = 0, result = [];
+
+ if (iterable.length === 0) {
+ resolve(result);
+ }
+
+ function resolver(i) {
+ return function (x) {
+ result[i] = x;
+ count += 1;
+
+ if (count === iterable.length) {
+ resolve(result);
+ }
+ };
+ }
+
+ for (var i = 0; i < iterable.length; i += 1) {
+ Promise$1.resolve(iterable[i]).then(resolver(i), reject);
+ }
+ });
+};
+
+Promise$1.race = function race(iterable) {
+ return new Promise$1(function (resolve, reject) {
+ for (var i = 0; i < iterable.length; i += 1) {
+ Promise$1.resolve(iterable[i]).then(resolve, reject);
+ }
+ });
+};
+
+var p$1 = Promise$1.prototype;
+
+p$1.resolve = function resolve(x) {
+ var promise = this;
+
+ if (promise.state === PENDING) {
+ if (x === promise) {
+ throw new TypeError('Promise settled with itself.');
+ }
+
+ var called = false;
+
+ try {
+ var then = x && x['then'];
+
+ if (x !== null && typeof x === 'object' && typeof then === 'function') {
+ then.call(x, function (x) {
+ if (!called) {
+ promise.resolve(x);
+ }
+ called = true;
+
+ }, function (r) {
+ if (!called) {
+ promise.reject(r);
+ }
+ called = true;
+ });
+ return;
+ }
+ } catch (e) {
+ if (!called) {
+ promise.reject(e);
+ }
+ return;
+ }
+
+ promise.state = RESOLVED;
+ promise.value = x;
+ promise.notify();
+ }
+};
+
+p$1.reject = function reject(reason) {
+ var promise = this;
+
+ if (promise.state === PENDING) {
+ if (reason === promise) {
+ throw new TypeError('Promise settled with itself.');
+ }
+
+ promise.state = REJECTED;
+ promise.value = reason;
+ promise.notify();
+ }
+};
+
+p$1.notify = function notify() {
+ var promise = this;
+
+ nextTick(function () {
+ if (promise.state !== PENDING) {
+ while (promise.deferred.length) {
+ var deferred = promise.deferred.shift(),
+ onResolved = deferred[0],
+ onRejected = deferred[1],
+ resolve = deferred[2],
+ reject = deferred[3];
+
+ try {
+ if (promise.state === RESOLVED) {
+ if (typeof onResolved === 'function') {
+ resolve(onResolved.call(undefined, promise.value));
+ } else {
+ resolve(promise.value);
+ }
+ } else if (promise.state === REJECTED) {
+ if (typeof onRejected === 'function') {
+ resolve(onRejected.call(undefined, promise.value));
+ } else {
+ reject(promise.value);
+ }
+ }
+ } catch (e) {
+ reject(e);
+ }
+ }
+ }
+ });
+};
+
+p$1.then = function then(onResolved, onRejected) {
+ var promise = this;
+
+ return new Promise$1(function (resolve, reject) {
+ promise.deferred.push([onResolved, onRejected, resolve, reject]);
+ promise.notify();
+ });
+};
+
+p$1.catch = function (onRejected) {
+ return this.then(undefined, onRejected);
+};
+
+/**
+ * Promise adapter.
+ */
+
+if (typeof Promise === 'undefined') {
+ window.Promise = Promise$1;
+}
+
+function PromiseObj(executor, context) {
+
+ if (executor instanceof Promise) {
+ this.promise = executor;
+ } else {
+ this.promise = new Promise(executor.bind(context));
+ }
+
+ this.context = context;
+}
+
+PromiseObj.all = function (iterable, context) {
+ return new PromiseObj(Promise.all(iterable), context);
+};
+
+PromiseObj.resolve = function (value, context) {
+ return new PromiseObj(Promise.resolve(value), context);
+};
+
+PromiseObj.reject = function (reason, context) {
+ return new PromiseObj(Promise.reject(reason), context);
+};
+
+PromiseObj.race = function (iterable, context) {
+ return new PromiseObj(Promise.race(iterable), context);
+};
+
+var p = PromiseObj.prototype;
+
+p.bind = function (context) {
+ this.context = context;
+ return this;
+};
+
+p.then = function (fulfilled, rejected) {
+
+ if (fulfilled && fulfilled.bind && this.context) {
+ fulfilled = fulfilled.bind(this.context);
+ }
+
+ if (rejected && rejected.bind && this.context) {
+ rejected = rejected.bind(this.context);
+ }
+
+ return new PromiseObj(this.promise.then(fulfilled, rejected), this.context);
+};
+
+p.catch = function (rejected) {
+
+ if (rejected && rejected.bind && this.context) {
+ rejected = rejected.bind(this.context);
+ }
+
+ return new PromiseObj(this.promise.catch(rejected), this.context);
+};
+
+p.finally = function (callback) {
+
+ return this.then(function (value) {
+ callback.call(this);
+ return value;
+ }, function (reason) {
+ callback.call(this);
+ return Promise.reject(reason);
+ }
+ );
+};
+
+/**
+ * Utility functions.
+ */
+
+var ref = {};
+var hasOwnProperty = ref.hasOwnProperty;
+
+var ref$1 = [];
+var slice = ref$1.slice;
+var debug = false;
+var ntick;
+
+var inBrowser = typeof window !== 'undefined';
+
+var Util = function (ref) {
+ var config = ref.config;
+ var nextTick = ref.nextTick;
+
+ ntick = nextTick;
+ debug = config.debug || !config.silent;
+};
+
+function warn(msg) {
+ if (typeof console !== 'undefined' && debug) {
+ console.warn('[VueResource warn]: ' + msg);
+ }
+}
+
+function error(msg) {
+ if (typeof console !== 'undefined') {
+ console.error(msg);
+ }
+}
+
+function nextTick(cb, ctx) {
+ return ntick(cb, ctx);
+}
+
+function trim(str) {
+ return str ? str.replace(/^\s*|\s*$/g, '') : '';
+}
+
+function toLower(str) {
+ return str ? str.toLowerCase() : '';
+}
+
+function toUpper(str) {
+ return str ? str.toUpperCase() : '';
+}
+
+var isArray = Array.isArray;
+
+function isString(val) {
+ return typeof val === 'string';
+}
+
+
+
+function isFunction(val) {
+ return typeof val === 'function';
+}
+
+function isObject(obj) {
+ return obj !== null && typeof obj === 'object';
+}
+
+function isPlainObject(obj) {
+ return isObject(obj) && Object.getPrototypeOf(obj) == Object.prototype;
+}
+
+function isBlob(obj) {
+ return typeof Blob !== 'undefined' && obj instanceof Blob;
+}
+
+function isFormData(obj) {
+ return typeof FormData !== 'undefined' && obj instanceof FormData;
+}
+
+function when(value, fulfilled, rejected) {
+
+ var promise = PromiseObj.resolve(value);
+
+ if (arguments.length < 2) {
+ return promise;
+ }
+
+ return promise.then(fulfilled, rejected);
+}
+
+function options(fn, obj, opts) {
+
+ opts = opts || {};
+
+ if (isFunction(opts)) {
+ opts = opts.call(obj);
+ }
+
+ return merge(fn.bind({$vm: obj, $options: opts}), fn, {$options: opts});
+}
+
+function each(obj, iterator) {
+
+ var i, key;
+
+ if (isArray(obj)) {
+ for (i = 0; i < obj.length; i++) {
+ iterator.call(obj[i], obj[i], i);
+ }
+ } else if (isObject(obj)) {
+ for (key in obj) {
+ if (hasOwnProperty.call(obj, key)) {
+ iterator.call(obj[key], obj[key], key);
+ }
+ }
+ }
+
+ return obj;
+}
+
+var assign = Object.assign || _assign;
+
+function merge(target) {
+
+ var args = slice.call(arguments, 1);
+
+ args.forEach(function (source) {
+ _merge(target, source, true);
+ });
+
+ return target;
+}
+
+function defaults(target) {
+
+ var args = slice.call(arguments, 1);
+
+ args.forEach(function (source) {
+
+ for (var key in source) {
+ if (target[key] === undefined) {
+ target[key] = source[key];
+ }
+ }
+
+ });
+
+ return target;
+}
+
+function _assign(target) {
+
+ var args = slice.call(arguments, 1);
+
+ args.forEach(function (source) {
+ _merge(target, source);
+ });
+
+ return target;
+}
+
+function _merge(target, source, deep) {
+ for (var key in source) {
+ if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
+ if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
+ target[key] = {};
+ }
+ if (isArray(source[key]) && !isArray(target[key])) {
+ target[key] = [];
+ }
+ _merge(target[key], source[key], deep);
+ } else if (source[key] !== undefined) {
+ target[key] = source[key];
+ }
+ }
+}
+
+/**
+ * Root Prefix Transform.
+ */
+
+var root = function (options$$1, next) {
+
+ var url = next(options$$1);
+
+ if (isString(options$$1.root) && !url.match(/^(https?:)?\//)) {
+ url = options$$1.root + '/' + url;
+ }
+
+ return url;
+};
+
+/**
+ * Query Parameter Transform.
+ */
+
+var query = function (options$$1, next) {
+
+ var urlParams = Object.keys(Url.options.params), query = {}, url = next(options$$1);
+
+ each(options$$1.params, function (value, key) {
+ if (urlParams.indexOf(key) === -1) {
+ query[key] = value;
+ }
+ });
+
+ query = Url.params(query);
+
+ if (query) {
+ url += (url.indexOf('?') == -1 ? '?' : '&') + query;
+ }
+
+ return url;
+};
+
+/**
+ * URL Template v2.0.6 (https://github.com/bramstein/url-template)
+ */
+
+function expand(url, params, variables) {
+
+ var tmpl = parse(url), expanded = tmpl.expand(params);
+
+ if (variables) {
+ variables.push.apply(variables, tmpl.vars);
+ }
+
+ return expanded;
+}
+
+function parse(template) {
+
+ var operators = ['+', '#', '.', '/', ';', '?', '&'], variables = [];
+
+ return {
+ vars: variables,
+ expand: function expand(context) {
+ return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
+ if (expression) {
+
+ var operator = null, values = [];
+
+ if (operators.indexOf(expression.charAt(0)) !== -1) {
+ operator = expression.charAt(0);
+ expression = expression.substr(1);
+ }
+
+ expression.split(/,/g).forEach(function (variable) {
+ var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
+ values.push.apply(values, getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
+ variables.push(tmp[1]);
+ });
+
+ if (operator && operator !== '+') {
+
+ var separator = ',';
+
+ if (operator === '?') {
+ separator = '&';
+ } else if (operator !== '#') {
+ separator = operator;
+ }
+
+ return (values.length !== 0 ? operator : '') + values.join(separator);
+ } else {
+ return values.join(',');
+ }
+
+ } else {
+ return encodeReserved(literal);
+ }
+ });
+ }
+ };
+}
+
+function getValues(context, operator, key, modifier) {
+
+ var value = context[key], result = [];
+
+ if (isDefined(value) && value !== '') {
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
+ value = value.toString();
+
+ if (modifier && modifier !== '*') {
+ value = value.substring(0, parseInt(modifier, 10));
+ }
+
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
+ } else {
+ if (modifier === '*') {
+ if (Array.isArray(value)) {
+ value.filter(isDefined).forEach(function (value) {
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
+ });
+ } else {
+ Object.keys(value).forEach(function (k) {
+ if (isDefined(value[k])) {
+ result.push(encodeValue(operator, value[k], k));
+ }
+ });
+ }
+ } else {
+ var tmp = [];
+
+ if (Array.isArray(value)) {
+ value.filter(isDefined).forEach(function (value) {
+ tmp.push(encodeValue(operator, value));
+ });
+ } else {
+ Object.keys(value).forEach(function (k) {
+ if (isDefined(value[k])) {
+ tmp.push(encodeURIComponent(k));
+ tmp.push(encodeValue(operator, value[k].toString()));
+ }
+ });
+ }
+
+ if (isKeyOperator(operator)) {
+ result.push(encodeURIComponent(key) + '=' + tmp.join(','));
+ } else if (tmp.length !== 0) {
+ result.push(tmp.join(','));
+ }
+ }
+ }
+ } else {
+ if (operator === ';') {
+ result.push(encodeURIComponent(key));
+ } else if (value === '' && (operator === '&' || operator === '?')) {
+ result.push(encodeURIComponent(key) + '=');
+ } else if (value === '') {
+ result.push('');
+ }
+ }
+
+ return result;
+}
+
+function isDefined(value) {
+ return value !== undefined && value !== null;
+}
+
+function isKeyOperator(operator) {
+ return operator === ';' || operator === '&' || operator === '?';
+}
+
+function encodeValue(operator, value, key) {
+
+ value = (operator === '+' || operator === '#') ? encodeReserved(value) : encodeURIComponent(value);
+
+ if (key) {
+ return encodeURIComponent(key) + '=' + value;
+ } else {
+ return value;
+ }
+}
+
+function encodeReserved(str) {
+ return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
+ if (!/%[0-9A-Fa-f]/.test(part)) {
+ part = encodeURI(part);
+ }
+ return part;
+ }).join('');
+}
+
+/**
+ * URL Template (RFC 6570) Transform.
+ */
+
+var template = function (options) {
+
+ var variables = [], url = expand(options.url, options.params, variables);
+
+ variables.forEach(function (key) {
+ delete options.params[key];
+ });
+
+ return url;
+};
+
+/**
+ * Service for URL templating.
+ */
+
+function Url(url, params) {
+
+ var self = this || {}, options$$1 = url, transform;
+
+ if (isString(url)) {
+ options$$1 = {url: url, params: params};
+ }
+
+ options$$1 = merge({}, Url.options, self.$options, options$$1);
+
+ Url.transforms.forEach(function (handler) {
+ transform = factory(handler, transform, self.$vm);
+ });
+
+ return transform(options$$1);
+}
+
+/**
+ * Url options.
+ */
+
+Url.options = {
+ url: '',
+ root: null,
+ params: {}
+};
+
+/**
+ * Url transforms.
+ */
+
+Url.transforms = [template, query, root];
+
+/**
+ * Encodes a Url parameter string.
+ *
+ * @param {Object} obj
+ */
+
+Url.params = function (obj) {
+
+ var params = [], escape = encodeURIComponent;
+
+ params.add = function (key, value) {
+
+ if (isFunction(value)) {
+ value = value();
+ }
+
+ if (value === null) {
+ value = '';
+ }
+
+ this.push(escape(key) + '=' + escape(value));
+ };
+
+ serialize(params, obj);
+
+ return params.join('&').replace(/%20/g, '+');
+};
+
+/**
+ * Parse a URL and return its components.
+ *
+ * @param {String} url
+ */
+
+Url.parse = function (url) {
+
+ var el = document.createElement('a');
+
+ if (document.documentMode) {
+ el.href = url;
+ url = el.href;
+ }
+
+ el.href = url;
+
+ return {
+ href: el.href,
+ protocol: el.protocol ? el.protocol.replace(/:$/, '') : '',
+ port: el.port,
+ host: el.host,
+ hostname: el.hostname,
+ pathname: el.pathname.charAt(0) === '/' ? el.pathname : '/' + el.pathname,
+ search: el.search ? el.search.replace(/^\?/, '') : '',
+ hash: el.hash ? el.hash.replace(/^#/, '') : ''
+ };
+};
+
+function factory(handler, next, vm) {
+ return function (options$$1) {
+ return handler.call(vm, options$$1, next);
+ };
+}
+
+function serialize(params, obj, scope) {
+
+ var array = isArray(obj), plain = isPlainObject(obj), hash;
+
+ each(obj, function (value, key) {
+
+ hash = isObject(value) || isArray(value);
+
+ if (scope) {
+ key = scope + '[' + (plain || hash ? key : '') + ']';
+ }
+
+ if (!scope && array) {
+ params.add(value.name, value.value);
+ } else if (hash) {
+ serialize(params, value, key);
+ } else {
+ params.add(key, value);
+ }
+ });
+}
+
+/**
+ * XDomain client (Internet Explorer).
+ */
+
+var xdrClient = function (request) {
+ return new PromiseObj(function (resolve) {
+
+ var xdr = new XDomainRequest(), handler = function (ref) {
+ var type = ref.type;
+
+
+ var status = 0;
+
+ if (type === 'load') {
+ status = 200;
+ } else if (type === 'error') {
+ status = 500;
+ }
+
+ resolve(request.respondWith(xdr.responseText, {status: status}));
+ };
+
+ request.abort = function () { return xdr.abort(); };
+
+ xdr.open(request.method, request.getUrl());
+
+ if (request.timeout) {
+ xdr.timeout = request.timeout;
+ }
+
+ xdr.onload = handler;
+ xdr.onabort = handler;
+ xdr.onerror = handler;
+ xdr.ontimeout = handler;
+ xdr.onprogress = function () {};
+ xdr.send(request.getBody());
+ });
+};
+
+/**
+ * CORS Interceptor.
+ */
+
+var SUPPORTS_CORS = inBrowser && 'withCredentials' in new XMLHttpRequest();
+
+var cors = function (request, next) {
+
+ if (inBrowser) {
+
+ var orgUrl = Url.parse(location.href);
+ var reqUrl = Url.parse(request.getUrl());
+
+ if (reqUrl.protocol !== orgUrl.protocol || reqUrl.host !== orgUrl.host) {
+
+ request.crossOrigin = true;
+ request.emulateHTTP = false;
+
+ if (!SUPPORTS_CORS) {
+ request.client = xdrClient;
+ }
+ }
+ }
+
+ next();
+};
+
+/**
+ * Body Interceptor.
+ */
+
+var body = function (request, next) {
+
+ if (isFormData(request.body)) {
+
+ request.headers.delete('Content-Type');
+
+ } else if (isObject(request.body) || isArray(request.body)) {
+
+ if (request.emulateJSON) {
+ request.body = Url.params(request.body);
+ request.headers.set('Content-Type', 'application/x-www-form-urlencoded');
+ } else {
+ request.body = JSON.stringify(request.body);
+ }
+ }
+
+ next(function (response) {
+
+ Object.defineProperty(response, 'data', {
+
+ get: function get() {
+ return this.body;
+ },
+
+ set: function set(body) {
+ this.body = body;
+ }
+
+ });
+
+ return response.bodyText ? when(response.text(), function (text) {
+
+ var type = response.headers.get('Content-Type') || '';
+
+ if (type.indexOf('application/json') === 0 || isJson(text)) {
+
+ try {
+ response.body = JSON.parse(text);
+ } catch (e) {
+ response.body = null;
+ }
+
+ } else {
+ response.body = text;
+ }
+
+ return response;
+
+ }) : response;
+
+ });
+};
+
+function isJson(str) {
+
+ var start = str.match(/^\[|^\{(?!\{)/), end = {'[': /]$/, '{': /}$/};
+
+ return start && end[start[0]].test(str);
+}
+
+/**
+ * JSONP client (Browser).
+ */
+
+var jsonpClient = function (request) {
+ return new PromiseObj(function (resolve) {
+
+ var name = request.jsonp || 'callback', callback = request.jsonpCallback || '_jsonp' + Math.random().toString(36).substr(2), body = null, handler, script;
+
+ handler = function (ref) {
+ var type = ref.type;
+
+
+ var status = 0;
+
+ if (type === 'load' && body !== null) {
+ status = 200;
+ } else if (type === 'error') {
+ status = 500;
+ }
+
+ if (status && window[callback]) {
+ delete window[callback];
+ document.body.removeChild(script);
+ }
+
+ resolve(request.respondWith(body, {status: status}));
+ };
+
+ window[callback] = function (result) {
+ body = JSON.stringify(result);
+ };
+
+ request.abort = function () {
+ handler({type: 'abort'});
+ };
+
+ request.params[name] = callback;
+
+ if (request.timeout) {
+ setTimeout(request.abort, request.timeout);
+ }
+
+ script = document.createElement('script');
+ script.src = request.getUrl();
+ script.type = 'text/javascript';
+ script.async = true;
+ script.onload = handler;
+ script.onerror = handler;
+
+ document.body.appendChild(script);
+ });
+};
+
+/**
+ * JSONP Interceptor.
+ */
+
+var jsonp = function (request, next) {
+
+ if (request.method == 'JSONP') {
+ request.client = jsonpClient;
+ }
+
+ next();
+};
+
+/**
+ * Before Interceptor.
+ */
+
+var before = function (request, next) {
+
+ if (isFunction(request.before)) {
+ request.before.call(this, request);
+ }
+
+ next();
+};
+
+/**
+ * HTTP method override Interceptor.
+ */
+
+var method = function (request, next) {
+
+ if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) {
+ request.headers.set('X-HTTP-Method-Override', request.method);
+ request.method = 'POST';
+ }
+
+ next();
+};
+
+/**
+ * Header Interceptor.
+ */
+
+var header = function (request, next) {
+
+ var headers = assign({}, Http.headers.common,
+ !request.crossOrigin ? Http.headers.custom : {},
+ Http.headers[toLower(request.method)]
+ );
+
+ each(headers, function (value, name) {
+ if (!request.headers.has(name)) {
+ request.headers.set(name, value);
+ }
+ });
+
+ next();
+};
+
+/**
+ * XMLHttp client (Browser).
+ */
+
+var SUPPORTS_BLOB = typeof Blob !== 'undefined' && typeof FileReader !== 'undefined';
+
+var xhrClient = function (request) {
+ return new PromiseObj(function (resolve) {
+
+ var xhr = new XMLHttpRequest(), handler = function (event) {
+
+ var response = request.respondWith(
+ 'response' in xhr ? xhr.response : xhr.responseText, {
+ status: xhr.status === 1223 ? 204 : xhr.status, // IE9 status bug
+ statusText: xhr.status === 1223 ? 'No Content' : trim(xhr.statusText)
+ }
+ );
+
+ each(trim(xhr.getAllResponseHeaders()).split('\n'), function (row) {
+ response.headers.append(row.slice(0, row.indexOf(':')), row.slice(row.indexOf(':') + 1));
+ });
+
+ resolve(response);
+ };
+
+ request.abort = function () { return xhr.abort(); };
+
+ if (request.progress) {
+ if (request.method === 'GET') {
+ xhr.addEventListener('progress', request.progress);
+ } else if (/^(POST|PUT)$/i.test(request.method)) {
+ xhr.upload.addEventListener('progress', request.progress);
+ }
+ }
+
+ xhr.open(request.method, request.getUrl(), true);
+
+ if (request.timeout) {
+ xhr.timeout = request.timeout;
+ }
+
+ if (request.credentials === true) {
+ xhr.withCredentials = true;
+ }
+
+ if (!request.crossOrigin) {
+ request.headers.set('X-Requested-With', 'XMLHttpRequest');
+ }
+
+ if ('responseType' in xhr && SUPPORTS_BLOB) {
+ xhr.responseType = 'blob';
+ }
+
+ request.headers.forEach(function (value, name) {
+ xhr.setRequestHeader(name, value);
+ });
+
+ xhr.onload = handler;
+ xhr.onabort = handler;
+ xhr.onerror = handler;
+ xhr.ontimeout = handler;
+ xhr.send(request.getBody());
+ });
+};
+
+/**
+ * Http client (Node).
+ */
+
+var nodeClient = function (request) {
+
+ var client = __webpack_require__(26);
+
+ return new PromiseObj(function (resolve) {
+
+ var url = request.getUrl();
+ var body = request.getBody();
+ var method = request.method;
+ var headers = {}, handler;
+
+ request.headers.forEach(function (value, name) {
+ headers[name] = value;
+ });
+
+ client(url, {body: body, method: method, headers: headers}).then(handler = function (resp) {
+
+ var response = request.respondWith(resp.body, {
+ status: resp.statusCode,
+ statusText: trim(resp.statusMessage)
+ }
+ );
+
+ each(resp.headers, function (value, name) {
+ response.headers.set(name, value);
+ });
+
+ resolve(response);
+
+ }, function (error$$1) { return handler(error$$1.response); });
+ });
+};
+
+/**
+ * Base client.
+ */
+
+var Client = function (context) {
+
+ var reqHandlers = [sendRequest], resHandlers = [], handler;
+
+ if (!isObject(context)) {
+ context = null;
+ }
+
+ function Client(request) {
+ return new PromiseObj(function (resolve) {
+
+ function exec() {
+
+ handler = reqHandlers.pop();
+
+ if (isFunction(handler)) {
+ handler.call(context, request, next);
+ } else {
+ warn(("Invalid interceptor of type " + (typeof handler) + ", must be a function"));
+ next();
+ }
+ }
+
+ function next(response) {
+
+ if (isFunction(response)) {
+
+ resHandlers.unshift(response);
+
+ } else if (isObject(response)) {
+
+ resHandlers.forEach(function (handler) {
+ response = when(response, function (response) {
+ return handler.call(context, response) || response;
+ });
+ });
+
+ when(response, resolve);
+
+ return;
+ }
+
+ exec();
+ }
+
+ exec();
+
+ }, context);
+ }
+
+ Client.use = function (handler) {
+ reqHandlers.push(handler);
+ };
+
+ return Client;
+};
+
+function sendRequest(request, resolve) {
+
+ var client = request.client || (inBrowser ? xhrClient : nodeClient);
+
+ resolve(client(request));
+}
+
+/**
+ * HTTP Headers.
+ */
+
+var Headers = function Headers(headers) {
+ var this$1 = this;
+
+
+ this.map = {};
+
+ each(headers, function (value, name) { return this$1.append(name, value); });
+};
+
+Headers.prototype.has = function has (name) {
+ return getName(this.map, name) !== null;
+};
+
+Headers.prototype.get = function get (name) {
+
+ var list = this.map[getName(this.map, name)];
+
+ return list ? list.join() : null;
+};
+
+Headers.prototype.getAll = function getAll (name) {
+ return this.map[getName(this.map, name)] || [];
+};
+
+Headers.prototype.set = function set (name, value) {
+ this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)];
+};
+
+Headers.prototype.append = function append (name, value){
+
+ var list = this.map[getName(this.map, name)];
+
+ if (list) {
+ list.push(trim(value));
+ } else {
+ this.set(name, value);
+ }
+};
+
+Headers.prototype.delete = function delete$1 (name){
+ delete this.map[getName(this.map, name)];
+};
+
+Headers.prototype.deleteAll = function deleteAll (){
+ this.map = {};
+};
+
+Headers.prototype.forEach = function forEach (callback, thisArg) {
+ var this$1 = this;
+
+ each(this.map, function (list, name) {
+ each(list, function (value) { return callback.call(thisArg, value, name, this$1); });
+ });
+};
+
+function getName(map, name) {
+ return Object.keys(map).reduce(function (prev, curr) {
+ return toLower(name) === toLower(curr) ? curr : prev;
+ }, null);
+}
+
+function normalizeName(name) {
+
+ if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
+ throw new TypeError('Invalid character in header field name');
+ }
+
+ return trim(name);
+}
+
+/**
+ * HTTP Response.
+ */
+
+var Response = function Response(body, ref) {
+ var url = ref.url;
+ var headers = ref.headers;
+ var status = ref.status;
+ var statusText = ref.statusText;
+
+
+ this.url = url;
+ this.ok = status >= 200 && status < 300;
+ this.status = status || 0;
+ this.statusText = statusText || '';
+ this.headers = new Headers(headers);
+ this.body = body;
+
+ if (isString(body)) {
+
+ this.bodyText = body;
+
+ } else if (isBlob(body)) {
+
+ this.bodyBlob = body;
+
+ if (isBlobText(body)) {
+ this.bodyText = blobText(body);
+ }
+ }
+};
+
+Response.prototype.blob = function blob () {
+ return when(this.bodyBlob);
+};
+
+Response.prototype.text = function text () {
+ return when(this.bodyText);
+};
+
+Response.prototype.json = function json () {
+ return when(this.text(), function (text) { return JSON.parse(text); });
+};
+
+function blobText(body) {
+ return new PromiseObj(function (resolve) {
+
+ var reader = new FileReader();
+
+ reader.readAsText(body);
+ reader.onload = function () {
+ resolve(reader.result);
+ };
+
+ });
+}
+
+function isBlobText(body) {
+ return body.type.indexOf('text') === 0 || body.type.indexOf('json') !== -1;
+}
+
+/**
+ * HTTP Request.
+ */
+
+var Request = function Request(options$$1) {
+
+ this.body = null;
+ this.params = {};
+
+ assign(this, options$$1, {
+ method: toUpper(options$$1.method || 'GET')
+ });
+
+ if (!(this.headers instanceof Headers)) {
+ this.headers = new Headers(this.headers);
+ }
+};
+
+Request.prototype.getUrl = function getUrl (){
+ return Url(this);
+};
+
+Request.prototype.getBody = function getBody (){
+ return this.body;
+};
+
+Request.prototype.respondWith = function respondWith (body, options$$1) {
+ return new Response(body, assign(options$$1 || {}, {url: this.getUrl()}));
+};
+
+/**
+ * Service for sending network requests.
+ */
+
+var COMMON_HEADERS = {'Accept': 'application/json, text/plain, */*'};
+var JSON_CONTENT_TYPE = {'Content-Type': 'application/json;charset=utf-8'};
+
+function Http(options$$1) {
+
+ var self = this || {}, client = Client(self.$vm);
+
+ defaults(options$$1 || {}, self.$options, Http.options);
+
+ Http.interceptors.forEach(function (handler) {
+ client.use(handler);
+ });
+
+ return client(new Request(options$$1)).then(function (response) {
+
+ return response.ok ? response : PromiseObj.reject(response);
+
+ }, function (response) {
+
+ if (response instanceof Error) {
+ error(response);
+ }
+
+ return PromiseObj.reject(response);
+ });
+}
+
+Http.options = {};
+
+Http.headers = {
+ put: JSON_CONTENT_TYPE,
+ post: JSON_CONTENT_TYPE,
+ patch: JSON_CONTENT_TYPE,
+ delete: JSON_CONTENT_TYPE,
+ common: COMMON_HEADERS,
+ custom: {}
+};
+
+Http.interceptors = [before, method, body, jsonp, header, cors];
+
+['get', 'delete', 'head', 'jsonp'].forEach(function (method$$1) {
+
+ Http[method$$1] = function (url, options$$1) {
+ return this(assign(options$$1 || {}, {url: url, method: method$$1}));
+ };
+
+});
+
+['post', 'put', 'patch'].forEach(function (method$$1) {
+
+ Http[method$$1] = function (url, body$$1, options$$1) {
+ return this(assign(options$$1 || {}, {url: url, method: method$$1, body: body$$1}));
+ };
+
+});
+
+/**
+ * Service for interacting with RESTful services.
+ */
+
+function Resource(url, params, actions, options$$1) {
+
+ var self = this || {}, resource = {};
+
+ actions = assign({},
+ Resource.actions,
+ actions
+ );
+
+ each(actions, function (action, name) {
+
+ action = merge({url: url, params: assign({}, params)}, options$$1, action);
+
+ resource[name] = function () {
+ return (self.$http || Http)(opts(action, arguments));
+ };
+ });
+
+ return resource;
+}
+
+function opts(action, args) {
+
+ var options$$1 = assign({}, action), params = {}, body;
+
+ switch (args.length) {
+
+ case 2:
+
+ params = args[0];
+ body = args[1];
+
+ break;
+
+ case 1:
+
+ if (/^(POST|PUT|PATCH)$/i.test(options$$1.method)) {
+ body = args[0];
+ } else {
+ params = args[0];
+ }
+
+ break;
+
+ case 0:
+
+ break;
+
+ default:
+
+ throw 'Expected up to 2 arguments [params, body], got ' + args.length + ' arguments';
+ }
+
+ options$$1.body = body;
+ options$$1.params = assign({}, options$$1.params, params);
+
+ return options$$1;
+}
+
+Resource.actions = {
+
+ get: {method: 'GET'},
+ save: {method: 'POST'},
+ query: {method: 'GET'},
+ update: {method: 'PUT'},
+ remove: {method: 'DELETE'},
+ delete: {method: 'DELETE'}
+
+};
+
+/**
+ * Install plugin.
+ */
+
+function plugin(Vue) {
+
+ if (plugin.installed) {
+ return;
+ }
+
+ Util(Vue);
+
+ Vue.url = Url;
+ Vue.http = Http;
+ Vue.resource = Resource;
+ Vue.Promise = PromiseObj;
+
+ Object.defineProperties(Vue.prototype, {
+
+ $url: {
+ get: function get() {
+ return options(Vue.url, this, this.$options.url);
+ }
+ },
+
+ $http: {
+ get: function get() {
+ return options(Vue.http, this, this.$options.http);
+ }
+ },
+
+ $resource: {
+ get: function get() {
+ return Vue.resource.bind(this);
+ }
+ },
+
+ $promise: {
+ get: function get() {
+ var this$1 = this;
+
+ return function (executor) { return new Vue.Promise(executor, this$1); };
+ }
+ }
+
+ });
+}
+
+if (typeof window !== 'undefined' && window.Vue) {
+ window.Vue.use(plugin);
+}
+
+module.exports = plugin;
+
+
+/***/ }),
+/* 8 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+/* WEBPACK VAR INJECTION */(function(process) {/**
+ * vue-router v2.2.1
+ * (c) 2017 Evan You
+ * @license MIT
+ */
+/* */
+
+function assert (condition, message) {
+ if (!condition) {
+ throw new Error(("[vue-router] " + message))
+ }
+}
+
+function warn (condition, message) {
+ if (!condition) {
+ typeof console !== 'undefined' && console.warn(("[vue-router] " + message));
+ }
+}
+
+var View = {
+ name: 'router-view',
+ functional: true,
+ props: {
+ name: {
+ type: String,
+ default: 'default'
+ }
+ },
+ render: function render (h, ref) {
+ var props = ref.props;
+ var children = ref.children;
+ var parent = ref.parent;
+ var data = ref.data;
+
+ data.routerView = true;
+
+ var name = props.name;
+ var route = parent.$route;
+ var cache = parent._routerViewCache || (parent._routerViewCache = {});
+
+ // determine current view depth, also check to see if the tree
+ // has been toggled inactive but kept-alive.
+ var depth = 0;
+ var inactive = false;
+ while (parent) {
+ if (parent.$vnode && parent.$vnode.data.routerView) {
+ depth++;
+ }
+ if (parent._inactive) {
+ inactive = true;
+ }
+ parent = parent.$parent;
+ }
+ data.routerViewDepth = depth;
+
+ // render previous view if the tree is inactive and kept-alive
+ if (inactive) {
+ return h(cache[name], data, children)
+ }
+
+ var matched = route.matched[depth];
+ // render empty node if no matched route
+ if (!matched) {
+ cache[name] = null;
+ return h()
+ }
+
+ var component = cache[name] = matched.components[name];
+
+ // inject instance registration hooks
+ var hooks = data.hook || (data.hook = {});
+ hooks.init = function (vnode) {
+ matched.instances[name] = vnode.child;
+ };
+ hooks.prepatch = function (oldVnode, vnode) {
+ matched.instances[name] = vnode.child;
+ };
+ hooks.destroy = function (vnode) {
+ if (matched.instances[name] === vnode.child) {
+ matched.instances[name] = undefined;
+ }
+ };
+
+ // resolve props
+ data.props = resolveProps(route, matched.props && matched.props[name]);
+
+ return h(component, data, children)
+ }
+};
+
+function resolveProps (route, config) {
+ switch (typeof config) {
+ case 'undefined':
+ return
+ case 'object':
+ return config
+ case 'function':
+ return config(route)
+ case 'boolean':
+ return config ? route.params : undefined
+ default:
+ warn(false, ("props in \"" + (route.path) + "\" is a " + (typeof config) + ", expecting an object, function or boolean."));
+ }
+}
+
+/* */
+
+var encodeReserveRE = /[!'()*]/g;
+var encodeReserveReplacer = function (c) { return '%' + c.charCodeAt(0).toString(16); };
+var commaRE = /%2C/g;
+
+// fixed encodeURIComponent which is more comformant to RFC3986:
+// - escapes [!'()*]
+// - preserve commas
+var encode = function (str) { return encodeURIComponent(str)
+ .replace(encodeReserveRE, encodeReserveReplacer)
+ .replace(commaRE, ','); };
+
+var decode = decodeURIComponent;
+
+function resolveQuery (
+ query,
+ extraQuery
+) {
+ if ( extraQuery === void 0 ) extraQuery = {};
+
+ if (query) {
+ var parsedQuery;
+ try {
+ parsedQuery = parseQuery(query);
+ } catch (e) {
+ process.env.NODE_ENV !== 'production' && warn(false, e.message);
+ parsedQuery = {};
+ }
+ for (var key in extraQuery) {
+ parsedQuery[key] = extraQuery[key];
+ }
+ return parsedQuery
+ } else {
+ return extraQuery
+ }
+}
+
+function parseQuery (query) {
+ var res = {};
+
+ query = query.trim().replace(/^(\?|#|&)/, '');
+
+ if (!query) {
+ return res
+ }
+
+ query.split('&').forEach(function (param) {
+ var parts = param.replace(/\+/g, ' ').split('=');
+ var key = decode(parts.shift());
+ var val = parts.length > 0
+ ? decode(parts.join('='))
+ : null;
+
+ if (res[key] === undefined) {
+ res[key] = val;
+ } else if (Array.isArray(res[key])) {
+ res[key].push(val);
+ } else {
+ res[key] = [res[key], val];
+ }
+ });
+
+ return res
+}
+
+function stringifyQuery (obj) {
+ var res = obj ? Object.keys(obj).map(function (key) {
+ var val = obj[key];
+
+ if (val === undefined) {
+ return ''
+ }
+
+ if (val === null) {
+ return encode(key)
+ }
+
+ if (Array.isArray(val)) {
+ var result = [];
+ val.slice().forEach(function (val2) {
+ if (val2 === undefined) {
+ return
+ }
+ if (val2 === null) {
+ result.push(encode(key));
+ } else {
+ result.push(encode(key) + '=' + encode(val2));
+ }
+ });
+ return result.join('&')
+ }
+
+ return encode(key) + '=' + encode(val)
+ }).filter(function (x) { return x.length > 0; }).join('&') : null;
+ return res ? ("?" + res) : ''
+}
+
+/* */
+
+var trailingSlashRE = /\/?$/;
+
+function createRoute (
+ record,
+ location,
+ redirectedFrom
+) {
+ var route = {
+ name: location.name || (record && record.name),
+ meta: (record && record.meta) || {},
+ path: location.path || '/',
+ hash: location.hash || '',
+ query: location.query || {},
+ params: location.params || {},
+ fullPath: getFullPath(location),
+ matched: record ? formatMatch(record) : []
+ };
+ if (redirectedFrom) {
+ route.redirectedFrom = getFullPath(redirectedFrom);
+ }
+ return Object.freeze(route)
+}
+
+// the starting route that represents the initial state
+var START = createRoute(null, {
+ path: '/'
+});
+
+function formatMatch (record) {
+ var res = [];
+ while (record) {
+ res.unshift(record);
+ record = record.parent;
+ }
+ return res
+}
+
+function getFullPath (ref) {
+ var path = ref.path;
+ var query = ref.query; if ( query === void 0 ) query = {};
+ var hash = ref.hash; if ( hash === void 0 ) hash = '';
+
+ return (path || '/') + stringifyQuery(query) + hash
+}
+
+function isSameRoute (a, b) {
+ if (b === START) {
+ return a === b
+ } else if (!b) {
+ return false
+ } else if (a.path && b.path) {
+ return (
+ a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') &&
+ a.hash === b.hash &&
+ isObjectEqual(a.query, b.query)
+ )
+ } else if (a.name && b.name) {
+ return (
+ a.name === b.name &&
+ a.hash === b.hash &&
+ isObjectEqual(a.query, b.query) &&
+ isObjectEqual(a.params, b.params)
+ )
+ } else {
+ return false
+ }
+}
+
+function isObjectEqual (a, b) {
+ if ( a === void 0 ) a = {};
+ if ( b === void 0 ) b = {};
+
+ var aKeys = Object.keys(a);
+ var bKeys = Object.keys(b);
+ if (aKeys.length !== bKeys.length) {
+ return false
+ }
+ return aKeys.every(function (key) { return String(a[key]) === String(b[key]); })
+}
+
+function isIncludedRoute (current, target) {
+ return (
+ current.path.replace(trailingSlashRE, '/').indexOf(
+ target.path.replace(trailingSlashRE, '/')
+ ) === 0 &&
+ (!target.hash || current.hash === target.hash) &&
+ queryIncludes(current.query, target.query)
+ )
+}
+
+function queryIncludes (current, target) {
+ for (var key in target) {
+ if (!(key in current)) {
+ return false
+ }
+ }
+ return true
+}
+
+/* */
+
+// work around weird flow bug
+var toTypes = [String, Object];
+var eventTypes = [String, Array];
+
+var Link = {
+ name: 'router-link',
+ props: {
+ to: {
+ type: toTypes,
+ required: true
+ },
+ tag: {
+ type: String,
+ default: 'a'
+ },
+ exact: Boolean,
+ append: Boolean,
+ replace: Boolean,
+ activeClass: String,
+ event: {
+ type: eventTypes,
+ default: 'click'
+ }
+ },
+ render: function render (h) {
+ var this$1 = this;
+
+ var router = this.$router;
+ var current = this.$route;
+ var ref = router.resolve(this.to, current, this.append);
+ var location = ref.location;
+ var route = ref.route;
+ var href = ref.href;
+ var classes = {};
+ var activeClass = this.activeClass || router.options.linkActiveClass || 'router-link-active';
+ var compareTarget = location.path ? createRoute(null, location) : route;
+ classes[activeClass] = this.exact
+ ? isSameRoute(current, compareTarget)
+ : isIncludedRoute(current, compareTarget);
+
+ var handler = function (e) {
+ if (guardEvent(e)) {
+ if (this$1.replace) {
+ router.replace(location);
+ } else {
+ router.push(location);
+ }
+ }
+ };
+
+ var on = { click: guardEvent };
+ if (Array.isArray(this.event)) {
+ this.event.forEach(function (e) { on[e] = handler; });
+ } else {
+ on[this.event] = handler;
+ }
+
+ var data = {
+ class: classes
+ };
+
+ if (this.tag === 'a') {
+ data.on = on;
+ data.attrs = { href: href };
+ } else {
+ // find the first child and apply listener and href
+ var a = findAnchor(this.$slots.default);
+ if (a) {
+ // in case the is a static node
+ a.isStatic = false;
+ var extend = _Vue.util.extend;
+ var aData = a.data = extend({}, a.data);
+ aData.on = on;
+ var aAttrs = a.data.attrs = extend({}, a.data.attrs);
+ aAttrs.href = href;
+ } else {
+ // doesn't have child, apply listener to self
+ data.on = on;
+ }
+ }
+
+ return h(this.tag, data, this.$slots.default)
+ }
+};
+
+function guardEvent (e) {
+ // don't redirect with control keys
+ if (e.metaKey || e.ctrlKey || e.shiftKey) { return }
+ // don't redirect when preventDefault called
+ if (e.defaultPrevented) { return }
+ // don't redirect on right click
+ if (e.button !== undefined && e.button !== 0) { return }
+ // don't redirect if `target="_blank"`
+ if (e.target && e.target.getAttribute) {
+ var target = e.target.getAttribute('target');
+ if (/\b_blank\b/i.test(target)) { return }
+ }
+ // this may be a Weex event which doesn't have this method
+ if (e.preventDefault) {
+ e.preventDefault();
+ }
+ return true
+}
+
+function findAnchor (children) {
+ if (children) {
+ var child;
+ for (var i = 0; i < children.length; i++) {
+ child = children[i];
+ if (child.tag === 'a') {
+ return child
+ }
+ if (child.children && (child = findAnchor(child.children))) {
+ return child
+ }
+ }
+ }
+}
+
+var _Vue;
+
+function install (Vue) {
+ if (install.installed) { return }
+ install.installed = true;
+
+ _Vue = Vue;
+
+ Object.defineProperty(Vue.prototype, '$router', {
+ get: function get () { return this.$root._router }
+ });
+
+ Object.defineProperty(Vue.prototype, '$route', {
+ get: function get () { return this.$root._route }
+ });
+
+ Vue.mixin({
+ beforeCreate: function beforeCreate () {
+ if (this.$options.router) {
+ this._router = this.$options.router;
+ this._router.init(this);
+ Vue.util.defineReactive(this, '_route', this._router.history.current);
+ }
+ }
+ });
+
+ Vue.component('router-view', View);
+ Vue.component('router-link', Link);
+
+ var strats = Vue.config.optionMergeStrategies;
+ // use the same hook merging strategy for route hooks
+ strats.beforeRouteEnter = strats.beforeRouteLeave = strats.created;
+}
+
+/* */
+
+var inBrowser = typeof window !== 'undefined';
+
+/* */
+
+function resolvePath (
+ relative,
+ base,
+ append
+) {
+ if (relative.charAt(0) === '/') {
+ return relative
+ }
+
+ if (relative.charAt(0) === '?' || relative.charAt(0) === '#') {
+ return base + relative
+ }
+
+ var stack = base.split('/');
+
+ // remove trailing segment if:
+ // - not appending
+ // - appending to trailing slash (last segment is empty)
+ if (!append || !stack[stack.length - 1]) {
+ stack.pop();
+ }
+
+ // resolve relative path
+ var segments = relative.replace(/^\//, '').split('/');
+ for (var i = 0; i < segments.length; i++) {
+ var segment = segments[i];
+ if (segment === '.') {
+ continue
+ } else if (segment === '..') {
+ stack.pop();
+ } else {
+ stack.push(segment);
+ }
+ }
+
+ // ensure leading slash
+ if (stack[0] !== '') {
+ stack.unshift('');
+ }
+
+ return stack.join('/')
+}
+
+function parsePath (path) {
+ var hash = '';
+ var query = '';
+
+ var hashIndex = path.indexOf('#');
+ if (hashIndex >= 0) {
+ hash = path.slice(hashIndex);
+ path = path.slice(0, hashIndex);
+ }
+
+ var queryIndex = path.indexOf('?');
+ if (queryIndex >= 0) {
+ query = path.slice(queryIndex + 1);
+ path = path.slice(0, queryIndex);
+ }
+
+ return {
+ path: path,
+ query: query,
+ hash: hash
+ }
+}
+
+function cleanPath (path) {
+ return path.replace(/\/\//g, '/')
+}
+
+/* */
+
+function createRouteMap (
+ routes,
+ oldPathMap,
+ oldNameMap
+) {
+ var pathMap = oldPathMap || Object.create(null);
+ var nameMap = oldNameMap || Object.create(null);
+
+ routes.forEach(function (route) {
+ addRouteRecord(pathMap, nameMap, route);
+ });
+
+ return {
+ pathMap: pathMap,
+ nameMap: nameMap
+ }
+}
+
+function addRouteRecord (
+ pathMap,
+ nameMap,
+ route,
+ parent,
+ matchAs
+) {
+ var path = route.path;
+ var name = route.name;
+ if (process.env.NODE_ENV !== 'production') {
+ assert(path != null, "\"path\" is required in a route configuration.");
+ assert(
+ typeof route.component !== 'string',
+ "route config \"component\" for path: " + (String(path || name)) + " cannot be a " +
+ "string id. Use an actual component instead."
+ );
+ }
+
+ var record = {
+ path: normalizePath(path, parent),
+ components: route.components || { default: route.component },
+ instances: {},
+ name: name,
+ parent: parent,
+ matchAs: matchAs,
+ redirect: route.redirect,
+ beforeEnter: route.beforeEnter,
+ meta: route.meta || {},
+ props: route.props == null
+ ? {}
+ : route.components
+ ? route.props
+ : { default: route.props }
+ };
+
+ if (route.children) {
+ // Warn if route is named and has a default child route.
+ // If users navigate to this route by name, the default child will
+ // not be rendered (GH Issue #629)
+ if (process.env.NODE_ENV !== 'production') {
+ if (route.name && route.children.some(function (child) { return /^\/?$/.test(child.path); })) {
+ warn(
+ false,
+ "Named Route '" + (route.name) + "' has a default child route. " +
+ "When navigating to this named route (:to=\"{name: '" + (route.name) + "'\"), " +
+ "the default child route will not be rendered. Remove the name from " +
+ "this route and use the name of the default child route for named " +
+ "links instead."
+ );
+ }
+ }
+ route.children.forEach(function (child) {
+ var childMatchAs = matchAs
+ ? cleanPath((matchAs + "/" + (child.path)))
+ : undefined;
+ addRouteRecord(pathMap, nameMap, child, record, childMatchAs);
+ });
+ }
+
+ if (route.alias !== undefined) {
+ if (Array.isArray(route.alias)) {
+ route.alias.forEach(function (alias) {
+ var aliasRoute = {
+ path: alias,
+ children: route.children
+ };
+ addRouteRecord(pathMap, nameMap, aliasRoute, parent, record.path);
+ });
+ } else {
+ var aliasRoute = {
+ path: route.alias,
+ children: route.children
+ };
+ addRouteRecord(pathMap, nameMap, aliasRoute, parent, record.path);
+ }
+ }
+
+ if (!pathMap[record.path]) {
+ pathMap[record.path] = record;
+ }
+
+ if (name) {
+ if (!nameMap[name]) {
+ nameMap[name] = record;
+ } else if (process.env.NODE_ENV !== 'production' && !matchAs) {
+ warn(
+ false,
+ "Duplicate named routes definition: " +
+ "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
+ );
+ }
+ }
+}
+
+function normalizePath (path, parent) {
+ path = path.replace(/\/$/, '');
+ if (path[0] === '/') { return path }
+ if (parent == null) { return path }
+ return cleanPath(((parent.path) + "/" + path))
+}
+
+var index$1 = Array.isArray || function (arr) {
+ return Object.prototype.toString.call(arr) == '[object Array]';
+};
+
+var isarray = index$1;
+
+/**
+ * Expose `pathToRegexp`.
+ */
+var index = pathToRegexp;
+var parse_1 = parse;
+var compile_1 = compile;
+var tokensToFunction_1 = tokensToFunction;
+var tokensToRegExp_1 = tokensToRegExp;
+
+/**
+ * The main path matching regexp utility.
+ *
+ * @type {RegExp}
+ */
+var PATH_REGEXP = new RegExp([
+ // Match escaped characters that would otherwise appear in future matches.
+ // This allows the user to escape special characters that won't transform.
+ '(\\\\.)',
+ // Match Express-style parameters and un-named parameters with a prefix
+ // and optional suffixes. Matches appear as:
+ //
+ // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
+ // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
+ // "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
+ '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
+].join('|'), 'g');
+
+/**
+ * Parse a string for the raw tokens.
+ *
+ * @param {string} str
+ * @param {Object=} options
+ * @return {!Array}
+ */
+function parse (str, options) {
+ var tokens = [];
+ var key = 0;
+ var index = 0;
+ var path = '';
+ var defaultDelimiter = options && options.delimiter || '/';
+ var res;
+
+ while ((res = PATH_REGEXP.exec(str)) != null) {
+ var m = res[0];
+ var escaped = res[1];
+ var offset = res.index;
+ path += str.slice(index, offset);
+ index = offset + m.length;
+
+ // Ignore already escaped sequences.
+ if (escaped) {
+ path += escaped[1];
+ continue
+ }
+
+ var next = str[index];
+ var prefix = res[2];
+ var name = res[3];
+ var capture = res[4];
+ var group = res[5];
+ var modifier = res[6];
+ var asterisk = res[7];
+
+ // Push the current path onto the tokens.
+ if (path) {
+ tokens.push(path);
+ path = '';
+ }
+
+ var partial = prefix != null && next != null && next !== prefix;
+ var repeat = modifier === '+' || modifier === '*';
+ var optional = modifier === '?' || modifier === '*';
+ var delimiter = res[2] || defaultDelimiter;
+ var pattern = capture || group;
+
+ tokens.push({
+ name: name || key++,
+ prefix: prefix || '',
+ delimiter: delimiter,
+ optional: optional,
+ repeat: repeat,
+ partial: partial,
+ asterisk: !!asterisk,
+ pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
+ });
+ }
+
+ // Match any characters still remaining.
+ if (index < str.length) {
+ path += str.substr(index);
+ }
+
+ // If the path exists, push it onto the end.
+ if (path) {
+ tokens.push(path);
+ }
+
+ return tokens
+}
+
+/**
+ * Compile a string to a template function for the path.
+ *
+ * @param {string} str
+ * @param {Object=} options
+ * @return {!function(Object=, Object=)}
+ */
+function compile (str, options) {
+ return tokensToFunction(parse(str, options))
+}
+
+/**
+ * Prettier encoding of URI path segments.
+ *
+ * @param {string}
+ * @return {string}
+ */
+function encodeURIComponentPretty (str) {
+ return encodeURI(str).replace(/[\/?#]/g, function (c) {
+ return '%' + c.charCodeAt(0).toString(16).toUpperCase()
+ })
+}
+
+/**
+ * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
+ *
+ * @param {string}
+ * @return {string}
+ */
+function encodeAsterisk (str) {
+ return encodeURI(str).replace(/[?#]/g, function (c) {
+ return '%' + c.charCodeAt(0).toString(16).toUpperCase()
+ })
+}
+
+/**
+ * Expose a method for transforming tokens into the path function.
+ */
+function tokensToFunction (tokens) {
+ // Compile all the tokens into regexps.
+ var matches = new Array(tokens.length);
+
+ // Compile all the patterns before compilation.
+ for (var i = 0; i < tokens.length; i++) {
+ if (typeof tokens[i] === 'object') {
+ matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
+ }
+ }
+
+ return function (obj, opts) {
+ var path = '';
+ var data = obj || {};
+ var options = opts || {};
+ var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
+
+ for (var i = 0; i < tokens.length; i++) {
+ var token = tokens[i];
+
+ if (typeof token === 'string') {
+ path += token;
+
+ continue
+ }
+
+ var value = data[token.name];
+ var segment;
+
+ if (value == null) {
+ if (token.optional) {
+ // Prepend partial segment prefixes.
+ if (token.partial) {
+ path += token.prefix;
+ }
+
+ continue
+ } else {
+ throw new TypeError('Expected "' + token.name + '" to be defined')
+ }
+ }
+
+ if (isarray(value)) {
+ if (!token.repeat) {
+ throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
+ }
+
+ if (value.length === 0) {
+ if (token.optional) {
+ continue
+ } else {
+ throw new TypeError('Expected "' + token.name + '" to not be empty')
+ }
+ }
+
+ for (var j = 0; j < value.length; j++) {
+ segment = encode(value[j]);
+
+ if (!matches[i].test(segment)) {
+ throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
+ }
+
+ path += (j === 0 ? token.prefix : token.delimiter) + segment;
+ }
+
+ continue
+ }
+
+ segment = token.asterisk ? encodeAsterisk(value) : encode(value);
+
+ if (!matches[i].test(segment)) {
+ throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
+ }
+
+ path += token.prefix + segment;
+ }
+
+ return path
+ }
+}
+
+/**
+ * Escape a regular expression string.
+ *
+ * @param {string} str
+ * @return {string}
+ */
+function escapeString (str) {
+ return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
+}
+
+/**
+ * Escape the capturing group by escaping special characters and meaning.
+ *
+ * @param {string} group
+ * @return {string}
+ */
+function escapeGroup (group) {
+ return group.replace(/([=!:$\/()])/g, '\\$1')
+}
+
+/**
+ * Attach the keys as a property of the regexp.
+ *
+ * @param {!RegExp} re
+ * @param {Array} keys
+ * @return {!RegExp}
+ */
+function attachKeys (re, keys) {
+ re.keys = keys;
+ return re
+}
+
+/**
+ * Get the flags for a regexp from the options.
+ *
+ * @param {Object} options
+ * @return {string}
+ */
+function flags (options) {
+ return options.sensitive ? '' : 'i'
+}
+
+/**
+ * Pull out keys from a regexp.
+ *
+ * @param {!RegExp} path
+ * @param {!Array} keys
+ * @return {!RegExp}
+ */
+function regexpToRegexp (path, keys) {
+ // Use a negative lookahead to match only capturing groups.
+ var groups = path.source.match(/\((?!\?)/g);
+
+ if (groups) {
+ for (var i = 0; i < groups.length; i++) {
+ keys.push({
+ name: i,
+ prefix: null,
+ delimiter: null,
+ optional: false,
+ repeat: false,
+ partial: false,
+ asterisk: false,
+ pattern: null
+ });
+ }
+ }
+
+ return attachKeys(path, keys)
+}
+
+/**
+ * Transform an array into a regexp.
+ *
+ * @param {!Array} path
+ * @param {Array} keys
+ * @param {!Object} options
+ * @return {!RegExp}
+ */
+function arrayToRegexp (path, keys, options) {
+ var parts = [];
+
+ for (var i = 0; i < path.length; i++) {
+ parts.push(pathToRegexp(path[i], keys, options).source);
+ }
+
+ var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
+
+ return attachKeys(regexp, keys)
+}
+
+/**
+ * Create a path regexp from string input.
+ *
+ * @param {string} path
+ * @param {!Array} keys
+ * @param {!Object} options
+ * @return {!RegExp}
+ */
+function stringToRegexp (path, keys, options) {
+ return tokensToRegExp(parse(path, options), keys, options)
+}
+
+/**
+ * Expose a function for taking tokens and returning a RegExp.
+ *
+ * @param {!Array} tokens
+ * @param {(Array|Object)=} keys
+ * @param {Object=} options
+ * @return {!RegExp}
+ */
+function tokensToRegExp (tokens, keys, options) {
+ if (!isarray(keys)) {
+ options = /** @type {!Object} */ (keys || options);
+ keys = [];
+ }
+
+ options = options || {};
+
+ var strict = options.strict;
+ var end = options.end !== false;
+ var route = '';
+
+ // Iterate over the tokens and create our regexp string.
+ for (var i = 0; i < tokens.length; i++) {
+ var token = tokens[i];
+
+ if (typeof token === 'string') {
+ route += escapeString(token);
+ } else {
+ var prefix = escapeString(token.prefix);
+ var capture = '(?:' + token.pattern + ')';
+
+ keys.push(token);
+
+ if (token.repeat) {
+ capture += '(?:' + prefix + capture + ')*';
+ }
+
+ if (token.optional) {
+ if (!token.partial) {
+ capture = '(?:' + prefix + '(' + capture + '))?';
+ } else {
+ capture = prefix + '(' + capture + ')?';
+ }
+ } else {
+ capture = prefix + '(' + capture + ')';
+ }
+
+ route += capture;
+ }
+ }
+
+ var delimiter = escapeString(options.delimiter || '/');
+ var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
+
+ // In non-strict mode we allow a slash at the end of match. If the path to
+ // match already ends with a slash, we remove it for consistency. The slash
+ // is valid at the end of a path match, not in the middle. This is important
+ // in non-ending mode, where "/test/" shouldn't match "/test//route".
+ if (!strict) {
+ route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
+ }
+
+ if (end) {
+ route += '$';
+ } else {
+ // In non-ending mode, we need the capturing groups to match as much as
+ // possible by using a positive lookahead to the end or next path segment.
+ route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
+ }
+
+ return attachKeys(new RegExp('^' + route, flags(options)), keys)
+}
+
+/**
+ * Normalize the given path string, returning a regular expression.
+ *
+ * An empty array can be passed in for the keys, which will hold the
+ * placeholder key descriptions. For example, using `/user/:id`, `keys` will
+ * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
+ *
+ * @param {(string|RegExp|Array)} path
+ * @param {(Array|Object)=} keys
+ * @param {Object=} options
+ * @return {!RegExp}
+ */
+function pathToRegexp (path, keys, options) {
+ if (!isarray(keys)) {
+ options = /** @type {!Object} */ (keys || options);
+ keys = [];
+ }
+
+ options = options || {};
+
+ if (path instanceof RegExp) {
+ return regexpToRegexp(path, /** @type {!Array} */ (keys))
+ }
+
+ if (isarray(path)) {
+ return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
+ }
+
+ return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
+}
+
+index.parse = parse_1;
+index.compile = compile_1;
+index.tokensToFunction = tokensToFunction_1;
+index.tokensToRegExp = tokensToRegExp_1;
+
+/* */
+
+var regexpCache = Object.create(null);
+
+function getRouteRegex (path) {
+ var hit = regexpCache[path];
+ var keys, regexp;
+
+ if (hit) {
+ keys = hit.keys;
+ regexp = hit.regexp;
+ } else {
+ keys = [];
+ regexp = index(path, keys);
+ regexpCache[path] = { keys: keys, regexp: regexp };
+ }
+
+ return { keys: keys, regexp: regexp }
+}
+
+var regexpCompileCache = Object.create(null);
+
+function fillParams (
+ path,
+ params,
+ routeMsg
+) {
+ try {
+ var filler =
+ regexpCompileCache[path] ||
+ (regexpCompileCache[path] = index.compile(path));
+ return filler(params || {}, { pretty: true })
+ } catch (e) {
+ if (process.env.NODE_ENV !== 'production') {
+ warn(false, ("missing param for " + routeMsg + ": " + (e.message)));
+ }
+ return ''
+ }
+}
+
+/* */
+
+function normalizeLocation (
+ raw,
+ current,
+ append
+) {
+ var next = typeof raw === 'string' ? { path: raw } : raw;
+ // named target
+ if (next.name || next._normalized) {
+ return next
+ }
+
+ // relative params
+ if (!next.path && next.params && current) {
+ next = assign({}, next);
+ next._normalized = true;
+ var params = assign(assign({}, current.params), next.params);
+ if (current.name) {
+ next.name = current.name;
+ next.params = params;
+ } else if (current.matched) {
+ var rawPath = current.matched[current.matched.length - 1].path;
+ next.path = fillParams(rawPath, params, ("path " + (current.path)));
+ } else if (process.env.NODE_ENV !== 'production') {
+ warn(false, "relative params navigation requires a current route.");
+ }
+ return next
+ }
+
+ var parsedPath = parsePath(next.path || '');
+ var basePath = (current && current.path) || '/';
+ var path = parsedPath.path
+ ? resolvePath(parsedPath.path, basePath, append || next.append)
+ : (current && current.path) || '/';
+ var query = resolveQuery(parsedPath.query, next.query);
+ var hash = next.hash || parsedPath.hash;
+ if (hash && hash.charAt(0) !== '#') {
+ hash = "#" + hash;
+ }
+
+ return {
+ _normalized: true,
+ path: path,
+ query: query,
+ hash: hash
+ }
+}
+
+function assign (a, b) {
+ for (var key in b) {
+ a[key] = b[key];
+ }
+ return a
+}
+
+/* */
+
+function createMatcher (routes) {
+ var ref = createRouteMap(routes);
+ var pathMap = ref.pathMap;
+ var nameMap = ref.nameMap;
+
+ function addRoutes (routes) {
+ createRouteMap(routes, pathMap, nameMap);
+ }
+
+ function match (
+ raw,
+ currentRoute,
+ redirectedFrom
+ ) {
+ var location = normalizeLocation(raw, currentRoute);
+ var name = location.name;
+
+ if (name) {
+ var record = nameMap[name];
+ if (process.env.NODE_ENV !== 'production') {
+ warn(record, ("Route with name '" + name + "' does not exist"));
+ }
+ var paramNames = getRouteRegex(record.path).keys
+ .filter(function (key) { return !key.optional; })
+ .map(function (key) { return key.name; });
+
+ if (typeof location.params !== 'object') {
+ location.params = {};
+ }
+
+ if (currentRoute && typeof currentRoute.params === 'object') {
+ for (var key in currentRoute.params) {
+ if (!(key in location.params) && paramNames.indexOf(key) > -1) {
+ location.params[key] = currentRoute.params[key];
+ }
+ }
+ }
+
+ if (record) {
+ location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
+ return _createRoute(record, location, redirectedFrom)
+ }
+ } else if (location.path) {
+ location.params = {};
+ for (var path in pathMap) {
+ if (matchRoute(path, location.params, location.path)) {
+ return _createRoute(pathMap[path], location, redirectedFrom)
+ }
+ }
+ }
+ // no match
+ return _createRoute(null, location)
+ }
+
+ function redirect (
+ record,
+ location
+ ) {
+ var originalRedirect = record.redirect;
+ var redirect = typeof originalRedirect === 'function'
+ ? originalRedirect(createRoute(record, location))
+ : originalRedirect;
+
+ if (typeof redirect === 'string') {
+ redirect = { path: redirect };
+ }
+
+ if (!redirect || typeof redirect !== 'object') {
+ process.env.NODE_ENV !== 'production' && warn(
+ false, ("invalid redirect option: " + (JSON.stringify(redirect)))
+ );
+ return _createRoute(null, location)
+ }
+
+ var re = redirect;
+ var name = re.name;
+ var path = re.path;
+ var query = location.query;
+ var hash = location.hash;
+ var params = location.params;
+ query = re.hasOwnProperty('query') ? re.query : query;
+ hash = re.hasOwnProperty('hash') ? re.hash : hash;
+ params = re.hasOwnProperty('params') ? re.params : params;
+
+ if (name) {
+ // resolved named direct
+ var targetRecord = nameMap[name];
+ if (process.env.NODE_ENV !== 'production') {
+ assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found."));
+ }
+ return match({
+ _normalized: true,
+ name: name,
+ query: query,
+ hash: hash,
+ params: params
+ }, undefined, location)
+ } else if (path) {
+ // 1. resolve relative redirect
+ var rawPath = resolveRecordPath(path, record);
+ // 2. resolve params
+ var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\""));
+ // 3. rematch with existing query and hash
+ return match({
+ _normalized: true,
+ path: resolvedPath,
+ query: query,
+ hash: hash
+ }, undefined, location)
+ } else {
+ warn(false, ("invalid redirect option: " + (JSON.stringify(redirect))));
+ return _createRoute(null, location)
+ }
+ }
+
+ function alias (
+ record,
+ location,
+ matchAs
+ ) {
+ var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\""));
+ var aliasedMatch = match({
+ _normalized: true,
+ path: aliasedPath
+ });
+ if (aliasedMatch) {
+ var matched = aliasedMatch.matched;
+ var aliasedRecord = matched[matched.length - 1];
+ location.params = aliasedMatch.params;
+ return _createRoute(aliasedRecord, location)
+ }
+ return _createRoute(null, location)
+ }
+
+ function _createRoute (
+ record,
+ location,
+ redirectedFrom
+ ) {
+ if (record && record.redirect) {
+ return redirect(record, redirectedFrom || location)
+ }
+ if (record && record.matchAs) {
+ return alias(record, location, record.matchAs)
+ }
+ return createRoute(record, location, redirectedFrom)
+ }
+
+ return {
+ match: match,
+ addRoutes: addRoutes
+ }
+}
+
+function matchRoute (
+ path,
+ params,
+ pathname
+) {
+ var ref = getRouteRegex(path);
+ var regexp = ref.regexp;
+ var keys = ref.keys;
+ var m = pathname.match(regexp);
+
+ if (!m) {
+ return false
+ } else if (!params) {
+ return true
+ }
+
+ for (var i = 1, len = m.length; i < len; ++i) {
+ var key = keys[i - 1];
+ var val = typeof m[i] === 'string' ? decodeURIComponent(m[i]) : m[i];
+ if (key) { params[key.name] = val; }
+ }
+
+ return true
+}
+
+function resolveRecordPath (path, record) {
+ return resolvePath(path, record.parent ? record.parent.path : '/', true)
+}
+
+/* */
+
+
+var positionStore = Object.create(null);
+
+function setupScroll () {
+ window.addEventListener('popstate', function (e) {
+ saveScrollPosition();
+ if (e.state && e.state.key) {
+ setStateKey(e.state.key);
+ }
+ });
+}
+
+function handleScroll (
+ router,
+ to,
+ from,
+ isPop
+) {
+ if (!router.app) {
+ return
+ }
+
+ var behavior = router.options.scrollBehavior;
+ if (!behavior) {
+ return
+ }
+
+ if (process.env.NODE_ENV !== 'production') {
+ assert(typeof behavior === 'function', "scrollBehavior must be a function");
+ }
+
+ // wait until re-render finishes before scrolling
+ router.app.$nextTick(function () {
+ var position = getScrollPosition();
+ var shouldScroll = behavior(to, from, isPop ? position : null);
+ if (!shouldScroll) {
+ return
+ }
+ var isObject = typeof shouldScroll === 'object';
+ if (isObject && typeof shouldScroll.selector === 'string') {
+ var el = document.querySelector(shouldScroll.selector);
+ if (el) {
+ position = getElementPosition(el);
+ } else if (isValidPosition(shouldScroll)) {
+ position = normalizePosition(shouldScroll);
+ }
+ } else if (isObject && isValidPosition(shouldScroll)) {
+ position = normalizePosition(shouldScroll);
+ }
+
+ if (position) {
+ window.scrollTo(position.x, position.y);
+ }
+ });
+}
+
+function saveScrollPosition () {
+ var key = getStateKey();
+ if (key) {
+ positionStore[key] = {
+ x: window.pageXOffset,
+ y: window.pageYOffset
+ };
+ }
+}
+
+function getScrollPosition () {
+ var key = getStateKey();
+ if (key) {
+ return positionStore[key]
+ }
+}
+
+function getElementPosition (el) {
+ var docEl = document.documentElement;
+ var docRect = docEl.getBoundingClientRect();
+ var elRect = el.getBoundingClientRect();
+ return {
+ x: elRect.left - docRect.left,
+ y: elRect.top - docRect.top
+ }
+}
+
+function isValidPosition (obj) {
+ return isNumber(obj.x) || isNumber(obj.y)
+}
+
+function normalizePosition (obj) {
+ return {
+ x: isNumber(obj.x) ? obj.x : window.pageXOffset,
+ y: isNumber(obj.y) ? obj.y : window.pageYOffset
+ }
+}
+
+function isNumber (v) {
+ return typeof v === 'number'
+}
+
+/* */
+
+var supportsPushState = inBrowser && (function () {
+ var ua = window.navigator.userAgent;
+
+ if (
+ (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
+ ua.indexOf('Mobile Safari') !== -1 &&
+ ua.indexOf('Chrome') === -1 &&
+ ua.indexOf('Windows Phone') === -1
+ ) {
+ return false
+ }
+
+ return window.history && 'pushState' in window.history
+})();
+
+// use User Timing api (if present) for more accurate key precision
+var Time = inBrowser && window.performance && window.performance.now
+ ? window.performance
+ : Date;
+
+var _key = genKey();
+
+function genKey () {
+ return Time.now().toFixed(3)
+}
+
+function getStateKey () {
+ return _key
+}
+
+function setStateKey (key) {
+ _key = key;
+}
+
+function pushState (url, replace) {
+ saveScrollPosition();
+ // try...catch the pushState call to get around Safari
+ // DOM Exception 18 where it limits to 100 pushState calls
+ var history = window.history;
+ try {
+ if (replace) {
+ history.replaceState({ key: _key }, '', url);
+ } else {
+ _key = genKey();
+ history.pushState({ key: _key }, '', url);
+ }
+ } catch (e) {
+ window.location[replace ? 'replace' : 'assign'](url);
+ }
+}
+
+function replaceState (url) {
+ pushState(url, true);
+}
+
+/* */
+
+function runQueue (queue, fn, cb) {
+ var step = function (index) {
+ if (index >= queue.length) {
+ cb();
+ } else {
+ if (queue[index]) {
+ fn(queue[index], function () {
+ step(index + 1);
+ });
+ } else {
+ step(index + 1);
+ }
+ }
+ };
+ step(0);
+}
+
+/* */
+
+
+var History = function History (router, base) {
+ this.router = router;
+ this.base = normalizeBase(base);
+ // start with a route object that stands for "nowhere"
+ this.current = START;
+ this.pending = null;
+ this.ready = false;
+ this.readyCbs = [];
+};
+
+History.prototype.listen = function listen (cb) {
+ this.cb = cb;
+};
+
+History.prototype.onReady = function onReady (cb) {
+ if (this.ready) {
+ cb();
+ } else {
+ this.readyCbs.push(cb);
+ }
+};
+
+History.prototype.transitionTo = function transitionTo (location, onComplete, onAbort) {
+ var this$1 = this;
+
+ var route = this.router.match(location, this.current);
+ this.confirmTransition(route, function () {
+ this$1.updateRoute(route);
+ onComplete && onComplete(route);
+ this$1.ensureURL();
+
+ // fire ready cbs once
+ if (!this$1.ready) {
+ this$1.ready = true;
+ this$1.readyCbs.forEach(function (cb) {
+ cb(route);
+ });
+ }
+ }, onAbort);
+};
+
+History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) {
+ var this$1 = this;
+
+ var current = this.current;
+ var abort = function () { onAbort && onAbort(); };
+ if (
+ isSameRoute(route, current) &&
+ // in the case the route map has been dynamically appended to
+ route.matched.length === current.matched.length
+ ) {
+ this.ensureURL();
+ return abort()
+ }
+
+ var ref = resolveQueue(this.current.matched, route.matched);
+ var updated = ref.updated;
+ var deactivated = ref.deactivated;
+ var activated = ref.activated;
+
+ var queue = [].concat(
+ // in-component leave guards
+ extractLeaveGuards(deactivated),
+ // global before hooks
+ this.router.beforeHooks,
+ // in-component update hooks
+ extractUpdateHooks(updated),
+ // in-config enter guards
+ activated.map(function (m) { return m.beforeEnter; }),
+ // async components
+ resolveAsyncComponents(activated)
+ );
+
+ this.pending = route;
+ var iterator = function (hook, next) {
+ if (this$1.pending !== route) {
+ return abort()
+ }
+ hook(route, current, function (to) {
+ if (to === false) {
+ // next(false) -> abort navigation, ensure current URL
+ this$1.ensureURL(true);
+ abort();
+ } else if (typeof to === 'string' || typeof to === 'object') {
+ // next('/') or next({ path: '/' }) -> redirect
+ (typeof to === 'object' && to.replace) ? this$1.replace(to) : this$1.push(to);
+ abort();
+ } else {
+ // confirm transition and pass on the value
+ next(to);
+ }
+ });
+ };
+
+ runQueue(queue, iterator, function () {
+ var postEnterCbs = [];
+ var isValid = function () { return this$1.current === route; };
+ var enterGuards = extractEnterGuards(activated, postEnterCbs, isValid);
+ // wait until async components are resolved before
+ // extracting in-component enter guards
+ runQueue(enterGuards, iterator, function () {
+ if (this$1.pending !== route) {
+ return abort()
+ }
+ this$1.pending = null;
+ onComplete(route);
+ if (this$1.router.app) {
+ this$1.router.app.$nextTick(function () {
+ postEnterCbs.forEach(function (cb) { return cb(); });
+ });
+ }
+ });
+ });
+};
+
+History.prototype.updateRoute = function updateRoute (route) {
+ var prev = this.current;
+ this.current = route;
+ this.cb && this.cb(route);
+ this.router.afterHooks.forEach(function (hook) {
+ hook && hook(route, prev);
+ });
+};
+
+function normalizeBase (base) {
+ if (!base) {
+ if (inBrowser) {
+ // respect tag
+ var baseEl = document.querySelector('base');
+ base = (baseEl && baseEl.getAttribute('href')) || '/';
+ } else {
+ base = '/';
+ }
+ }
+ // make sure there's the starting slash
+ if (base.charAt(0) !== '/') {
+ base = '/' + base;
+ }
+ // remove trailing slash
+ return base.replace(/\/$/, '')
+}
+
+function resolveQueue (
+ current,
+ next
+) {
+ var i;
+ var max = Math.max(current.length, next.length);
+ for (i = 0; i < max; i++) {
+ if (current[i] !== next[i]) {
+ break
+ }
+ }
+ return {
+ updated: next.slice(0, i),
+ activated: next.slice(i),
+ deactivated: current.slice(i)
+ }
+}
+
+function extractGuards (
+ records,
+ name,
+ bind,
+ reverse
+) {
+ var guards = flatMapComponents(records, function (def, instance, match, key) {
+ var guard = extractGuard(def, name);
+ if (guard) {
+ return Array.isArray(guard)
+ ? guard.map(function (guard) { return bind(guard, instance, match, key); })
+ : bind(guard, instance, match, key)
+ }
+ });
+ return flatten(reverse ? guards.reverse() : guards)
+}
+
+function extractGuard (
+ def,
+ key
+) {
+ if (typeof def !== 'function') {
+ // extend now so that global mixins are applied.
+ def = _Vue.extend(def);
+ }
+ return def.options[key]
+}
+
+function extractLeaveGuards (deactivated) {
+ return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
+}
+
+function extractUpdateHooks (updated) {
+ return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
+}
+
+function bindGuard (guard, instance) {
+ return function boundRouteGuard () {
+ return guard.apply(instance, arguments)
+ }
+}
+
+function extractEnterGuards (
+ activated,
+ cbs,
+ isValid
+) {
+ return extractGuards(activated, 'beforeRouteEnter', function (guard, _, match, key) {
+ return bindEnterGuard(guard, match, key, cbs, isValid)
+ })
+}
+
+function bindEnterGuard (
+ guard,
+ match,
+ key,
+ cbs,
+ isValid
+) {
+ return function routeEnterGuard (to, from, next) {
+ return guard(to, from, function (cb) {
+ next(cb);
+ if (typeof cb === 'function') {
+ cbs.push(function () {
+ // #750
+ // if a router-view is wrapped with an out-in transition,
+ // the instance may not have been registered at this time.
+ // we will need to poll for registration until current route
+ // is no longer valid.
+ poll(cb, match.instances, key, isValid);
+ });
+ }
+ })
+ }
+}
+
+function poll (
+ cb, // somehow flow cannot infer this is a function
+ instances,
+ key,
+ isValid
+) {
+ if (instances[key]) {
+ cb(instances[key]);
+ } else if (isValid()) {
+ setTimeout(function () {
+ poll(cb, instances, key, isValid);
+ }, 16);
+ }
+}
+
+function resolveAsyncComponents (matched) {
+ return flatMapComponents(matched, function (def, _, match, key) {
+ // if it's a function and doesn't have Vue options attached,
+ // assume it's an async component resolve function.
+ // we are not using Vue's default async resolving mechanism because
+ // we want to halt the navigation until the incoming component has been
+ // resolved.
+ if (typeof def === 'function' && !def.options) {
+ return function (to, from, next) {
+ var resolve = once(function (resolvedDef) {
+ match.components[key] = resolvedDef;
+ next();
+ });
+
+ var reject = once(function (reason) {
+ warn(false, ("Failed to resolve async component " + key + ": " + reason));
+ next(false);
+ });
+
+ var res = def(resolve, reject);
+ if (res && typeof res.then === 'function') {
+ res.then(resolve, reject);
+ }
+ }
+ }
+ })
+}
+
+function flatMapComponents (
+ matched,
+ fn
+) {
+ return flatten(matched.map(function (m) {
+ return Object.keys(m.components).map(function (key) { return fn(
+ m.components[key],
+ m.instances[key],
+ m, key
+ ); })
+ }))
+}
+
+function flatten (arr) {
+ return Array.prototype.concat.apply([], arr)
+}
+
+// in Webpack 2, require.ensure now also returns a Promise
+// so the resolve/reject functions may get called an extra time
+// if the user uses an arrow function shorthand that happens to
+// return that Promise.
+function once (fn) {
+ var called = false;
+ return function () {
+ if (called) { return }
+ called = true;
+ return fn.apply(this, arguments)
+ }
+}
+
+/* */
+
+
+var HTML5History = (function (History$$1) {
+ function HTML5History (router, base) {
+ var this$1 = this;
+
+ History$$1.call(this, router, base);
+
+ var expectScroll = router.options.scrollBehavior;
+
+ if (expectScroll) {
+ setupScroll();
+ }
+
+ window.addEventListener('popstate', function (e) {
+ this$1.transitionTo(getLocation(this$1.base), function (route) {
+ if (expectScroll) {
+ handleScroll(router, route, this$1.current, true);
+ }
+ });
+ });
+ }
+
+ if ( History$$1 ) HTML5History.__proto__ = History$$1;
+ HTML5History.prototype = Object.create( History$$1 && History$$1.prototype );
+ HTML5History.prototype.constructor = HTML5History;
+
+ HTML5History.prototype.go = function go (n) {
+ window.history.go(n);
+ };
+
+ HTML5History.prototype.push = function push (location, onComplete, onAbort) {
+ var this$1 = this;
+
+ this.transitionTo(location, function (route) {
+ pushState(cleanPath(this$1.base + route.fullPath));
+ handleScroll(this$1.router, route, this$1.current, false);
+ onComplete && onComplete(route);
+ }, onAbort);
+ };
+
+ HTML5History.prototype.replace = function replace (location, onComplete, onAbort) {
+ var this$1 = this;
+
+ this.transitionTo(location, function (route) {
+ replaceState(cleanPath(this$1.base + route.fullPath));
+ handleScroll(this$1.router, route, this$1.current, false);
+ onComplete && onComplete(route);
+ }, onAbort);
+ };
+
+ HTML5History.prototype.ensureURL = function ensureURL (push) {
+ if (getLocation(this.base) !== this.current.fullPath) {
+ var current = cleanPath(this.base + this.current.fullPath);
+ push ? pushState(current) : replaceState(current);
+ }
+ };
+
+ HTML5History.prototype.getCurrentLocation = function getCurrentLocation () {
+ return getLocation(this.base)
+ };
+
+ return HTML5History;
+}(History));
+
+function getLocation (base) {
+ var path = window.location.pathname;
+ if (base && path.indexOf(base) === 0) {
+ path = path.slice(base.length);
+ }
+ return (path || '/') + window.location.search + window.location.hash
+}
+
+/* */
+
+
+var HashHistory = (function (History$$1) {
+ function HashHistory (router, base, fallback) {
+ History$$1.call(this, router, base);
+ // check history fallback deeplinking
+ if (fallback && checkFallback(this.base)) {
+ return
+ }
+ ensureSlash();
+ }
+
+ if ( History$$1 ) HashHistory.__proto__ = History$$1;
+ HashHistory.prototype = Object.create( History$$1 && History$$1.prototype );
+ HashHistory.prototype.constructor = HashHistory;
+
+ // this is delayed until the app mounts
+ // to avoid the hashchange listener being fired too early
+ HashHistory.prototype.setupListeners = function setupListeners () {
+ var this$1 = this;
+
+ window.addEventListener('hashchange', function () {
+ if (!ensureSlash()) {
+ return
+ }
+ this$1.transitionTo(getHash(), function (route) {
+ replaceHash(route.fullPath);
+ });
+ });
+ };
+
+ HashHistory.prototype.push = function push (location, onComplete, onAbort) {
+ this.transitionTo(location, function (route) {
+ pushHash(route.fullPath);
+ onComplete && onComplete(route);
+ }, onAbort);
+ };
+
+ HashHistory.prototype.replace = function replace (location, onComplete, onAbort) {
+ this.transitionTo(location, function (route) {
+ replaceHash(route.fullPath);
+ onComplete && onComplete(route);
+ }, onAbort);
+ };
+
+ HashHistory.prototype.go = function go (n) {
+ window.history.go(n);
+ };
+
+ HashHistory.prototype.ensureURL = function ensureURL (push) {
+ var current = this.current.fullPath;
+ if (getHash() !== current) {
+ push ? pushHash(current) : replaceHash(current);
+ }
+ };
+
+ HashHistory.prototype.getCurrentLocation = function getCurrentLocation () {
+ return getHash()
+ };
+
+ return HashHistory;
+}(History));
+
+function checkFallback (base) {
+ var location = getLocation(base);
+ if (!/^\/#/.test(location)) {
+ window.location.replace(
+ cleanPath(base + '/#' + location)
+ );
+ return true
+ }
+}
+
+function ensureSlash () {
+ var path = getHash();
+ if (path.charAt(0) === '/') {
+ return true
+ }
+ replaceHash('/' + path);
+ return false
+}
+
+function getHash () {
+ // We can't use window.location.hash here because it's not
+ // consistent across browsers - Firefox will pre-decode it!
+ var href = window.location.href;
+ var index = href.indexOf('#');
+ return index === -1 ? '' : href.slice(index + 1)
+}
+
+function pushHash (path) {
+ window.location.hash = path;
+}
+
+function replaceHash (path) {
+ var i = window.location.href.indexOf('#');
+ window.location.replace(
+ window.location.href.slice(0, i >= 0 ? i : 0) + '#' + path
+ );
+}
+
+/* */
+
+
+var AbstractHistory = (function (History$$1) {
+ function AbstractHistory (router, base) {
+ History$$1.call(this, router, base);
+ this.stack = [];
+ this.index = -1;
+ }
+
+ if ( History$$1 ) AbstractHistory.__proto__ = History$$1;
+ AbstractHistory.prototype = Object.create( History$$1 && History$$1.prototype );
+ AbstractHistory.prototype.constructor = AbstractHistory;
+
+ AbstractHistory.prototype.push = function push (location, onComplete, onAbort) {
+ var this$1 = this;
+
+ this.transitionTo(location, function (route) {
+ this$1.stack = this$1.stack.slice(0, this$1.index + 1).concat(route);
+ this$1.index++;
+ onComplete && onComplete(route);
+ }, onAbort);
+ };
+
+ AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) {
+ var this$1 = this;
+
+ this.transitionTo(location, function (route) {
+ this$1.stack = this$1.stack.slice(0, this$1.index).concat(route);
+ onComplete && onComplete(route);
+ }, onAbort);
+ };
+
+ AbstractHistory.prototype.go = function go (n) {
+ var this$1 = this;
+
+ var targetIndex = this.index + n;
+ if (targetIndex < 0 || targetIndex >= this.stack.length) {
+ return
+ }
+ var route = this.stack[targetIndex];
+ this.confirmTransition(route, function () {
+ this$1.index = targetIndex;
+ this$1.updateRoute(route);
+ });
+ };
+
+ AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () {
+ var current = this.stack[this.stack.length - 1];
+ return current ? current.fullPath : '/'
+ };
+
+ AbstractHistory.prototype.ensureURL = function ensureURL () {
+ // noop
+ };
+
+ return AbstractHistory;
+}(History));
+
+/* */
+
+var VueRouter = function VueRouter (options) {
+ if ( options === void 0 ) options = {};
+
+ this.app = null;
+ this.apps = [];
+ this.options = options;
+ this.beforeHooks = [];
+ this.afterHooks = [];
+ this.matcher = createMatcher(options.routes || []);
+
+ var mode = options.mode || 'hash';
+ this.fallback = mode === 'history' && !supportsPushState;
+ if (this.fallback) {
+ mode = 'hash';
+ }
+ if (!inBrowser) {
+ mode = 'abstract';
+ }
+ this.mode = mode;
+
+ switch (mode) {
+ case 'history':
+ this.history = new HTML5History(this, options.base);
+ break
+ case 'hash':
+ this.history = new HashHistory(this, options.base, this.fallback);
+ break
+ case 'abstract':
+ this.history = new AbstractHistory(this, options.base);
+ break
+ default:
+ if (process.env.NODE_ENV !== 'production') {
+ assert(false, ("invalid mode: " + mode));
+ }
+ }
+};
+
+var prototypeAccessors = { currentRoute: {} };
+
+VueRouter.prototype.match = function match (
+ raw,
+ current,
+ redirectedFrom
+) {
+ return this.matcher.match(raw, current, redirectedFrom)
+};
+
+prototypeAccessors.currentRoute.get = function () {
+ return this.history && this.history.current
+};
+
+VueRouter.prototype.init = function init (app /* Vue component instance */) {
+ var this$1 = this;
+
+ process.env.NODE_ENV !== 'production' && assert(
+ install.installed,
+ "not installed. Make sure to call `Vue.use(VueRouter)` " +
+ "before creating root instance."
+ );
+
+ this.apps.push(app);
+
+ // main app already initialized.
+ if (this.app) {
+ return
+ }
+
+ this.app = app;
+
+ var history = this.history;
+
+ if (history instanceof HTML5History) {
+ history.transitionTo(history.getCurrentLocation());
+ } else if (history instanceof HashHistory) {
+ var setupHashListener = function () {
+ history.setupListeners();
+ };
+ history.transitionTo(
+ history.getCurrentLocation(),
+ setupHashListener,
+ setupHashListener
+ );
+ }
+
+ history.listen(function (route) {
+ this$1.apps.forEach(function (app) {
+ app._route = route;
+ });
+ });
+};
+
+VueRouter.prototype.beforeEach = function beforeEach (fn) {
+ this.beforeHooks.push(fn);
+};
+
+VueRouter.prototype.afterEach = function afterEach (fn) {
+ this.afterHooks.push(fn);
+};
+
+VueRouter.prototype.onReady = function onReady (cb) {
+ this.history.onReady(cb);
+};
+
+VueRouter.prototype.push = function push (location, onComplete, onAbort) {
+ this.history.push(location, onComplete, onAbort);
+};
+
+VueRouter.prototype.replace = function replace (location, onComplete, onAbort) {
+ this.history.replace(location, onComplete, onAbort);
+};
+
+VueRouter.prototype.go = function go (n) {
+ this.history.go(n);
+};
+
+VueRouter.prototype.back = function back () {
+ this.go(-1);
+};
+
+VueRouter.prototype.forward = function forward () {
+ this.go(1);
+};
+
+VueRouter.prototype.getMatchedComponents = function getMatchedComponents (to) {
+ var route = to
+ ? this.resolve(to).route
+ : this.currentRoute;
+ if (!route) {
+ return []
+ }
+ return [].concat.apply([], route.matched.map(function (m) {
+ return Object.keys(m.components).map(function (key) {
+ return m.components[key]
+ })
+ }))
+};
+
+VueRouter.prototype.resolve = function resolve (
+ to,
+ current,
+ append
+) {
+ var location = normalizeLocation(to, current || this.history.current, append);
+ var route = this.match(location, current);
+ var fullPath = route.redirectedFrom || route.fullPath;
+ var base = this.history.base;
+ var href = createHref(base, fullPath, this.mode);
+ return {
+ location: location,
+ route: route,
+ href: href,
+ // for backwards compat
+ normalizedTo: location,
+ resolved: route
+ }
+};
+
+VueRouter.prototype.addRoutes = function addRoutes (routes) {
+ this.matcher.addRoutes(routes);
+ if (this.history.current !== START) {
+ this.history.transitionTo(this.history.getCurrentLocation());
+ }
+};
+
+Object.defineProperties( VueRouter.prototype, prototypeAccessors );
+
+function createHref (base, fullPath, mode) {
+ var path = mode === 'hash' ? '#' + fullPath : fullPath;
+ return base ? cleanPath(base + '/' + path) : path
+}
+
+VueRouter.install = install;
+VueRouter.version = '2.2.1';
+
+if (inBrowser && window.Vue) {
+ window.Vue.use(VueRouter);
+}
+
+/* harmony default export */ __webpack_exports__["a"] = (VueRouter);
+
+/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(2)))
+
+/***/ }),
+/* 9 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_vue__ = __webpack_require__(4);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_vue__);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__promise_js__ = __webpack_require__(1);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_js__ = __webpack_require__(0);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__options_js__ = __webpack_require__(12);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__storage_js__ = __webpack_require__(13);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__oauth_oauth1_js__ = __webpack_require__(10);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__oauth_oauth2_js__ = __webpack_require__(11);
+
+
+
+
+
+
+
+
+class VueAuthenticate {
+ constructor($http, overrideOptions) {
+ let options = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["a" /* objectExtend */])({}, __WEBPACK_IMPORTED_MODULE_3__options_js__["a" /* default */]);
+ options = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["a" /* objectExtend */])(options, overrideOptions);
+ let storage = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__storage_js__["a" /* default */])(options);
+
+ Object.defineProperties(this, {
+ $http: {
+ get() {
+ return $http;
+ }
+ },
+
+ options: {
+ get() {
+ return options;
+ }
+ },
+
+ storage: {
+ get() {
+ return storage;
+ }
+ },
+
+ tokenName: {
+ get() {
+ if (this.options.tokenPrefix) {
+ return [this.options.tokenPrefix, this.options.tokenName].join('_');
+ } else {
+ return this.options.tokenName;
+ }
+ }
+ }
+ });
+
+ // Setup request interceptors
+ if (this.options.requestInterceptor && __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["b" /* isFunction */])(this.options.requestInterceptor)) {
+ this.options.requestInterceptor.call(this);
+
+ if (this.options.responseInterceptor && __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["b" /* isFunction */])(this.options.responseInterceptor)) {
+ this.options.responseInterceptor.call(this);
+ }
+ } else {
+ // By default, insert request interceptor for vue-resource
+ __WEBPACK_IMPORTED_MODULE_0_vue___default.a.http.interceptors.push((request, next) => {
+ if (this.isAuthenticated()) {
+ request.headers.set('Authorization', [this.options.tokenType, this.getToken()].join(' '));
+ } else {
+ request.headers.delete('Authorization');
+ }
+
+ if (this.options.responseInterceptor && __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["b" /* isFunction */])(this.options.responseInterceptor)) {
+ this.options.responseInterceptor.call(this);
+ } else {
+ next(response => {
+ try {
+ var responseJson = JSON.parse(response[this.options.responseDataKey]);
+ if (responseJson[this.options.tokenName]) {
+ this.setToken(responseJson);
+ delete responseJson[this.options.tokenName];
+ }
+ } catch (e) {}
+ });
+ }
+ });
+ }
+ }
+
+ /**
+ * Check if user is authenticated
+ * @author Sahat Yalkabov
+ * @copyright Method taken from https://github.com/sahat/satellizer
+ * @return {Boolean}
+ */
+ isAuthenticated() {
+ let token = this.storage.getItem(this.tokenName);
+
+ if (token) {
+ // Token is present
+ if (token.split('.').length === 3) {
+ // Token with a valid JWT format XXX.YYY.ZZZ
+ try {
+ // Could be a valid JWT or an access token with the same format
+ const base64Url = token.split('.')[1];
+ const base64 = base64Url.replace('-', '+').replace('_', '/');
+ const exp = JSON.parse(this.$window.atob(base64)).exp;
+ if (typeof exp === 'number') {
+ // JWT with an optonal expiration claims
+ return Math.round(new Date().getTime() / 1000) < exp;
+ }
+ } catch (e) {
+ return true; // Pass: Non-JWT token that looks like JWT
+ }
+ }
+ return true; // Pass: All other tokens
+ }
+ return false;
+ }
+
+ /**
+ * Get token if user is authenticated
+ * @return {String} Authentication token
+ */
+ getToken() {
+ return this.storage.getItem(this.tokenName);
+ }
+
+ /**
+ * Set new authentication token
+ * @param {String|Object} token
+ */
+ setToken(response) {
+ if (response[this.options.requestDataKey]) {
+ response = response[this.options.requestDataKey];
+ }
+
+ let token;
+ if (response.access_token) {
+ if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["c" /* isObject */])(response.access_token) && __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["c" /* isObject */])(response.access_token[this.options.requestDataKey])) {
+ response = response.access_token;
+ } else if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["d" /* isString */])(response.access_token)) {
+ token = response.access_token;
+ }
+ }
+
+ if (!token && response) {
+ token = response[this.options.tokenName];
+ }
+
+ if (token) {
+ this.storage.setItem(this.tokenName, token);
+ }
+ }
+
+ getPayload() {
+ const token = this.storage.getItem(this.tokenName);
+
+ if (token && token.split('.').length === 3) {
+ try {
+ const base64Url = token.split('.')[1];
+ const base64 = base64Url.replace('-', '+').replace('_', '/');
+ return JSON.parse(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["e" /* decodeBase64 */])(base64));
+ } catch (e) {
+ console.log(e);
+ }
+ }
+ }
+
+ /**
+ * Login user using email and password
+ * @param {Object} user User data
+ * @param {Object} requestOptions Request options
+ * @return {Promise} Request promise
+ */
+ login(user, requestOptions) {
+ requestOptions = requestOptions || {};
+ requestOptions.url = requestOptions.url ? requestOptions.url : __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["f" /* joinUrl */])(this.options.baseUrl, this.options.loginUrl);
+ requestOptions[this.options.requestDataKey] = user || requestOptions[this.options.requestDataKey];
+ requestOptions.method = requestOptions.method || 'POST';
+ requestOptions.withCredentials = requestOptions.withCredentials || this.options.withCredentials;
+
+ return this.$http(requestOptions).then(response => {
+ this.setToken(response);
+ return response;
+ });
+ }
+
+ /**
+ * Register new user
+ * @param {Object} user User data
+ * @param {Object} requestOptions Request options
+ * @return {Promise} Request promise
+ */
+ register(user, requestOptions) {
+ requestOptions = requestOptions || {};
+ requestOptions.url = requestOptions.url ? requestOptions.url : __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__utils_js__["f" /* joinUrl */])(this.options.baseUrl, this.options.registerUrl);
+ requestOptions[this.options.requestDataKey] = user || requestOptions[this.options.requestDataKey];
+ requestOptions.method = requestOptions.method || 'POST';
+ requestOptions.withCredentials = requestOptions.withCredentials || this.options.withCredentials;
+
+ return this.$http(requestOptions).then(response => {
+ this.setToken(response);
+ return response;
+ });
+ }
+
+ /**
+ * Logout current user
+ * @param {Object} requestOptions Logout request options object
+ * @return {Promise} Request promise
+ */
+ logout(requestOptions) {
+ if (!this.isAuthenticated()) {
+ return __WEBPACK_IMPORTED_MODULE_1__promise_js__["a" /* default */].reject(new Error('There is no currently authenticated user'));
+ }
+
+ requestOptions = requestOptions || {};
+ requestOptions.url = requestOptions.logoutUrl || this.options.logoutUrl;
+
+ if (requestOptions.url) {
+ requestOptions.method = requestOptions.method || 'POST';
+ requestOptions.withCredentials = requestOptions.withCredentials || this.options.withCredentials;
+
+ return this.$http(requestOptions).then(response => {
+ this.storage.removeItem(this.tokenName);
+ });
+ } else {
+ this.storage.removeItem(this.tokenName);
+ return __WEBPACK_IMPORTED_MODULE_1__promise_js__["a" /* default */].resolve();
+ }
+ }
+
+ /**
+ * Authenticate user using authentication provider
+ *
+ * @param {String} provider Provider name
+ * @param {Object} userData User data
+ * @param {Object} requestOptions Request options
+ * @return {Promise} Request promise
+ */
+ authenticate(provider, userData, requestOptions) {
+ return new __WEBPACK_IMPORTED_MODULE_1__promise_js__["a" /* default */]((resolve, reject) => {
+ var providerConfig = this.options.providers[provider];
+ if (!providerConfig) {
+ return reject(new Error('Unknown provider'));
+ }
+
+ let providerInstance;
+ switch (providerConfig.oauthType) {
+ case '1.0':
+ providerInstance = new __WEBPACK_IMPORTED_MODULE_5__oauth_oauth1_js__["a" /* default */](this.$http, this.storage, providerConfig, this.options);
+ break;
+ case '2.0':
+ providerInstance = new __WEBPACK_IMPORTED_MODULE_6__oauth_oauth2_js__["a" /* default */](this.$http, this.storage, providerConfig, this.options);
+ break;
+ default:
+ return reject(new Error('Invalid OAuth type'));
+ break;
+ }
+
+ return providerInstance.init(userData).then(response => {
+ this.setToken(response);
+ if (this.isAuthenticated()) {
+ return resolve(response);
+ } else {
+ return reject(new Error('Authentication failed'));
+ }
+ }).catch(() => {
+ reject(new Error('Authentication error occurred'));
+ });
+ });
+ }
+}
+/* harmony export (immutable) */ __webpack_exports__["a"] = VueAuthenticate;
+
+
+/***/ }),
+/* 10 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__popup_js__ = __webpack_require__(5);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_js__ = __webpack_require__(0);
+
+
+
+const defaultProviderConfig = {
+ name: null,
+ url: null,
+ authorizationEndpoint: null,
+ scope: null,
+ scopePrefix: null,
+ scopeDelimiter: null,
+ redirectUri: null,
+ requiredUrlParams: null,
+ defaultUrlParams: null,
+ oauthType: '1.0',
+ popupOptions: { width: null, height: null }
+};
+
+class OAuth {
+ constructor($http, storage, providerConfig, options) {
+ this.$http = $http;
+ this.storage = storage;
+ this.providerConfig = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["a" /* objectExtend */])({}, defaultProviderConfig);
+ this.providerConfig = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["a" /* objectExtend */])(this.providerConfig, providerConfig);
+ this.options = options;
+ }
+
+ /**
+ * Initialize OAuth1 process
+ * @param {Object} userData User data
+ * @return {Promise}
+ */
+ init(userData) {
+ this.oauthPopup = new __WEBPACK_IMPORTED_MODULE_0__popup_js__["a" /* default */]('about:blank', this.providerConfig.name, this.providerConfig.popupOptions);
+
+ if (window && !window['cordova']) {
+ this.oauthPopup.open(this.providerConfig.redirectUri, true);
+ }
+
+ return this.getRequestToken().then(response => {
+ return this.openPopup(response).then(popupResponse => {
+ return this.exchangeForToken(popupResponse, userData);
+ });
+ });
+ }
+
+ /**
+ * Get OAuth1 request token
+ * @return {Promise}
+ */
+ getRequestToken() {
+ let requestOptions = {};
+ requestOptions.method = 'POST';
+ requestOptions[this.options.requestDataKey] = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["a" /* objectExtend */])({}, this.providerConfig);
+ requestOptions.withCredentials = this.options.withCredentials;
+ if (this.options.baseUrl) {
+ requestOptions.url = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["f" /* joinUrl */])(this.options.baseUrl, this.providerConfig.url);
+ } else {
+ requestOptions.url = this.providerConfig.url;
+ }
+
+ return this.$http(requestOptions);
+ }
+
+ /**
+ * Open OAuth1 popup
+ * @param {Object} response Response object containing request token
+ * @return {Promise}
+ */
+ openPopup(response) {
+ const url = [this.providerConfig.authorizationEndpoint, this.buildQueryString(response[this.options.responseDataKey])].join('?');
+
+ this.oauthPopup.popup.location = url;
+ if (window && window['cordova']) {
+ return this.oauthPopup.open(this.providerConfig.redirectUri);
+ } else {
+ return this.oauthPopup.pooling(this.providerConfig.redirectUri);
+ }
+ }
+
+ /**
+ * Exchange token and token verifier for access token
+ * @param {Object} oauth OAuth data containing token and token verifier
+ * @param {Object} userData User data
+ * @return {Promise}
+ */
+ exchangeForToken(oauth, userData) {
+ let payload = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["a" /* objectExtend */])({}, userData);
+ payload = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["a" /* objectExtend */])(payload, oauth);
+ let requestOptions = {};
+ requestOptions.method = 'POST';
+ requestOptions[this.options.requestDataKey] = payload;
+ requestOptions.withCredentials = this.options.withCredentials;
+ if (this.options.baseUrl) {
+ requestOptions.url = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["f" /* joinUrl */])(this.options.baseUrl, this.providerConfig.url);
+ } else {
+ requestOptions.url = this.providerConfig.url;
+ }
+ return this.$http(requestOptions);
+ }
+
+ buildQueryString(params) {
+ const parsedParams = [];
+ for (var key in params) {
+ let value = params[key];
+ parsedParams.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
+ }
+ return parsedParams.join('&');
+ }
+}
+/* harmony export (immutable) */ __webpack_exports__["a"] = OAuth;
+
+
+/***/ }),
+/* 11 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__popup_js__ = __webpack_require__(5);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_js__ = __webpack_require__(0);
+
+
+
+/**
+ * Default provider configuration
+ * @type {Object}
+ */
+const defaultProviderConfig = {
+ name: null,
+ url: null,
+ clientId: null,
+ authorizationEndpoint: null,
+ redirectUri: null,
+ scope: null,
+ scopePrefix: null,
+ scopeDelimiter: null,
+ state: null,
+ requiredUrlParams: null,
+ defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],
+ responseType: 'code',
+ responseParams: {
+ code: 'code',
+ clientId: 'clientId',
+ redirectUri: 'redirectUri'
+ },
+ oauthType: '2.0',
+ popupOptions: { width: null, height: null }
+};
+
+class OAuth2 {
+ constructor($http, storage, providerConfig, options) {
+ this.$http = $http;
+ this.storage = storage;
+ this.providerConfig = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["a" /* objectExtend */])({}, defaultProviderConfig);
+ this.providerConfig = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["a" /* objectExtend */])(this.providerConfig, providerConfig);
+ this.options = options;
+ }
+
+ init(userData) {
+ let stateName = this.providerConfig.name;
+ if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["b" /* isFunction */])(this.providerConfig.state)) {
+ this.storage.setItem(stateName, this.providerConfig.state());
+ } else if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["d" /* isString */])(this.providerConfig.state)) {
+ this.storage.setItem(stateName, this.providerConfig.state);
+ }
+
+ let url = [this.providerConfig.authorizationEndpoint, this._stringifyRequestParams()].join('?');
+
+ this.oauthPopup = new __WEBPACK_IMPORTED_MODULE_0__popup_js__["a" /* default */](url, this.providerConfig.name, this.providerConfig.popupOptions);
+
+ return new Promise((resolve, reject) => {
+ this.oauthPopup.open(this.providerConfig.redirectUri).then(response => {
+ if (this.providerConfig.responseType === 'token' || !this.providerConfig.url) {
+ return resolve(response);
+ }
+
+ if (response.state && response.state !== this.storage.getItem(stateName)) {
+ return reject(new Error('State parameter value does not match original OAuth request state value'));
+ }
+
+ resolve(this.exchangeForToken(response, userData));
+ }).catch(err => {
+ reject(err);
+ });
+ });
+ }
+
+ /**
+ * Exchange temporary oauth data for access token
+ * @author Sahat Yalkabov
+ * @copyright Method taken from https://github.com/sahat/satellizer
+ *
+ * @param {[type]} oauth [description]
+ * @param {[type]} userData [description]
+ * @return {[type]} [description]
+ */
+ exchangeForToken(oauth, userData) {
+ let payload = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["a" /* objectExtend */])({}, userData);
+
+ for (let key in defaultProviderConfig.responseParams) {
+ let value = defaultProviderConfig[key];
+
+ switch (key) {
+ case 'code':
+ payload[key] = oauth.code;
+ break;
+ case 'clientId':
+ payload[key] = this.providerConfig.clientId;
+ break;
+ case 'redirectUri':
+ payload[key] = this.providerConfig.redirectUri;
+ break;
+ default:
+ payload[key] = oauth[key];
+ }
+ }
+
+ if (oauth.state) {
+ payload.state = oauth.state;
+ }
+
+ let exchangeTokenUrl;
+ if (this.options.baseUrl) {
+ exchangeTokenUrl = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["f" /* joinUrl */])(this.options.baseUrl, this.providerConfig.url);
+ } else {
+ exchangeTokenUrl = this.providerConfig.url;
+ }
+
+ return this.$http.post(exchangeTokenUrl, payload, {
+ withCredentials: this.options.withCredentials
+ });
+ }
+
+ /**
+ * Stringify oauth params
+ * @author Sahat Yalkabov
+ * @copyright Method taken from https://github.com/sahat/satellizer
+ *
+ * @return {String}
+ */
+ _stringifyRequestParams() {
+ let keyValuePairs = [];
+ let paramCategories = ['defaultUrlParams', 'requiredUrlParams', 'optionalUrlParams'];
+
+ paramCategories.forEach(categoryName => {
+ if (!this.providerConfig[categoryName]) return;
+ if (!Array.isArray(this.providerConfig[categoryName])) return;
+
+ this.providerConfig[categoryName].forEach(paramName => {
+ let camelCaseParamName = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["g" /* camelCase */])(paramName);
+ let paramValue = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_js__["b" /* isFunction */])(this.providerConfig[paramName]) ? this.providerConfig[paramName]() : this.providerConfig[camelCaseParamName];
+
+ if (paramName === 'redirect_uri' && !paramValue) return;
+
+ if (paramName === 'state') {
+ const stateName = this.defaults.name + '_state';
+ paramValue = encodeURIComponent(this.storage.getItem(stateName));
+ }
+ if (paramName === 'scope' && Array.isArray(paramValue)) {
+ paramValue = paramValue.join(this.providerConfig.scopeDelimiter);
+ if (this.providerConfig.scopePrefix) {
+ paramValue = [this.providerConfig.scopePrefix, paramValue].join(this.providerConfig.scopeDelimiter);
+ }
+ }
+
+ keyValuePairs.push([paramName, paramValue]);
+ });
+ });
+
+ return keyValuePairs.map(param => {
+ return param.join('=');
+ }).join('&');
+ }
+}
+/* harmony export (immutable) */ __webpack_exports__["a"] = OAuth2;
+
+
+/***/ }),
+/* 12 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+/**
+ * @author Sahat Yalkabov
+ * @copyright Configuration taken from https://github.com/sahat/satellizer
+ * and extended to fit vue-authenticate library
+ */
+/* harmony default export */ __webpack_exports__["a"] = ({
+ baseUrl: null,
+ tokenName: 'token',
+ tokenPrefix: 'vueauth',
+ tokenHeader: 'Authorization',
+ tokenType: 'Bearer',
+ loginUrl: '/auth/login',
+ registerUrl: '/auth/register',
+ logoutUrl: null,
+ storageType: 'localStorage',
+ storageNamespace: 'vue-authenticate',
+ requestDataKey: 'body',
+ responseDataKey: 'body',
+
+ providers: {
+ facebook: {
+ name: 'facebook',
+ url: '/auth/facebook',
+ authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',
+ redirectUri: null,
+ requiredUrlParams: ['display', 'scope'],
+ scope: ['email'],
+ scopeDelimiter: ',',
+ display: 'popup',
+ oauthType: '2.0',
+ popupOptions: { width: 580, height: 400 }
+ },
+
+ google: {
+ name: 'google',
+ url: '/auth/google',
+ authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
+ redirectUri: null,
+ requiredUrlParams: ['scope'],
+ optionalUrlParams: ['display'],
+ scope: ['profile', 'email'],
+ scopePrefix: 'openid',
+ scopeDelimiter: ' ',
+ display: 'popup',
+ oauthType: '2.0',
+ popupOptions: { width: 452, height: 633 }
+ },
+
+ github: {
+ name: 'github',
+ url: '/auth/github',
+ authorizationEndpoint: 'https://github.com/login/oauth/authorize',
+ redirectUri: null,
+ optionalUrlParams: ['scope'],
+ scope: ['user:email'],
+ scopeDelimiter: ' ',
+ oauthType: '2.0',
+ popupOptions: { width: 1020, height: 618 }
+ },
+
+ twitter: {
+ name: 'twitter',
+ url: '/auth/twitter',
+ authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',
+ redirectUri: null,
+ oauthType: '1.0',
+ popupOptions: { width: 495, height: 645 }
+ }
+ }
+});
+
+/***/ }),
+/* 13 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__storage_local_storage_js__ = __webpack_require__(14);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__storage_memory_storage_js__ = __webpack_require__(15);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__storage_session_storage_js__ = __webpack_require__(16);
+/* harmony export (immutable) */ __webpack_exports__["a"] = StorageFactory;
+
+
+
+
+function StorageFactory(options) {
+ switch (options.storageType) {
+ case 'localStorage':
+ try {
+ window.localStorage.setItem('testKey', 'test');
+ window.localStorage.removeItem('testKey');
+ return new __WEBPACK_IMPORTED_MODULE_0__storage_local_storage_js__["a" /* default */](options.storageNamespace);
+ } catch (e) {}
+
+ case 'sessionStorage':
+ try {
+ window.sessionStorage.setItem('testKey', 'test');
+ window.sessionStorage.removeItem('testKey');
+ return new __WEBPACK_IMPORTED_MODULE_2__storage_session_storage_js__["a" /* default */](options.storageNamespace);
+ } catch (e) {}
+
+ case 'memoryStorage':
+ default:
+ return new __WEBPACK_IMPORTED_MODULE_1__storage_memory_storage_js__["a" /* default */](options.storageNamespace);
+ break;
+ }
+}
+
+/***/ }),
+/* 14 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+class LocalStorage {
+ constructor(namespace) {
+ this.namespace = namespace || null;
+ }
+
+ setItem(key, value) {
+ window.localStorage.setItem(this._getStorageKey(key), value);
+ }
+
+ getItem(key) {
+ return window.localStorage.getItem(this._getStorageKey(key));
+ }
+
+ removeItem(key) {
+ window.localStorage.removeItem(this._getStorageKey(key));
+ }
+
+ _getStorageKey(key) {
+ if (this.namespace) {
+ return [this.namespace, key].join('.');
+ }
+ return key;
+ }
+}
+
+/* harmony default export */ __webpack_exports__["a"] = (LocalStorage);
+
+/***/ }),
+/* 15 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+class MemoryStorage {
+ constructor(namespace) {
+ this.namespace = namespace || null;
+ this._storage = {};
+ }
+
+ setItem(key, value) {
+ this._storage[this._getStorageKey(key)] = value;
+ }
+
+ getItem(key) {
+ return this._storage[this._getStorageKey(key)];
+ }
+
+ removeItem(key) {
+ delete this._storage[this._getStorageKey(key)];
+ }
+
+ _getStorageKey(key) {
+ if (this.namespace) {
+ return [this.namespace, key].join('.');
+ }
+ return key;
+ }
+}
+
+/* harmony default export */ __webpack_exports__["a"] = (MemoryStorage);
+
+/***/ }),
+/* 16 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+class LocalStorage {
+ constructor(namespace) {
+ this.namespace = namespace || null;
+ }
+
+ setItem(key, value) {
+ window.sessionStorage.setItem(this._getStorageKey(key), value);
+ }
+
+ getItem(key) {
+ return window.sessionStorage.getItem(this._getStorageKey(key));
+ }
+
+ removeItem(key) {
+ window.sessionStorage.removeItem(this._getStorageKey(key));
+ }
+
+ _getStorageKey(key) {
+ if (this.namespace) {
+ return [this.namespace, key].join('.');
+ }
+ return key;
+ }
+}
+
+/* harmony default export */ __webpack_exports__["a"] = (LocalStorage);
+
+/***/ }),
+/* 17 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_vue__ = __webpack_require__(4);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_vue__);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_vue_router__ = __webpack_require__(8);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_vue_resource__ = __webpack_require__(7);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_vue_resource___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_vue_resource__);
+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__src_index_js__ = __webpack_require__(6);
+
+
+ // Comment for axios example
+
+// import axios from 'axios' // Uncomment for axios example
+// import VueAxios from 'vue-axios' // Uncomment for axios example
+
+
+
+__WEBPACK_IMPORTED_MODULE_0_vue___default.a.use(__WEBPACK_IMPORTED_MODULE_1_vue_router__["a" /* default */]);
+__WEBPACK_IMPORTED_MODULE_0_vue___default.a.use(__WEBPACK_IMPORTED_MODULE_2_vue_resource___default.a); // Comment for axios example
+
+// Vue.use(VueAxios, axios) // Uncomment for axios example
+
+__WEBPACK_IMPORTED_MODULE_0_vue___default.a.use(__WEBPACK_IMPORTED_MODULE_3__src_index_js__["a" /* default */], {});
+
+const router = new __WEBPACK_IMPORTED_MODULE_1_vue_router__["a" /* default */]({
+ mode: 'history',
+ routes: [{
+ path: '/',
+ name: 'index',
+ component: {
+ data: function () {
+ return {
+ response: null
+ };
+ },
+ template: `
+
+
+
+
+
+
+
+
+
+
+
{{JSON.stringify(response, null, 2)}}
+
+ `,
+ methods: {
+ authLogin: function () {
+ let user = {
+ email: 'john.doe@domain.com',
+ password: 'pass123456'
+ };
+
+ if (this.$auth.isAuthenticated()) {
+ this.$auth.logout();
+ }
+
+ this.$auth.login(user).then(response => {
+ this.response = response;
+ console.log(this.$auth.isAuthenticated());
+ console.log(this.$auth.getPayload());
+ });
+ },
+
+ authRegister: function () {
+ let user = {
+ name: 'John Doe',
+ email: 'john.doe@domain.com',
+ password: 'pass123456'
+ };
+
+ if (this.$auth.isAuthenticated()) {
+ this.$auth.logout();
+ }
+
+ this.$auth.register(user).then(response => {
+ this.response = response;
+ console.log(this.$auth.isAuthenticated());
+ console.log(this.$auth.getPayload());
+ });
+ },
+
+ authLogout: function () {
+ this.$auth.logout().then(() => {
+ if (!this.$auth.isAuthenticated()) {
+ this.response = null;
+ } else {
+ console.log(this.$auth.isAuthenticated());
+ }
+ });
+ },
+
+ auth: function (provider) {
+ this.$auth.logout();
+ this.response = null;
+
+ console.log('User authenticated: ', this.$auth.isAuthenticated());
+
+ this.$auth.authenticate(provider).then(authResponse => {
+ if (provider === 'github') {
+ this.$http.get('https://api.github.com/user').then(response => {
+ this.response = response;
+ });
+ } else if (provider === 'facebook') {
+ this.$http.get('https://graph.facebook.com/v2.5/me', {
+ params: { access_token: this.$auth.getToken() }
+ }).then(response => {
+ this.response = response;
+ });
+ } else if (provider === 'google') {
+ this.$http.get('https://www.googleapis.com/plus/v1/people/me/openIdConnect').then(response => {
+ this.response = response;
+ });
+ } else if (provider === 'twitter') {
+ this.response = authResponse.body.profile;
+ }
+ });
+ }
+ }
+ }
+ }, {
+ path: '/auth/callback',
+ component: {
+ template: '',
+ mounted: function () {}
+ }
+ }]
+});
+
+const app = new __WEBPACK_IMPORTED_MODULE_0_vue___default.a({
+ router
+}).$mount('#app');
+
+/***/ }),
+/* 18 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"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
+}
+
+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, j, 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, j = 0; i < l; i += 4, j += 3) {
+ 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) + (uint8[i + 1] << 8) + (uint8[i + 2])
+ 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 - 2] << 8) + (uint8[len - 1])
+ output += lookup[tmp >> 10]
+ output += lookup[(tmp >> 4) & 0x3F]
+ output += lookup[(tmp << 2) & 0x3F]
+ output += '='
+ }
+
+ parts.push(output)
+
+ return parts.join('')
+}
+
+
+/***/ }),
+/* 19 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+/* WEBPACK VAR INJECTION */(function(global) {/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+/* eslint-disable no-proto */
+
+
+
+var base64 = __webpack_require__(18)
+var ieee754 = __webpack_require__(20)
+var isArray = __webpack_require__(21)
+
+exports.Buffer = Buffer
+exports.SlowBuffer = SlowBuffer
+exports.INSPECT_MAX_BYTES = 50
+
+/**
+ * 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.
+ *
+ * - 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()
+
+/*
+ * Export kMaxLength after typed array support is determined.
+ */
+exports.kMaxLength = kMaxLength()
+
+function typedArraySupport () {
+ try {
+ var arr = new Uint8Array(1)
+ arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
+ return arr.foo() === 42 && // typed array instances can be augmented
+ 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
+}
+
+function createBuffer (that, length) {
+ if (kMaxLength() < length) {
+ throw new RangeError('Invalid typed array length')
+ }
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = new Uint8Array(length)
+ that.__proto__ = Buffer.prototype
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ if (that === null) {
+ that = new Buffer(length)
+ }
+ that.length = length
+ }
+
+ return that
+}
+
+/**
+ * The Buffer constructor returns instances of `Uint8Array` that have their
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
+ * returns a single octet.
+ *
+ * The `Uint8Array` prototype remains unmodified.
+ */
+
+function Buffer (arg, encodingOrOffset, length) {
+ if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
+ return new Buffer(arg, encodingOrOffset, length)
+ }
+
+ // Common case.
+ if (typeof arg === 'number') {
+ if (typeof encodingOrOffset === 'string') {
+ throw new Error(
+ 'If encoding is specified then the first argument must be a string'
+ )
+ }
+ return allocUnsafe(this, arg)
+ }
+ return from(this, arg, encodingOrOffset, length)
+}
+
+Buffer.poolSize = 8192 // not used by this implementation
+
+// TODO: Legacy, not needed anymore. Remove in next major version.
+Buffer._augment = function (arr) {
+ arr.__proto__ = Buffer.prototype
+ return arr
+}
+
+function from (that, value, encodingOrOffset, length) {
+ if (typeof value === 'number') {
+ throw new TypeError('"value" argument must not be a number')
+ }
+
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
+ return fromArrayBuffer(that, value, encodingOrOffset, length)
+ }
+
+ if (typeof value === 'string') {
+ return fromString(that, value, encodingOrOffset)
+ }
+
+ return fromObject(that, value)
+}
+
+/**
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
+ * if value is a number.
+ * Buffer.from(str[, encoding])
+ * Buffer.from(array)
+ * Buffer.from(buffer)
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
+ **/
+Buffer.from = function (value, encodingOrOffset, length) {
+ return from(null, value, encodingOrOffset, length)
+}
+
+if (Buffer.TYPED_ARRAY_SUPPORT) {
+ Buffer.prototype.__proto__ = Uint8Array.prototype
+ Buffer.__proto__ = Uint8Array
+ if (typeof Symbol !== 'undefined' && Symbol.species &&
+ Buffer[Symbol.species] === Buffer) {
+ // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
+ Object.defineProperty(Buffer, Symbol.species, {
+ value: null,
+ configurable: true
+ })
+ }
+}
+
+function assertSize (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('"size" argument must be a number')
+ } else if (size < 0) {
+ throw new RangeError('"size" argument must not be negative')
+ }
+}
+
+function alloc (that, size, fill, encoding) {
+ assertSize(size)
+ if (size <= 0) {
+ return createBuffer(that, size)
+ }
+ if (fill !== undefined) {
+ // Only pay attention to encoding if it's a string. This
+ // prevents accidentally sending in a number that would
+ // be interpretted as a start offset.
+ return typeof encoding === 'string'
+ ? createBuffer(that, size).fill(fill, encoding)
+ : createBuffer(that, size).fill(fill)
+ }
+ return createBuffer(that, size)
+}
+
+/**
+ * Creates a new filled Buffer instance.
+ * alloc(size[, fill[, encoding]])
+ **/
+Buffer.alloc = function (size, fill, encoding) {
+ return alloc(null, size, fill, encoding)
+}
+
+function allocUnsafe (that, size) {
+ assertSize(size)
+ that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
+ for (var i = 0; i < size; ++i) {
+ that[i] = 0
+ }
+ }
+ return that
+}
+
+/**
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
+ * */
+Buffer.allocUnsafe = function (size) {
+ return allocUnsafe(null, size)
+}
+/**
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
+ */
+Buffer.allocUnsafeSlow = function (size) {
+ return allocUnsafe(null, size)
+}
+
+function fromString (that, string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') {
+ encoding = 'utf8'
+ }
+
+ if (!Buffer.isEncoding(encoding)) {
+ throw new TypeError('"encoding" must be a valid string encoding')
+ }
+
+ var length = byteLength(string, encoding) | 0
+ that = createBuffer(that, length)
+
+ var actual = that.write(string, encoding)
+
+ if (actual !== length) {
+ // Writing a hex string, for example, that contains invalid characters will
+ // cause everything after the first invalid character to be ignored. (e.g.
+ // 'abxxcd' will be treated as 'ab')
+ that = that.slice(0, actual)
+ }
+
+ return that
+}
+
+function fromArrayLike (that, array) {
+ var length = array.length < 0 ? 0 : checked(array.length) | 0
+ that = createBuffer(that, length)
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255
+ }
+ return that
+}
+
+function fromArrayBuffer (that, array, byteOffset, length) {
+ array.byteLength // this throws if `array` is not a valid ArrayBuffer
+
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
+ throw new RangeError('\'offset\' is out of bounds')
+ }
+
+ if (array.byteLength < byteOffset + (length || 0)) {
+ throw new RangeError('\'length\' is out of bounds')
+ }
+
+ if (byteOffset === undefined && length === undefined) {
+ array = new Uint8Array(array)
+ } else if (length === undefined) {
+ array = new Uint8Array(array, byteOffset)
+ } else {
+ array = new Uint8Array(array, byteOffset, length)
+ }
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = array
+ that.__proto__ = Buffer.prototype
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ that = fromArrayLike(that, array)
+ }
+ return that
+}
+
+function fromObject (that, obj) {
+ if (Buffer.isBuffer(obj)) {
+ var len = checked(obj.length) | 0
+ that = createBuffer(that, len)
+
+ if (that.length === 0) {
+ return that
+ }
+
+ obj.copy(that, 0, 0, len)
+ return that
+ }
+
+ if (obj) {
+ if ((typeof ArrayBuffer !== 'undefined' &&
+ obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
+ if (typeof obj.length !== 'number' || isnan(obj.length)) {
+ return createBuffer(that, 0)
+ }
+ return fromArrayLike(that, obj)
+ }
+
+ if (obj.type === 'Buffer' && isArray(obj.data)) {
+ return fromArrayLike(that, obj.data)
+ }
+ }
+
+ throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
+}
+
+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 (length) {
+ if (+length != length) { // eslint-disable-line eqeqeq
+ length = 0
+ }
+ return Buffer.alloc(+length)
+}
+
+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
+
+ 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
+}
+
+Buffer.isEncoding = function isEncoding (encoding) {
+ switch (String(encoding).toLowerCase()) {
+ case 'hex':
+ case 'utf8':
+ case 'utf-8':
+ case 'ascii':
+ case 'latin1':
+ case 'binary':
+ case 'base64':
+ 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 Buffer.alloc(0)
+ }
+
+ var i
+ if (length === undefined) {
+ length = 0
+ for (i = 0; i < list.length; ++i) {
+ length += list[i].length
+ }
+ }
+
+ var buffer = Buffer.allocUnsafe(length)
+ var pos = 0
+ for (i = 0; i < list.length; ++i) {
+ var buf = list[i]
+ if (!Buffer.isBuffer(buf)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
+ }
+ buf.copy(buffer, pos)
+ pos += buf.length
+ }
+ return buffer
+}
+
+function byteLength (string, encoding) {
+ if (Buffer.isBuffer(string)) {
+ return string.length
+ }
+ if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
+ (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
+ return string.byteLength
+ }
+ 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 'latin1':
+ case 'binary':
+ return len
+ case 'utf8':
+ case 'utf-8':
+ case undefined:
+ 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
+
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
+ // property of a typed array.
+
+ // This behaves neither like String nor Uint8Array in that we set start/end
+ // to their upper/lower bounds if the value passed is out of range.
+ // undefined is handled specially as per ECMA-262 6th Edition,
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
+ if (start === undefined || start < 0) {
+ start = 0
+ }
+ // Return early if start > this.length. Done here to prevent potential uint32
+ // coercion fail below.
+ if (start > this.length) {
+ return ''
+ }
+
+ if (end === undefined || end > this.length) {
+ end = this.length
+ }
+
+ if (end <= 0) {
+ return ''
+ }
+
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
+ end >>>= 0
+ start >>>= 0
+
+ if (end <= start) {
+ return ''
+ }
+
+ if (!encoding) encoding = 'utf8'
+
+ 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 'latin1':
+ case 'binary':
+ return latin1Slice(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
+ }
+ }
+}
+
+// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
+// Buffer instances.
+Buffer.prototype._isBuffer = true
+
+function swap (b, n, m) {
+ var i = b[n]
+ b[n] = b[m]
+ b[m] = i
+}
+
+Buffer.prototype.swap16 = function swap16 () {
+ var len = this.length
+ if (len % 2 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
+ }
+ for (var i = 0; i < len; i += 2) {
+ swap(this, i, i + 1)
+ }
+ return this
+}
+
+Buffer.prototype.swap32 = function swap32 () {
+ var len = this.length
+ if (len % 4 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
+ }
+ for (var i = 0; i < len; i += 4) {
+ swap(this, i, i + 3)
+ swap(this, i + 1, i + 2)
+ }
+ return this
+}
+
+Buffer.prototype.swap64 = function swap64 () {
+ var len = this.length
+ if (len % 8 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
+ }
+ for (var i = 0; i < len; i += 8) {
+ swap(this, i, i + 7)
+ swap(this, i + 1, i + 6)
+ swap(this, i + 2, i + 5)
+ swap(this, i + 3, i + 4)
+ }
+ return this
+}
+
+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 (target, start, end, thisStart, thisEnd) {
+ if (!Buffer.isBuffer(target)) {
+ throw new TypeError('Argument must be a Buffer')
+ }
+
+ if (start === undefined) {
+ start = 0
+ }
+ if (end === undefined) {
+ end = target ? target.length : 0
+ }
+ if (thisStart === undefined) {
+ thisStart = 0
+ }
+ if (thisEnd === undefined) {
+ thisEnd = this.length
+ }
+
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
+ throw new RangeError('out of range index')
+ }
+
+ if (thisStart >= thisEnd && start >= end) {
+ return 0
+ }
+ if (thisStart >= thisEnd) {
+ return -1
+ }
+ if (start >= end) {
+ return 1
+ }
+
+ start >>>= 0
+ end >>>= 0
+ thisStart >>>= 0
+ thisEnd >>>= 0
+
+ if (this === target) return 0
+
+ var x = thisEnd - thisStart
+ var y = end - start
+ var len = Math.min(x, y)
+
+ var thisCopy = this.slice(thisStart, thisEnd)
+ var targetCopy = target.slice(start, end)
+
+ for (var i = 0; i < len; ++i) {
+ if (thisCopy[i] !== targetCopy[i]) {
+ x = thisCopy[i]
+ y = targetCopy[i]
+ break
+ }
+ }
+
+ if (x < y) return -1
+ if (y < x) return 1
+ return 0
+}
+
+// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
+// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
+//
+// Arguments:
+// - buffer - a Buffer to search
+// - val - a string, Buffer, or number
+// - byteOffset - an index into `buffer`; will be clamped to an int32
+// - encoding - an optional encoding, relevant is val is a string
+// - dir - true for indexOf, false for lastIndexOf
+function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
+ // Empty buffer means no match
+ if (buffer.length === 0) return -1
+
+ // Normalize byteOffset
+ if (typeof byteOffset === 'string') {
+ encoding = byteOffset
+ byteOffset = 0
+ } else if (byteOffset > 0x7fffffff) {
+ byteOffset = 0x7fffffff
+ } else if (byteOffset < -0x80000000) {
+ byteOffset = -0x80000000
+ }
+ byteOffset = +byteOffset // Coerce to Number.
+ if (isNaN(byteOffset)) {
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
+ byteOffset = dir ? 0 : (buffer.length - 1)
+ }
+
+ // Normalize byteOffset: negative offsets start from the end of the buffer
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset
+ if (byteOffset >= buffer.length) {
+ if (dir) return -1
+ else byteOffset = buffer.length - 1
+ } else if (byteOffset < 0) {
+ if (dir) byteOffset = 0
+ else return -1
+ }
+
+ // Normalize val
+ if (typeof val === 'string') {
+ val = Buffer.from(val, encoding)
+ }
+
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
+ if (Buffer.isBuffer(val)) {
+ // Special case: looking for empty string/buffer always fails
+ if (val.length === 0) {
+ return -1
+ }
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
+ } else if (typeof val === 'number') {
+ val = val & 0xFF // Search for a byte value [0-255]
+ if (Buffer.TYPED_ARRAY_SUPPORT &&
+ typeof Uint8Array.prototype.indexOf === 'function') {
+ if (dir) {
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
+ } else {
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
+ }
+ }
+ return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
+ }
+
+ throw new TypeError('val must be string, number or Buffer')
+}
+
+function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
+ var indexSize = 1
+ var arrLength = arr.length
+ var valLength = val.length
+
+ if (encoding !== undefined) {
+ encoding = String(encoding).toLowerCase()
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
+ encoding === 'utf16le' || encoding === 'utf-16le') {
+ if (arr.length < 2 || val.length < 2) {
+ return -1
+ }
+ indexSize = 2
+ arrLength /= 2
+ valLength /= 2
+ byteOffset /= 2
+ }
+ }
+
+ function read (buf, i) {
+ if (indexSize === 1) {
+ return buf[i]
+ } else {
+ return buf.readUInt16BE(i * indexSize)
+ }
+ }
+
+ var i
+ if (dir) {
+ var foundIndex = -1
+ for (i = byteOffset; i < arrLength; i++) {
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
+ if (foundIndex === -1) foundIndex = i
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
+ } else {
+ if (foundIndex !== -1) i -= i - foundIndex
+ foundIndex = -1
+ }
+ }
+ } else {
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
+ for (i = byteOffset; i >= 0; i--) {
+ var found = true
+ for (var j = 0; j < valLength; j++) {
+ if (read(arr, i + j) !== read(val, j)) {
+ found = false
+ break
+ }
+ }
+ if (found) return i
+ }
+ }
+
+ return -1
+}
+
+Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
+ return this.indexOf(val, byteOffset, encoding) !== -1
+}
+
+Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
+}
+
+Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
+}
+
+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 TypeError('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)) return i
+ 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 latin1Write (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 {
+ throw new Error(
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
+ )
+ }
+
+ 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 'latin1':
+ case 'binary':
+ return latin1Write(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 latin1Slice (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 = this.subarray(start, end)
+ newBuf.__proto__ = Buffer.prototype
+ } else {
+ var sliceLen = end - start
+ newBuf = new Buffer(sliceLen, undefined)
+ for (var i = 0; i < sliceLen; ++i) {
+ newBuf[i] = this[i + start]
+ }
+ }
+
+ 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" argument must be a Buffer instance')
+ if (value > max || value < min) throw new RangeError('"value" argument 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) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
+ checkInt(this, value, offset, byteLength, maxBytes, 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) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
+ checkInt(this, value, offset, byteLength, maxBytes, 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 = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
+ sub = 1
+ }
+ 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 = 0
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
+ sub = 1
+ }
+ 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 (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 {
+ Uint8Array.prototype.set.call(
+ target,
+ this.subarray(start, start + len),
+ targetStart
+ )
+ }
+
+ return len
+}
+
+// Usage:
+// buffer.fill(number[, offset[, end]])
+// buffer.fill(buffer[, offset[, end]])
+// buffer.fill(string[, offset[, end]][, encoding])
+Buffer.prototype.fill = function fill (val, start, end, encoding) {
+ // Handle string cases:
+ if (typeof val === 'string') {
+ if (typeof start === 'string') {
+ encoding = start
+ start = 0
+ end = this.length
+ } else if (typeof end === 'string') {
+ encoding = end
+ end = this.length
+ }
+ if (val.length === 1) {
+ var code = val.charCodeAt(0)
+ if (code < 256) {
+ val = code
+ }
+ }
+ if (encoding !== undefined && typeof encoding !== 'string') {
+ throw new TypeError('encoding must be a string')
+ }
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
+ throw new TypeError('Unknown encoding: ' + encoding)
+ }
+ } else if (typeof val === 'number') {
+ val = val & 255
+ }
+
+ // Invalid ranges are not set to a default, so can range check early.
+ if (start < 0 || this.length < start || this.length < end) {
+ throw new RangeError('Out of range index')
+ }
+
+ if (end <= start) {
+ return this
+ }
+
+ start = start >>> 0
+ end = end === undefined ? this.length : end >>> 0
+
+ if (!val) val = 0
+
+ var i
+ if (typeof val === 'number') {
+ for (i = start; i < end; ++i) {
+ this[i] = val
+ }
+ } else {
+ var bytes = Buffer.isBuffer(val)
+ ? val
+ : utf8ToBytes(new Buffer(val, encoding).toString())
+ var len = bytes.length
+ for (i = 0; i < end - start; ++i) {
+ this[i + start] = bytes[i % len]
+ }
+ }
+
+ return this
+}
+
+// HELPER FUNCTIONS
+// ================
+
+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
+}
+
+function isnan (val) {
+ return val !== val // eslint-disable-line no-self-compare
+}
+
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
+
+/***/ }),
+/* 20 */
+/***/ (function(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
+}
+
+
+/***/ }),
+/* 21 */
+/***/ (function(module, exports) {
+
+var toString = {}.toString;
+
+module.exports = Array.isArray || function (arr) {
+ return toString.call(arr) == '[object Array]';
+};
+
+
+/***/ }),
+/* 22 */
+/***/ (function(module, exports, __webpack_require__) {
+
+/* WEBPACK VAR INJECTION */(function(setImmediate) {(function (root) {
+
+ // Store setTimeout reference so promise-polyfill will be unaffected by
+ // other code modifying setTimeout (like sinon.useFakeTimers())
+ var setTimeoutFunc = setTimeout;
+
+ function noop() {}
+
+ // Polyfill for Function.prototype.bind
+ function bind(fn, thisArg) {
+ return function () {
+ fn.apply(thisArg, arguments);
+ };
+ }
+
+ function Promise(fn) {
+ if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
+ if (typeof fn !== 'function') throw new TypeError('not a function');
+ this._state = 0;
+ this._handled = false;
+ this._value = undefined;
+ this._deferreds = [];
+
+ doResolve(fn, this);
+ }
+
+ function handle(self, deferred) {
+ while (self._state === 3) {
+ self = self._value;
+ }
+ if (self._state === 0) {
+ self._deferreds.push(deferred);
+ return;
+ }
+ self._handled = true;
+ Promise._immediateFn(function () {
+ var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
+ if (cb === null) {
+ (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
+ return;
+ }
+ var ret;
+ try {
+ ret = cb(self._value);
+ } catch (e) {
+ reject(deferred.promise, e);
+ return;
+ }
+ resolve(deferred.promise, ret);
+ });
+ }
+
+ function resolve(self, newValue) {
+ try {
+ // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
+ if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
+ if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
+ var then = newValue.then;
+ if (newValue instanceof Promise) {
+ self._state = 3;
+ self._value = newValue;
+ finale(self);
+ return;
+ } else if (typeof then === 'function') {
+ doResolve(bind(then, newValue), self);
+ return;
+ }
+ }
+ self._state = 1;
+ self._value = newValue;
+ finale(self);
+ } catch (e) {
+ reject(self, e);
+ }
+ }
+
+ function reject(self, newValue) {
+ self._state = 2;
+ self._value = newValue;
+ finale(self);
+ }
+
+ function finale(self) {
+ if (self._state === 2 && self._deferreds.length === 0) {
+ Promise._immediateFn(function() {
+ if (!self._handled) {
+ Promise._unhandledRejectionFn(self._value);
+ }
+ });
+ }
+
+ for (var i = 0, len = self._deferreds.length; i < len; i++) {
+ handle(self, self._deferreds[i]);
+ }
+ self._deferreds = null;
+ }
+
+ function Handler(onFulfilled, onRejected, promise) {
+ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
+ this.onRejected = typeof onRejected === 'function' ? onRejected : null;
+ this.promise = promise;
+ }
+
+ /**
+ * Take a potentially misbehaving resolver function and make sure
+ * onFulfilled and onRejected are only called once.
+ *
+ * Makes no guarantees about asynchrony.
+ */
+ function doResolve(fn, self) {
+ var done = false;
+ try {
+ fn(function (value) {
+ if (done) return;
+ done = true;
+ resolve(self, value);
+ }, function (reason) {
+ if (done) return;
+ done = true;
+ reject(self, reason);
+ });
+ } catch (ex) {
+ if (done) return;
+ done = true;
+ reject(self, ex);
+ }
+ }
+
+ Promise.prototype['catch'] = function (onRejected) {
+ return this.then(null, onRejected);
+ };
+
+ Promise.prototype.then = function (onFulfilled, onRejected) {
+ var prom = new (this.constructor)(noop);
+
+ handle(this, new Handler(onFulfilled, onRejected, prom));
+ return prom;
+ };
+
+ Promise.all = function (arr) {
+ var args = Array.prototype.slice.call(arr);
+
+ return new Promise(function (resolve, reject) {
+ if (args.length === 0) return resolve([]);
+ var remaining = args.length;
+
+ function res(i, val) {
+ try {
+ if (val && (typeof val === 'object' || typeof val === 'function')) {
+ var then = val.then;
+ if (typeof then === 'function') {
+ then.call(val, function (val) {
+ res(i, val);
+ }, reject);
+ return;
+ }
+ }
+ args[i] = val;
+ if (--remaining === 0) {
+ resolve(args);
+ }
+ } catch (ex) {
+ reject(ex);
+ }
+ }
+
+ for (var i = 0; i < args.length; i++) {
+ res(i, args[i]);
+ }
+ });
+ };
+
+ Promise.resolve = function (value) {
+ if (value && typeof value === 'object' && value.constructor === Promise) {
+ return value;
+ }
+
+ return new Promise(function (resolve) {
+ resolve(value);
+ });
+ };
+
+ Promise.reject = function (value) {
+ return new Promise(function (resolve, reject) {
+ reject(value);
+ });
+ };
+
+ Promise.race = function (values) {
+ return new Promise(function (resolve, reject) {
+ for (var i = 0, len = values.length; i < len; i++) {
+ values[i].then(resolve, reject);
+ }
+ });
+ };
+
+ // Use polyfill for setImmediate for performance gains
+ Promise._immediateFn = (typeof setImmediate === 'function' && function (fn) { setImmediate(fn); }) ||
+ function (fn) {
+ setTimeoutFunc(fn, 0);
+ };
+
+ Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
+ if (typeof console !== 'undefined' && console) {
+ console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
+ }
+ };
+
+ /**
+ * Set the immediate function to execute callbacks
+ * @param fn {function} Function to execute
+ * @deprecated
+ */
+ Promise._setImmediateFn = function _setImmediateFn(fn) {
+ Promise._immediateFn = fn;
+ };
+
+ /**
+ * Change the function to execute on unhandled rejection
+ * @param {function} fn Function to execute on unhandled rejection
+ * @deprecated
+ */
+ Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
+ Promise._unhandledRejectionFn = fn;
+ };
+
+ if (typeof module !== 'undefined' && module.exports) {
+ module.exports = Promise;
+ } else if (!root.Promise) {
+ root.Promise = Promise;
+ }
+
+})(this);
+
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24).setImmediate))
+
+/***/ }),
+/* 23 */
+/***/ (function(module, exports, __webpack_require__) {
+
+/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
+ "use strict";
+
+ if (global.setImmediate) {
+ return;
+ }
+
+ var nextHandle = 1; // Spec says greater than zero
+ var tasksByHandle = {};
+ var currentlyRunningATask = false;
+ var doc = global.document;
+ var registerImmediate;
+
+ function setImmediate(callback) {
+ // Callback can either be a function or a string
+ if (typeof callback !== "function") {
+ callback = new Function("" + callback);
+ }
+ // Copy function arguments
+ var args = new Array(arguments.length - 1);
+ for (var i = 0; i < args.length; i++) {
+ args[i] = arguments[i + 1];
+ }
+ // Store and register the task
+ var task = { callback: callback, args: args };
+ tasksByHandle[nextHandle] = task;
+ registerImmediate(nextHandle);
+ return nextHandle++;
+ }
+
+ function clearImmediate(handle) {
+ delete tasksByHandle[handle];
+ }
+
+ function run(task) {
+ var callback = task.callback;
+ var args = task.args;
+ switch (args.length) {
+ case 0:
+ callback();
+ break;
+ case 1:
+ callback(args[0]);
+ break;
+ case 2:
+ callback(args[0], args[1]);
+ break;
+ case 3:
+ callback(args[0], args[1], args[2]);
+ break;
+ default:
+ callback.apply(undefined, args);
+ break;
+ }
+ }
+
+ function runIfPresent(handle) {
+ // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
+ // So if we're currently running a task, we'll need to delay this invocation.
+ if (currentlyRunningATask) {
+ // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
+ // "too much recursion" error.
+ setTimeout(runIfPresent, 0, handle);
+ } else {
+ var task = tasksByHandle[handle];
+ if (task) {
+ currentlyRunningATask = true;
+ try {
+ run(task);
+ } finally {
+ clearImmediate(handle);
+ currentlyRunningATask = false;
+ }
+ }
+ }
+ }
+
+ function installNextTickImplementation() {
+ registerImmediate = function(handle) {
+ process.nextTick(function () { runIfPresent(handle); });
+ };
+ }
+
+ function canUsePostMessage() {
+ // The test against `importScripts` prevents this implementation from being installed inside a web worker,
+ // where `global.postMessage` means something completely different and can't be used for this purpose.
+ if (global.postMessage && !global.importScripts) {
+ var postMessageIsAsynchronous = true;
+ var oldOnMessage = global.onmessage;
+ global.onmessage = function() {
+ postMessageIsAsynchronous = false;
+ };
+ global.postMessage("", "*");
+ global.onmessage = oldOnMessage;
+ return postMessageIsAsynchronous;
+ }
+ }
+
+ function installPostMessageImplementation() {
+ // Installs an event handler on `global` for the `message` event: see
+ // * https://developer.mozilla.org/en/DOM/window.postMessage
+ // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
+
+ var messagePrefix = "setImmediate$" + Math.random() + "$";
+ var onGlobalMessage = function(event) {
+ if (event.source === global &&
+ typeof event.data === "string" &&
+ event.data.indexOf(messagePrefix) === 0) {
+ runIfPresent(+event.data.slice(messagePrefix.length));
+ }
+ };
+
+ if (global.addEventListener) {
+ global.addEventListener("message", onGlobalMessage, false);
+ } else {
+ global.attachEvent("onmessage", onGlobalMessage);
+ }
+
+ registerImmediate = function(handle) {
+ global.postMessage(messagePrefix + handle, "*");
+ };
+ }
+
+ function installMessageChannelImplementation() {
+ var channel = new MessageChannel();
+ channel.port1.onmessage = function(event) {
+ var handle = event.data;
+ runIfPresent(handle);
+ };
+
+ registerImmediate = function(handle) {
+ channel.port2.postMessage(handle);
+ };
+ }
+
+ function installReadyStateChangeImplementation() {
+ var html = doc.documentElement;
+ registerImmediate = function(handle) {
+ // Create a
+
+
\ No newline at end of file
diff --git a/test/index.js b/test/index.js
new file mode 100644
index 0000000..87f1fb8
--- /dev/null
+++ b/test/index.js
@@ -0,0 +1,133 @@
+import Vue from 'vue'
+import VueRouter from 'vue-router'
+import VueResource from 'vue-resource' // Comment for axios example
+
+// import axios from 'axios' // Uncomment for axios example
+// import VueAxios from 'vue-axios' // Uncomment for axios example
+
+import VueAuthenticate from '../src/index.js'
+
+Vue.use(VueRouter)
+Vue.use(VueResource) // Comment for axios example
+
+// Vue.use(VueAxios, axios) // Uncomment for axios example
+
+Vue.use(VueAuthenticate, {})
+
+const router = new VueRouter({
+ mode: 'history',
+ routes: [
+ {
+ path: '/',
+ name: 'index',
+ component: {
+ data: function () {
+ return {
+ response: null
+ }
+ },
+ template: `
+
+
+
+
+
+
+
+
+
+
+
{{JSON.stringify(response, null, 2)}}
+
+ `,
+ methods: {
+ authLogin: function() {
+ let user = {
+ email: 'john.doe@domain.com',
+ password: 'pass123456'
+ };
+
+ if (this.$auth.isAuthenticated()) {
+ this.$auth.logout()
+ }
+
+ this.$auth.login(user).then((response) => {
+ this.response = response
+ console.log(this.$auth.isAuthenticated())
+ console.log(this.$auth.getPayload())
+ })
+ },
+
+ authRegister: function() {
+ let user = {
+ name: 'John Doe',
+ email: 'john.doe@domain.com',
+ password: 'pass123456'
+ };
+
+ if (this.$auth.isAuthenticated()) {
+ this.$auth.logout()
+ }
+
+ this.$auth.register(user).then((response) => {
+ this.response = response
+ console.log(this.$auth.isAuthenticated())
+ console.log(this.$auth.getPayload())
+ })
+ },
+
+ authLogout: function() {
+ this.$auth.logout().then(() => {
+ if (!this.$auth.isAuthenticated()) {
+ this.response = null
+ } else {
+ console.log(this.$auth.isAuthenticated())
+ }
+ })
+ },
+
+ auth: function(provider) {
+ this.$auth.logout()
+ this.response = null
+
+ console.log('User authenticated: ', this.$auth.isAuthenticated())
+
+ this.$auth.authenticate(provider).then((authResponse) => {
+ if (provider === 'github') {
+ this.$http.get('https://api.github.com/user').then((response) => {
+ this.response = response
+ })
+ } else if (provider === 'facebook') {
+ this.$http.get('https://graph.facebook.com/v2.5/me', {
+ params: { access_token: this.$auth.getToken() }
+ }).then((response) => {
+ this.response = response
+ })
+ } else if (provider === 'google') {
+ this.$http.get('https://www.googleapis.com/plus/v1/people/me/openIdConnect').then((response) => {
+ this.response = response
+ })
+ } else if (provider === 'twitter') {
+ this.response = authResponse.body.profile
+ }
+ })
+ }
+ }
+ }
+ },
+
+ {
+ path: '/auth/callback',
+ component: {
+ template: '',
+ mounted: function () {
+
+ }
+ }
+ }
+ ]
+})
+
+const app = new Vue({
+ router
+}).$mount('#app')
\ No newline at end of file
diff --git a/test/server.js b/test/server.js
new file mode 100644
index 0000000..e8b3e81
--- /dev/null
+++ b/test/server.js
@@ -0,0 +1,217 @@
+var express = require('express')
+var bodyParser = require('body-parser')
+var Axios = require('axios')
+var Request = require('request')
+var cors = require('cors')
+var config = require('./config.json')
+var OAuth = require('oauth')
+var timestamp = require('unix-timestamp')
+var oauthSignature = require('oauth-signature')
+
+var app = express()
+app.use(cors())
+app.use(bodyParser.json())
+// app.use(allowCrossDomain);
+
+app.get('/', function (req, res) {
+ res.send('vue-authenticate')
+})
+
+app.post('/auth/:provider', function(req, res){
+ switch(req.params.provider) {
+ case 'github':
+ githubAuth(req, res)
+ break
+ case 'facebook':
+ facebookAuth(req, res)
+ break
+ case 'google':
+ googleAuth(req, res)
+ break
+ case 'twitter':
+ twitterAuth(req, res)
+ break
+ case 'login':
+ loginAuth(req, res)
+ break
+ case 'register':
+ registerAuth(req, res)
+ break
+ }
+});
+
+app.listen(4000);
+
+function allowCrossDomain(req, res, next) {
+ res.header('Access-Control-Allow-Origin', '*');
+ res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
+ res.header('Access-Control-Allow-Headers', 'Content-Type');
+ next();
+}
+
+function loginAuth(req, res) {
+ res.json({
+ id: 1,
+ name: 'John Doe',
+ email: 'john.doe@domain.com',
+ created_at: new Date(),
+
+ token: 'eyJpZCI6MSwiZW1haWwiOiJqb2huLmRvZUBkb21haW4uY29tIiwibmFtZSI6IkpvaG4gRG9lIiwiYWxnIjoiSFMyNTYifQ.eyJpZCI6MSwiZW1haWwiOiJqb2huLmRvZUBkb21haW4uY29tIiwibmFtZSI6IkpvaG4gRG9lIn0.CyXHbjCBjA4uLuOwefCGbFw1ulQtF-QfS9-X0fFUCGE'
+
+ })
+}
+
+function registerAuth(req, res) {
+ res.json({
+ id: 1,
+ name: 'John Doe',
+ email: 'john.doe@domain.com',
+ created_at: new Date(),
+
+ token: 'eyJpZCI6MSwiZW1haWwiOiJqb2huLmRvZUBkb21haW4uY29tIiwibmFtZSI6IkpvaG4gRG9lIiwiYWxnIjoiSFMyNTYifQ.eyJpZCI6MSwiZW1haWwiOiJqb2huLmRvZUBkb21haW4uY29tIiwibmFtZSI6IkpvaG4gRG9lIn0.CyXHbjCBjA4uLuOwefCGbFw1ulQtF-QfS9-X0fFUCGE'
+
+ })
+}
+
+function githubAuth(req, res) {
+ Axios.post('https://github.com/login/oauth/access_token', {
+ client_id: config.auth.github.clientId,
+ client_secret: config.auth.github.clientSecret,
+ code: req.body.code,
+ redirect_uri: req.body.redirectUri,
+ state: req.body.state,
+ grant_type: 'authorization_code'
+ }, { 'Content-Type': 'application/json' }).then(function (response) {
+ var responseJson = parseQueryString(response.data)
+ if (responseJson.error) {
+ res.status(500).json({ error: responseJson.error })
+ } else {
+ res.json(responseJson)
+ }
+ }).catch(function (err) {
+ res.status(500).json(err)
+ })
+}
+
+function facebookAuth(req, res) {
+ Axios.post('https://graph.facebook.com/v2.4/oauth/access_token', {
+ client_id: config.auth.facebook.clientId,
+ client_secret: config.auth.facebook.clientSecret,
+ code: req.body.code,
+ redirect_uri: req.body.redirectUri
+ }, { 'Content-Type': 'application/json' }).then(function (response) {
+ var responseJson = response.data
+ res.json(responseJson)
+ }).catch(function (err) {
+ res.status(500).json(err)
+ })
+}
+
+function googleAuth(req, res) {
+ Request({
+ method: 'post',
+ url: 'https://accounts.google.com/o/oauth2/token',
+ form: {
+ code: req.body.code,
+ client_id: config.auth.google.clientId,
+ client_secret: config.auth.google.clientSecret,
+ redirect_uri: req.body.redirectUri,
+ grant_type: 'authorization_code'
+ },
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded'
+ }
+ }, function (err, response, body) {
+ try {
+ if (!err && response.statusCode === 200) {
+ var responseJson = JSON.parse(body)
+ res.json(responseJson)
+ } else {
+ res.status(response.statusCode).json(err)
+ }
+ } catch (e) {
+ res.status(500).json(err || e)
+ }
+ })
+}
+
+oauthService = new OAuth.OAuth(
+ 'https://api.twitter.com/oauth/request_token',
+ 'https://api.twitter.com/oauth/access_token',
+ config.auth.twitter.clientId,
+ config.auth.twitter.clientSecret,
+ '1.0A',
+ null,
+ 'HMAC-SHA1'
+)
+
+function twitterAuth(req, res) {
+ if (!req.body.oauth_token) {
+ oauthService.getOAuthRequestToken({ oauth_callback: req.body.redirectUri }, function (error, oauthToken, oauthTokenSecret, results) {
+ if (error) {
+ res.status(500).json(error)
+ } else {
+ res.json({
+ oauth_token: oauthToken,
+ oauth_token_secret: oauthTokenSecret
+ })
+ }
+ })
+ } else {
+ oauthService.getOAuthAccessToken(req.body.oauth_token, null, req.body.oauth_verifier, function (error, oauthAccessToken, oauthAccessTokenSecret, results) {
+
+ if (error) {
+ res.status(500).json(error)
+ } else {
+ var verifyCredentialsUrl = 'https://api.twitter.com/1.1/account/verify_credentials.json'
+ var parameters = {
+ oauth_consumer_key: config.auth.twitter.clientId,
+ oauth_token: oauthAccessToken,
+ oauth_nonce: ('vueauth-' + new Date().getTime()),
+ oauth_timestamp: timestamp.now(),
+ oauth_signature_method: 'HMAC-SHA1',
+ oauth_version: '1.0'
+ }
+
+ var signature = oauthSignature.generate('GET', verifyCredentialsUrl, parameters, config.auth.twitter.clientSecret, oauthAccessTokenSecret)
+
+ Axios.get('https://api.twitter.com/1.1/account/verify_credentials.json', {
+ headers: {
+ Authorization: 'OAuth ' +
+ 'oauth_consumer_key="' + config.auth.twitter.clientId + '",' +
+ 'oauth_token="' + oauthAccessToken + '",' +
+ 'oauth_nonce="' + parameters.oauth_nonce + '",' +
+ 'oauth_timestamp="' + parameters.oauth_timestamp + '",' +
+ 'oauth_signature_method="HMAC-SHA1",'+
+ 'oauth_version="1.0",' +
+ 'oauth_signature="' + signature + '"'
+ }
+ }).then(function (response) {
+ res.json({
+ access_token: oauthAccessToken,
+ access_token_secret: oauthAccessTokenSecret,
+
+ profile: response.data
+ })
+ }).catch(function (err) {
+ console.log(err.response.data.errors)
+ res.status(500).json(err.response.data.errors)
+ })
+ }
+ })
+ }
+}
+
+function parseQueryString(str) {
+ let obj = {};
+ let key;
+ let value;
+ (str || '').split('&').forEach((keyValue) => {
+ if (keyValue) {
+ value = keyValue.split('=');
+ key = decodeURIComponent(value[0]);
+ obj[key] = (!!value[1]) ? decodeURIComponent(value[1]) : true;
+ }
+ });
+ return obj;
+}
\ No newline at end of file
diff --git a/test/webpack.config.js b/test/webpack.config.js
new file mode 100644
index 0000000..4a0c337
--- /dev/null
+++ b/test/webpack.config.js
@@ -0,0 +1,23 @@
+module.exports = {
+ entry: __dirname + '/index.js',
+ output: {
+ path: __dirname + '/',
+ filename: 'index.bundle.js'
+ },
+ module: {
+ rules: [
+ {
+ test: /\.js$/,
+ exclude: /(node_modules|bower_components)/,
+ use: {
+ loader: 'babel-loader'
+ }
+ }
+ ]
+ },
+ resolve: {
+ alias: {
+ vue: 'vue/dist/vue.common.js'
+ }
+ }
+};
\ No newline at end of file
diff --git a/webpack.config.js b/webpack.config.js
new file mode 100644
index 0000000..aba7fda
--- /dev/null
+++ b/webpack.config.js
@@ -0,0 +1,18 @@
+module.exports = {
+ entry: __dirname + '/src/index.js',
+ output: {
+ path: __dirname + '/dist',
+ filename: 'vue-authenticate.min.js'
+ },
+ module: {
+ rules: [
+ {
+ test: /\.js$/,
+ exclude: /(node_modules|bower_components)/,
+ use: {
+ loader: 'babel-loader'
+ }
+ }
+ ]
+ }
+};
\ No newline at end of file